From c20b720fcc2037df2474d8c98fa73772fddd81fa Mon Sep 17 00:00:00 2001
From: Rochet2
Date: Wed, 7 Dec 2016 10:52:57 +0200
Subject: [PATCH 01/86] Implement oauth2
---
pom.xml | 5 +
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 4 +
.../TmcServerCommunicationTaskFactory.java | 151 +++++++++++-------
.../tmc/core/communication/oauth2/Oauth.java | 59 +++++++
.../core/communication/oauth2/OauthFlow.java | 21 +++
.../communication/oauth2/PasswordFlow.java | 48 ++++++
.../tmc/core/configuration/TmcSettings.java | 6 +
.../cs/tmc/core/holders/TmcOauthHolder.java | 23 +++
.../cs/tmc/core/commands/RunTestsTest.java | 4 +
.../core/communication/oauth2/OauthTest.java | 64 ++++++++
.../tmc/core/holders/TmcOauthHolderTest.java | 37 +++++
11 files changed, 366 insertions(+), 56 deletions(-)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthFlow.java
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/PasswordFlow.java
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/holders/TmcOauthHolder.java
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/holders/TmcOauthHolderTest.java
diff --git a/pom.xml b/pom.xml
index 8c02cb3c..16186961 100644
--- a/pom.xml
+++ b/pom.xml
@@ -402,6 +402,11 @@
tmc-junit-runner
0.2.5
+
+ org.apache.oltu.oauth2
+ org.apache.oltu.oauth2.client
+ 1.0.2
+
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 9173f73c..b65d04e9 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -17,6 +17,8 @@
import fi.helsinki.cs.tmc.core.commands.SendSpywareEvents;
import fi.helsinki.cs.tmc.core.commands.Submit;
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
+import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
+import fi.helsinki.cs.tmc.core.communication.oauth2.PasswordFlow;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
@@ -25,6 +27,7 @@
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.domain.submission.SubmissionResult;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
+import fi.helsinki.cs.tmc.core.holders.TmcOauthHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utilities.ExceptionTrackingCallable;
import fi.helsinki.cs.tmc.langs.abstraction.ValidationResult;
@@ -72,6 +75,7 @@ public TmcCore() {}
public TmcCore(TmcSettings settings, TaskExecutor tmcLangs) {
TmcSettingsHolder.set(settings);
TmcLangsHolder.set(tmcLangs);
+ TmcOauthHolder.set(new Oauth(new PasswordFlow(settings)));
}
public Callable sendDiagnostics(
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 02d9fcd7..ad8d703d 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -2,6 +2,7 @@
import fi.helsinki.cs.tmc.core.communication.http.HttpTasks;
import fi.helsinki.cs.tmc.core.communication.http.UriUtils;
+import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
import fi.helsinki.cs.tmc.core.communication.serialization.ByteArrayGsonSerializer;
import fi.helsinki.cs.tmc.core.communication.serialization.CourseInfoParser;
import fi.helsinki.cs.tmc.core.communication.serialization.CourseListParser;
@@ -13,6 +14,7 @@
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.exceptions.FailedHttpResponseException;
import fi.helsinki.cs.tmc.core.exceptions.ObsoleteClientException;
+import fi.helsinki.cs.tmc.core.holders.TmcOauthHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utilities.JsonMaker;
import fi.helsinki.cs.tmc.core.utilities.JsonMakerGsonSerializer;
@@ -23,6 +25,8 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
+import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
+import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -35,6 +39,8 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
/**
@@ -43,27 +49,33 @@
public class TmcServerCommunicationTaskFactory {
public static final int API_VERSION = 7;
+ private static final Logger LOG = Logger.getLogger(
+ TmcServerCommunicationTaskFactory.class.getName());
private TmcSettings settings;
+ private Oauth oauth;
private CourseListParser courseListParser;
private CourseInfoParser courseInfoParser;
private ReviewListParser reviewListParser;
private String clientVersion;
public TmcServerCommunicationTaskFactory() {
- this(TmcSettingsHolder.get());
+ this(TmcSettingsHolder.get(), TmcOauthHolder.get());
}
- public TmcServerCommunicationTaskFactory(TmcSettings settings) {
- this(settings, new CourseListParser(), new CourseInfoParser(), new ReviewListParser());
+ public TmcServerCommunicationTaskFactory(TmcSettings settings, Oauth oauth) {
+ this(settings, oauth, new CourseListParser(),
+ new CourseInfoParser(), new ReviewListParser());
}
public TmcServerCommunicationTaskFactory(
TmcSettings settings,
+ Oauth oauth,
CourseListParser courseListParser,
CourseInfoParser courseInfoParser,
ReviewListParser reviewListParser) {
this.settings = settings;
+ this.oauth = oauth;
this.courseListParser = courseListParser;
this.courseInfoParser = courseInfoParser;
this.reviewListParser = reviewListParser;
@@ -78,7 +90,33 @@ public void setSettings(TmcSettings settings) {
this.settings = settings;
}
- private URI getCourseListUrl() {
+ /**
+ * Returns a Callable that calls the given Callable.
+ *
+ *
+ * If the call fails once, the oauth token is refreshed and the call is done again.
+ *
+ * @param return type of the callable
+ * @param callable Callable to be wrapped
+ * @return The given Callable wrapped in another Callable
+ */
+ private Callable wrapWithTokenRefresh(final Callable callable) {
+ return new Callable() {
+ @Override
+ public T call() throws Exception {
+ try {
+ return callable.call();
+ } catch (FailedHttpResponseException e) {
+ LOG.log(Level.INFO,
+ "Callable call failed, refreshing oauth token and trying again");
+ oauth.refreshToken();
+ return callable.call();
+ }
+ }
+ };
+ }
+
+ private URI getCourseListUrl() throws OAuthSystemException, OAuthProblemException {
String serverAddress = settings.getServerAddress();
String url;
if (serverAddress.endsWith("/")) {
@@ -89,10 +127,12 @@ private URI getCourseListUrl() {
return addApiCallQueryParameters(URI.create(url));
}
- private URI addApiCallQueryParameters(URI url) {
+ private URI addApiCallQueryParameters(URI url) throws OAuthSystemException,
+ OAuthProblemException {
url = UriUtils.withQueryParam(url, "api_version", "" + API_VERSION);
url = UriUtils.withQueryParam(url, "client", settings.clientName());
url = UriUtils.withQueryParam(url, "client_version", clientVersion);
+ url = UriUtils.withQueryParam(url, "access_token", oauth.getToken());
return url;
}
@@ -113,11 +153,11 @@ public boolean needsOnlyPassword() {
}
public Callable> getDownloadingCourseListTask() {
- final Callable download = createHttpTasks().getForText(getCourseListUrl());
- return new Callable>() {
+ return wrapWithTokenRefresh(new Callable>() {
@Override
public List call() throws Exception {
try {
+ Callable download = createHttpTasks().getForText(getCourseListUrl());
String text = download.call();
return courseListParser.parseFromJson(text);
} catch (FailedHttpResponseException ex) {
@@ -125,16 +165,16 @@ public List call() throws Exception {
}
//TODO: Cancellable?
}
- };
+ });
}
- public Callable getFullCourseInfoTask(Course courseStub) {
- URI url = addApiCallQueryParameters(courseStub.getDetailsUrl());
- final Callable download = createHttpTasks().getForText(url);
- return new Callable() {
+ public Callable getFullCourseInfoTask(final Course courseStub) {
+ return wrapWithTokenRefresh(new Callable() {
@Override
public Course call() throws Exception {
try {
+ URI url = addApiCallQueryParameters(courseStub.getDetailsUrl());
+ final Callable download = createHttpTasks().getForText(url);
String text = download.call();
return courseInfoParser.parseFromJson(text);
} catch (FailedHttpResponseException ex) {
@@ -143,17 +183,17 @@ public Course call() throws Exception {
}
//TODO: Cancellable?
- };
+ });
}
- public Callable getUnlockingTask(Course course) {
- Map params = Collections.emptyMap();
- final Callable download =
- createHttpTasks().postForText(getUnlockUrl(course), params);
- return new Callable() {
+ public Callable getUnlockingTask(final Course course) {
+ final Map params = Collections.emptyMap();
+ return wrapWithTokenRefresh(new Callable() {
@Override
public Void call() throws Exception {
try {
+ final Callable download = createHttpTasks()
+ .postForText(getUnlockUrl(course), params);
download.call();
return null;
} catch (FailedHttpResponseException ex) {
@@ -162,10 +202,10 @@ public Void call() throws Exception {
}
//TODO: Cancellable?
- };
+ });
}
- private URI getUnlockUrl(Course course) {
+ private URI getUnlockUrl(Course course) throws OAuthSystemException, OAuthProblemException {
return addApiCallQueryParameters(course.getUnlockUrl());
}
@@ -181,23 +221,21 @@ public Callable getDownloadingExerciseSolutionZipTask(Exercise exercise)
public Callable getSubmittingExerciseTask(
final Exercise exercise, final byte[] sourceZip, Map extraParams) {
- final URI submitUrl = addApiCallQueryParameters(exercise.getReturnUrl());
- Map params = new LinkedHashMap<>();
+ final Map params = new LinkedHashMap<>();
params.put("client_time", "" + (System.currentTimeMillis() / 1000L));
params.put("client_nanotime", "" + System.nanoTime());
params.putAll(extraParams);
- final Callable upload =
- createHttpTasks()
- .uploadFileForTextDownload(
- submitUrl, params, "submission[file]", sourceZip);
-
- return new Callable() {
+ return wrapWithTokenRefresh(new Callable() {
@Override
public SubmissionResponse call() throws Exception {
String response;
try {
+ final URI submitUrl = addApiCallQueryParameters(exercise.getReturnUrl());
+ final Callable upload = createHttpTasks()
+ .uploadFileForTextDownload(submitUrl, params,
+ "submission[file]", sourceZip);
response = upload.call();
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
@@ -222,7 +260,7 @@ public SubmissionResponse call() throws Exception {
}
//TODO: Cancellable?
- };
+ });
}
public static class SubmissionResponse {
@@ -240,13 +278,13 @@ public Callable getSubmissionFetchTask(URI submissionUrl) {
return createHttpTasks().getForText(submissionUrl);
}
- public Callable> getDownloadingReviewListTask(Course course) {
- URI url = addApiCallQueryParameters(course.getReviewsUrl());
- final Callable download = createHttpTasks().getForText(url);
- return new Callable>() {
+ public Callable> getDownloadingReviewListTask(final Course course) {
+ return wrapWithTokenRefresh(new Callable>() {
@Override
public List call() throws Exception {
try {
+ URI url = addApiCallQueryParameters(course.getReviewsUrl());
+ final Callable download = createHttpTasks().getForText(url);
String text = download.call();
return reviewListParser.parseFromJson(text);
} catch (FailedHttpResponseException ex) {
@@ -255,12 +293,11 @@ public List call() throws Exception {
}
//TODO: Cancellable?
- };
+ });
}
- public Callable getMarkingReviewAsReadTask(Review review, boolean read) {
- URI url = addApiCallQueryParameters(URI.create(review.getUpdateUrl() + ".json"));
- Map params = new HashMap<>();
+ public Callable getMarkingReviewAsReadTask(final Review review, boolean read) {
+ final Map params = new HashMap<>();
params.put("_method", "put");
if (read) {
params.put("mark_as_read", "1");
@@ -268,22 +305,22 @@ public Callable getMarkingReviewAsReadTask(Review review, boolean read) {
params.put("mark_as_unread", "1");
}
- final Callable task = createHttpTasks().postForText(url, params);
- return new Callable() {
+ return wrapWithTokenRefresh(new Callable() {
@Override
public Void call() throws Exception {
+ URI url = addApiCallQueryParameters(URI.create(review.getUpdateUrl() + ".json"));
+ final Callable task = createHttpTasks().postForText(url, params);
task.call();
return null;
}
//TODO: Cancellable?
- };
+ });
}
- public Callable getFeedbackAnsweringJob(URI answerUrl, List answers) {
- final URI submitUrl = addApiCallQueryParameters(answerUrl);
-
- Map params = new HashMap<>();
+ public Callable getFeedbackAnsweringJob(final URI answerUrl,
+ List answers) {
+ final Map params = new HashMap<>();
for (int i = 0; i < answers.size(); ++i) {
String keyPrefix = "answers[" + i + "]";
FeedbackAnswer answer = answers.get(i);
@@ -291,12 +328,13 @@ public Callable getFeedbackAnsweringJob(URI answerUrl, List upload = createHttpTasks().postForText(submitUrl, params);
-
- return new Callable() {
+ return wrapWithTokenRefresh(new Callable() {
@Override
public String call() throws Exception {
try {
+ final URI submitUrl = addApiCallQueryParameters(answerUrl);
+ final Callable upload = createHttpTasks()
+ .postForText(submitUrl, params);
return upload.call();
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
@@ -304,35 +342,36 @@ public String call() throws Exception {
}
//TODO: Cancellable?
- };
+ });
}
- public Callable
*
* @return oauth token
- * @throws org.apache.oltu.oauth2.common.exception.OAuthSystemException an error occurred with
- * getting token
- * @throws org.apache.oltu.oauth2.common.exception.OAuthProblemException an error occurred with
- * getting token
+ * @throws TmcCoreException when an oauth token hasn't been fetched yet
*/
- public String getToken() throws OAuthSystemException, OAuthProblemException {
- if (flow == null) {
- throw new OAuthSystemException("Oauth flow is null");
- }
+ public String getToken() throws NotLoggedInException {
if (!hasToken()) {
- token = flow.getToken();
+ throw new NotLoggedInException();
}
- return token;
+ return settings.getToken().get();
}
/**
@@ -53,35 +60,36 @@ public String getToken() throws OAuthSystemException, OAuthProblemException {
* @return has token
*/
public boolean hasToken() {
- return token != null;
+ return settings.getToken().isPresent();
}
/**
- * Returns the oauth token.
- *
- *
- * Uses the known flow to fetch the token and caches it.
- *
- * @return oauth token
- * @throws org.apache.oltu.oauth2.common.exception.OAuthSystemException an error occurred with
- * getting token
- * @throws org.apache.oltu.oauth2.common.exception.OAuthProblemException an error occurred with
- * getting token
+ * Fetches a new oauth token from server using settings' parameters in request.
+ * @param password for fetching correct token
+ * @throws OAuthSystemException an error occurred with getting token
+ * @throws OAuthProblemException an error occurred with getting token
*/
- public String refreshToken() throws OAuthSystemException, OAuthProblemException {
- if (flow == null) {
- throw new OAuthSystemException("Oauth flow is null");
- }
- token = flow.getToken();
- return token;
+ public void fetchNewToken(String password) throws OAuthSystemException, OAuthProblemException {
+ log.info("Fetching new oauth token from server");
+ OAuthClientRequest request = OAuthClientRequest
+ .tokenLocation(settings.getOauthTokenUrl())
+ .setGrantType(GrantType.PASSWORD)
+ .setClientId(settings.getOauthApplicationId())
+ .setClientSecret(settings.getOauthSecret())
+ .setUsername(settings.getUsername())
+ .setPassword(password)
+ .buildQueryMessage();
+ OAuthClient client = new OAuthClient(new URLConnectionClient());
+ String token = client.accessToken(request, OAuthJSONAccessTokenResponse.class)
+ .getAccessToken();
+ setToken(token);
}
-
+
/**
- * Changes the oauth flow.
- *
- * @param authflow an oauth flow
+ * Sets given oauth token to TmcSettings.
+ * @param token to be set to settings
*/
- public void setFlow(OauthFlow authflow) {
- this.flow = authflow;
+ private void setToken(String token) {
+ settings.setToken(token);
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthFlow.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthFlow.java
deleted file mode 100644
index 047552e0..00000000
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthFlow.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package fi.helsinki.cs.tmc.core.communication.oauth2;
-
-import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
-import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
-
-/**
- * An interface for an oauth flow.
- */
-public interface OauthFlow {
-
- /**
- * Uses the flow to get a token from the server.
- *
- * @return a oauth token
- * @throws org.apache.oltu.oauth2.common.exception.OAuthSystemException an error occurred with
- * getting token
- * @throws org.apache.oltu.oauth2.common.exception.OAuthProblemException an error occurred with
- * getting token
- */
- public String getToken() throws OAuthSystemException, OAuthProblemException;
-}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/PasswordFlow.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/PasswordFlow.java
deleted file mode 100644
index 4311440c..00000000
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/PasswordFlow.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package fi.helsinki.cs.tmc.core.communication.oauth2;
-
-import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
-
-import org.apache.oltu.oauth2.client.OAuthClient;
-import org.apache.oltu.oauth2.client.URLConnectionClient;
-import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
-import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
-import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
-import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
-import org.apache.oltu.oauth2.common.message.types.GrantType;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * A password flow for oauth.
- *
- *
- * Password flow fetches the token from server by using username and password
- */
-public class PasswordFlow implements OauthFlow {
-
- private static final Logger LOG = Logger.getLogger(PasswordFlow.class.getName());
- private final TmcSettings settings;
-
- public PasswordFlow(TmcSettings settings) {
- this.settings = settings;
- }
-
- @Override
- public String getToken() throws OAuthSystemException, OAuthProblemException {
- LOG.log(Level.INFO, "Fetching new oauth token from server");
- OAuthClientRequest request = OAuthClientRequest
- .tokenLocation(settings.getOauthTokenUrl())
- .setGrantType(GrantType.PASSWORD)
- .setClientId(settings.getOauthApplicationId())
- .setClientSecret(settings.getOauthSecret())
- .setUsername(settings.getUsername())
- .setPassword(settings.getPassword())
- .buildQueryMessage();
- OAuthClient client = new OAuthClient(new URLConnectionClient());
- String token = client.accessToken(request, OAuthJSONAccessTokenResponse.class)
- .getAccessToken();
- return token;
- }
-
-}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index 8f76c59e..fc0b0ee5 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -14,7 +14,12 @@ public interface TmcSettings {
String getServerAddress();
- String getPassword();
+ /**
+ * Used for old login credentials, new ones use oauth.
+ */
+ Optional getPassword();
+
+ void setPassword(Optional password);
String getUsername();
@@ -64,4 +69,8 @@ public interface TmcSettings {
String getOauthApplicationId();
String getOauthSecret();
+
+ void setToken(String token);
+
+ Optional getToken();
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/exceptions/AuthenticationFailedException.java b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/AuthenticationFailedException.java
new file mode 100644
index 00000000..928b14b7
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/AuthenticationFailedException.java
@@ -0,0 +1,8 @@
+package fi.helsinki.cs.tmc.core.exceptions;
+
+public class AuthenticationFailedException extends TmcCoreException {
+
+ public AuthenticationFailedException(Exception ex) {
+ super("Authentication failed!", ex);
+ }
+}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/exceptions/NotLoggedInException.java b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/NotLoggedInException.java
new file mode 100644
index 00000000..e82b9a0e
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/NotLoggedInException.java
@@ -0,0 +1,8 @@
+package fi.helsinki.cs.tmc.core.exceptions;
+
+public class NotLoggedInException extends TmcCoreException {
+
+ public NotLoggedInException() {
+ super("Not logged in!");
+ }
+}
diff --git a/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java b/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
index b08e3a36..ae01a451 100644
--- a/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
+++ b/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
@@ -4,6 +4,7 @@
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utilities.Cooldown;
import fi.helsinki.cs.tmc.core.utilities.SingletonTask;
@@ -220,8 +221,13 @@ public void run() {
"Sending {0} events to {1}",
new Object[] {eventsToSend.size(), url});
- if (!tryToSend(eventsToSend, url)) {
- shouldSendMore = false;
+ try {
+ if (!tryToSend(eventsToSend, url)) {
+ shouldSendMore = false;
+ }
+ } catch (NotLoggedInException e) {
+ throw new RuntimeException(
+ "Could not send analytics because not logged in.", e);
}
} while (shouldSendMore);
}
@@ -257,7 +263,8 @@ private URI pickDestinationUrl() {
return urls.get(random.nextInt(urls.size()));
}
- private boolean tryToSend(final ArrayList eventsToSend, final URI url) {
+ private boolean tryToSend(final ArrayList eventsToSend, final URI url)
+ throws NotLoggedInException {
Callable task = serverAccess.getSendEventLogJob(url, eventsToSend);
// TODO: Should we still wrap this into bg task (future)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
new file mode 100644
index 00000000..08a28232
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
@@ -0,0 +1,68 @@
+package fi.helsinki.cs.tmc.core.commands;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doAnswer;
+
+import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.exceptions.AuthenticationFailedException;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
+
+import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
+import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+public class AuthenticateUserTest {
+ @Mock
+ ProgressObserver mockObserver;
+
+ TmcSettings settings;
+ @Mock
+ Oauth oauth;
+
+ private Command command;
+
+ @Before
+ public void setUp() throws OAuthProblemException, OAuthSystemException {
+ MockitoAnnotations.initMocks(this);
+ settings = new MockSettings();
+ TmcSettingsHolder.set(settings);
+ doAnswer(new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+ settings.setToken("testToken");
+ return null;
+ }
+ }).when(oauth).fetchNewToken("password");
+ doAnswer(new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+ throw new OAuthSystemException();
+ }
+ }).when(oauth).fetchNewToken("wrongPassword");
+ }
+
+ @Test
+ public void testCallSucceeds() throws Exception {
+ command = new AuthenticateUser(mockObserver, "password", oauth);
+ command.call();
+ assertTrue(settings.getToken().isPresent());
+ assertEquals(settings.getToken().get(), "testToken");
+ }
+
+ @Test(expected = AuthenticationFailedException.class)
+ public void testCallFails() throws Exception {
+ command = new AuthenticateUser(mockObserver, "wrongPassword", oauth);
+ command.call();
+ }
+}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java
index 051d3c1e..d2de1915 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java
@@ -6,8 +6,6 @@
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
-import fi.helsinki.cs.tmc.core.communication.oauth2.PasswordFlow;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthMock.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthMock.java
deleted file mode 100644
index 05b417c1..00000000
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthMock.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package fi.helsinki.cs.tmc.core.communication.oauth2;
-
-class OauthMock extends Oauth {
- public OauthMock() {
- super();
- }
-}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
index 0739d83e..4cce45fe 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
@@ -4,62 +4,71 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
+
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
+
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mock;
+
import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.lang.reflect.Field;
public class OauthTest {
- private Oauth oauth;
+ private TmcSettings settings;
- @Mock
- private OauthFlow flow;
+ private Oauth oauth;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- when(flow.getToken()).thenReturn("one", "two");
- this.oauth = new OauthMock();
- this.oauth.setFlow(flow);
+ settings = new MockSettings();
+ TmcSettingsHolder.set(settings);
+ oauth = spy(Oauth.getInstance());
+ doAnswer(new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+ settings.setToken("testToken");
+ return null;
+ }
+ }).when(oauth).fetchNewToken(anyString());
}
- @Test
- public void hasNoTokenWhenInitialized() throws Exception {
- assertFalse(oauth.hasToken());
- verify(flow, times(0)).getToken();
+ @After
+ public void tearDown() throws NoSuchFieldException, IllegalAccessException {
+ Field oauth = Oauth.class.getDeclaredField("oauth");
+ oauth.setAccessible(true);
+ oauth.set(null, null);
}
@Test
- public void hasTokenWhenFetchedAndCallsFlow() {
+ public void hasTokenWhenFetched() {
try {
- String token = oauth.getToken();
- verify(flow).getToken();
+ oauth.fetchNewToken("password");
assertTrue(oauth.hasToken());
- assertEquals("one", token);
+ assertEquals("testToken", settings.getToken().get());
} catch (OAuthSystemException | OAuthProblemException ex) {
fail("Got exception: " + ex.toString());
}
}
@Test
- public void refreshTokenCallsFlowAndGetsNewToken() {
- try {
- String token = oauth.getToken();
- assertEquals("one", token);
- verify(flow, times(1)).getToken();
- String token2 = oauth.refreshToken();
- assertEquals("two", token2);
- verify(flow, times(2)).getToken();
- assertTrue(oauth.hasToken());
- } catch (OAuthSystemException | OAuthProblemException ex) {
- fail("Got exception: " + ex.toString());
- }
+ public void hasNoTokenWhenInitialized() throws Exception {
+ assertFalse(oauth.hasToken());
+ verify(oauth, times(0)).fetchNewToken(anyString());
}
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java b/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
index 594543a7..a639c0b8 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
@@ -13,6 +13,7 @@
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.spyware.EventSendBuffer;
import fi.helsinki.cs.tmc.spyware.EventStore;
@@ -65,7 +66,7 @@ public class EventSendBufferTest {
private EventSendBuffer sender;
@Before
- public void setUp() throws IOException {
+ public void setUp() throws IOException, NotLoggedInException {
MockitoAnnotations.initMocks(this);
TmcSettingsHolder.set(tmcSettings);
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
new file mode 100644
index 00000000..285edf89
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -0,0 +1,125 @@
+package fi.helsinki.cs.tmc.core.utils;
+
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Course;
+
+import com.google.common.base.Optional;
+
+import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
+
+import java.nio.file.Path;
+import java.util.Locale;
+
+public class MockSettings implements TmcSettings {
+
+ private Optional token;
+
+ public MockSettings() {
+ token = Optional.absent();
+ }
+
+ @Override
+ public String getServerAddress() {
+ return null;
+ }
+
+ @Override
+ public Optional getPassword() {
+ return null;
+ }
+
+ @Override
+ public void setPassword(Optional password) {
+
+ }
+
+ @Override
+ public String getUsername() {
+ return null;
+ }
+
+ @Override
+ public boolean userDataExists() {
+ return false;
+ }
+
+ @Override
+ public Optional getCurrentCourse() {
+ return null;
+ }
+
+ @Override
+ public String apiVersion() {
+ return null;
+ }
+
+ @Override
+ public String clientName() {
+ return null;
+ }
+
+ @Override
+ public String clientVersion() {
+ return null;
+ }
+
+ @Override
+ public String getFormattedUserData() {
+ return null;
+ }
+
+ @Override
+ public Path getTmcProjectDirectory() {
+ return null;
+ }
+
+ @Override
+ public Locale getLocale() {
+ return null;
+ }
+
+ @Override
+ public SystemDefaultRoutePlanner proxy() {
+ return null;
+ }
+
+ @Override
+ public void setCourse(Course theCourse) {
+
+ }
+
+ @Override
+ public void setConfigRoot(Path configRoot) {
+
+ }
+
+ @Override
+ public Path getConfigRoot() {
+ return null;
+ }
+
+ @Override
+ public String getOauthTokenUrl() {
+ return null;
+ }
+
+ @Override
+ public String getOauthApplicationId() {
+ return null;
+ }
+
+ @Override
+ public String getOauthSecret() {
+ return null;
+ }
+
+ @Override
+ public void setToken(String token) {
+ this.token = Optional.of(token);
+ }
+
+ @Override
+ public Optional getToken() {
+ return token;
+ }
+}
From e5631a3e82f77bc381cf63f55aa6597b46bb006a Mon Sep 17 00:00:00 2001
From: Antti
Date: Mon, 6 Feb 2017 12:21:21 +0200
Subject: [PATCH 05/86] Tests for core commands and few refactorings
---
.../commands/AbstractSubmissionCommand.java | 4 +
.../tmc/core/commands/GetCourseDetails.java | 4 +
.../cs/tmc/core/commands/ListCourses.java | 4 +
.../TmcServerCommunicationTaskFactory.java | 22 ++--
.../cs/tmc/spyware/EventSendBuffer.java | 11 +-
.../fi/helsinki/cs/tmc/core/TmcCoreTest.java | 122 ++++++++++++++++++
.../cs/tmc/core/utils/MockSettings.java | 31 ++---
7 files changed, 163 insertions(+), 35 deletions(-)
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/TmcCoreTest.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/AbstractSubmissionCommand.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/AbstractSubmissionCommand.java
index af2125bc..06173271 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/AbstractSubmissionCommand.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/AbstractSubmissionCommand.java
@@ -3,6 +3,7 @@
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.exceptions.TmcCoreException;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
@@ -71,6 +72,9 @@ TmcServerCommunicationTaskFactory.SubmissionResponse submitToServer(
return response;
} catch (Exception ex) {
+ if (ex instanceof NotLoggedInException) {
+ throw (NotLoggedInException)ex;
+ }
informObserver(1, "Failed to submit exercise");
logger.warn("Failed to submit exercise", ex);
throw new TmcCoreException("Failed to submit exercise", ex);
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetails.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetails.java
index 2da3908f..40bf7e98 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetails.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetails.java
@@ -3,6 +3,7 @@
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.exceptions.TmcCoreException;
import com.google.common.annotations.VisibleForTesting;
@@ -46,6 +47,9 @@ public Course call() throws TmcCoreException, URISyntaxException {
informObserver(1, "Course refresh completed successfully");
return result;
} catch (Exception ex) {
+ if (ex instanceof NotLoggedInException) {
+ throw (NotLoggedInException)ex;
+ }
logger.warn("Failed to get course details for course " + course.getName(), ex);
informObserver(1, "Failed to refresh course");
throw new TmcCoreException("Failed to get course details", ex);
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/ListCourses.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/ListCourses.java
index 32cf5fa3..5a8803c1 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/ListCourses.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/ListCourses.java
@@ -3,6 +3,7 @@
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.exceptions.TmcCoreException;
import fi.helsinki.cs.tmc.core.utilities.ServerErrorHelper;
@@ -43,6 +44,9 @@ public List call() throws TmcCoreException {
logger.debug("Successfully fetched course list");
return result;
} catch (Exception ex) {
+ if (ex instanceof NotLoggedInException) {
+ throw (NotLoggedInException)ex;
+ }
logger.info("Failed to fetch courses from the server", ex);
informObserver(1, "Failed to fetch courses from the server");
throw new TmcCoreException("Failed to fetch courses from the server. \n"
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 0f177348..9b8d00fe 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -100,7 +100,7 @@ public void setSettings(TmcSettings settings) {
* @param callable Callable to be wrapped
* @return The given Callable wrapped in another Callable
*/
- private Callable wrapWithTokenRefresh(final Callable callable) {
+ private Callable wrapWithNotLoggedInException(final Callable callable) {
return new Callable() {
@Override
public T call() throws Exception {
@@ -120,9 +120,9 @@ private URI getCourseListUrl()
String serverAddress = settings.getServerAddress();
String url;
if (serverAddress.endsWith("/")) {
- url = settings.getServerAddress() + "courses.json";
+ url = serverAddress + "courses.json";
} else {
- url = settings.getServerAddress() + "/courses.json";
+ url = serverAddress + "/courses.json";
}
return addApiCallQueryParameters(URI.create(url));
}
@@ -137,7 +137,7 @@ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
}
public Callable> getDownloadingCourseListTask() {
- return wrapWithTokenRefresh(new Callable>() {
+ return wrapWithNotLoggedInException(new Callable>() {
@Override
public List call() throws Exception {
try {
@@ -153,7 +153,7 @@ public List call() throws Exception {
}
public Callable getFullCourseInfoTask(final Course courseStub) {
- return wrapWithTokenRefresh(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
public Course call() throws Exception {
try {
@@ -172,7 +172,7 @@ public Course call() throws Exception {
public Callable getUnlockingTask(final Course course) {
final Map params = Collections.emptyMap();
- return wrapWithTokenRefresh(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
public Void call() throws Exception {
try {
@@ -211,7 +211,7 @@ public Callable getSubmittingExerciseTask(
params.put("client_nanotime", "" + System.nanoTime());
params.putAll(extraParams);
- return wrapWithTokenRefresh(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
public SubmissionResponse call() throws Exception {
String response;
@@ -263,7 +263,7 @@ public Callable getSubmissionFetchTask(URI submissionUrl) {
}
public Callable> getDownloadingReviewListTask(final Course course) {
- return wrapWithTokenRefresh(new Callable>() {
+ return wrapWithNotLoggedInException(new Callable>() {
@Override
public List call() throws Exception {
try {
@@ -289,7 +289,7 @@ public Callable getMarkingReviewAsReadTask(final Review review, boolean re
params.put("mark_as_unread", "1");
}
- return wrapWithTokenRefresh(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
public Void call() throws Exception {
URI url = addApiCallQueryParameters(URI.create(review.getUpdateUrl() + ".json"));
@@ -312,7 +312,7 @@ public Callable getFeedbackAnsweringJob(final URI answerUrl,
params.put(keyPrefix + "[answer]", answer.getAnswer());
}
- return wrapWithTokenRefresh(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
public String call() throws Exception {
try {
@@ -343,7 +343,7 @@ public Callable getSendEventLogJob(final URI spywareServerUrl,
throw new RuntimeException(e);
}
- return wrapWithTokenRefresh(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
public Object call() throws Exception {
URI url = addApiCallQueryParameters(spywareServerUrl);
diff --git a/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java b/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
index ae01a451..678734d7 100644
--- a/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
+++ b/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
@@ -221,14 +221,9 @@ public void run() {
"Sending {0} events to {1}",
new Object[] {eventsToSend.size(), url});
- try {
if (!tryToSend(eventsToSend, url)) {
shouldSendMore = false;
}
- } catch (NotLoggedInException e) {
- throw new RuntimeException(
- "Could not send analytics because not logged in.", e);
- }
} while (shouldSendMore);
}
@@ -263,13 +258,11 @@ private URI pickDestinationUrl() {
return urls.get(random.nextInt(urls.size()));
}
- private boolean tryToSend(final ArrayList eventsToSend, final URI url)
- throws NotLoggedInException {
- Callable task = serverAccess.getSendEventLogJob(url, eventsToSend);
-
+ private boolean tryToSend(final ArrayList eventsToSend, final URI url) {
// TODO: Should we still wrap this into bg task (future)
try {
+ Callable task = serverAccess.getSendEventLogJob(url, eventsToSend);
task.call();
} catch (Exception ex) {
log.log(Level.INFO, "Sending failed", ex);
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/TmcCoreTest.java b/src/test/java/fi/helsinki/cs/tmc/core/TmcCoreTest.java
new file mode 100644
index 00000000..40ffcae0
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/TmcCoreTest.java
@@ -0,0 +1,122 @@
+package fi.helsinki.cs.tmc.core;
+
+import static org.mockito.Mockito.doReturn;
+
+import fi.helsinki.cs.tmc.core.commands.GetCourseDetails;
+import fi.helsinki.cs.tmc.core.commands.GetUnreadReviews;
+import fi.helsinki.cs.tmc.core.commands.ListCourses;
+import fi.helsinki.cs.tmc.core.commands.MarkReviewAsRead;
+import fi.helsinki.cs.tmc.core.commands.SendFeedback;
+import fi.helsinki.cs.tmc.core.commands.SendSpywareEvents;
+import fi.helsinki.cs.tmc.core.commands.Submit;
+import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.domain.Review;
+import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
+import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
+import fi.helsinki.cs.tmc.spyware.LoggableEvent;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
+import java.lang.reflect.Field;
+import java.net.URI;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+public class TmcCoreTest {
+
+ @Mock
+ ProgressObserver observer;
+
+ @Spy
+ Course course = new Course();
+
+ @Mock
+ Review review;
+
+ @Mock
+ Exercise exercise;
+
+ @Spy
+ TmcSettings settings = new MockSettings();
+
+ @Mock
+ TaskExecutor tmcLangs;
+
+ @Mock
+ Path path;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ TmcSettingsHolder.set(settings);
+ TmcLangsHolder.set(tmcLangs);
+ Locale locale = new Locale("a", "b", "c");
+ doReturn(URI.create("testUrl")).when(course).getReviewsUrl();
+ doReturn(URI.create("testUrl")).when(course).getDetailsUrl();
+ doReturn(path).when(settings).getTmcProjectDirectory();
+ doReturn(locale).when(settings).getLocale();
+ doReturn(URI.create("testUrl")).when(exercise).getReturnUrl();
+ }
+
+ @After
+ public void tearDown() throws NoSuchFieldException, IllegalAccessException {
+ Field oauth = Oauth.class.getDeclaredField("oauth");
+ oauth.setAccessible(true);
+ oauth.set(null, null);
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandListCoursesThrowsNotLoggedInExceptionWhenHasNoToken() throws Exception {
+ new ListCourses(observer).call();
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandGetUnreadReviewsThrowsNotLoggedInExceptionWhenHasNoToken() throws Exception {
+ new GetUnreadReviews(observer, course).call();
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandSendFeedbackThrowsNotLoggedInExceptionWhenHasNoToken() throws Exception {
+ new SendFeedback(observer, new ArrayList(), new URI("test")).call();
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandGetCourseDetailsThrowsNotLoggedInExceptionWhenHasNoToken() throws Exception {
+ new GetCourseDetails(observer, course).call();
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandMarkReviewsAsReadThrowsNotLoggedInExceptionWhenHasNoToken()
+ throws Exception {
+ new MarkReviewAsRead(observer, review).call();
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandSendSpywareEventsThrowsNotLoggedInExceptionWhenHasNoToken()
+ throws Exception {
+ List spywareUrls = new ArrayList<>();
+ spywareUrls.add(URI.create("test"));
+ course.setSpywareUrls(spywareUrls);
+ new SendSpywareEvents(observer, course, new ArrayList()).call();
+ }
+
+ @Test (expected = NotLoggedInException.class)
+ public void commandSubmitThrowsNotLoggedInExceptionWhenHasNoToken() throws Exception {
+ new Submit(observer, exercise).call();
+ }
+}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index 285edf89..ec14433a 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -7,6 +7,7 @@
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
+import java.lang.UnsupportedOperationException;
import java.nio.file.Path;
import java.util.Locale;
@@ -20,12 +21,12 @@ public MockSettings() {
@Override
public String getServerAddress() {
- return null;
+ return "testAddress";
}
@Override
public Optional getPassword() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
@@ -35,7 +36,7 @@ public void setPassword(Optional password) {
@Override
public String getUsername() {
- return null;
+ return "testUsername";
}
@Override
@@ -45,42 +46,42 @@ public boolean userDataExists() {
@Override
public Optional getCurrentCourse() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public String apiVersion() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public String clientName() {
- return null;
+ return "testClient";
}
@Override
public String clientVersion() {
- return null;
+ return "testClient";
}
@Override
public String getFormattedUserData() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public Path getTmcProjectDirectory() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public Locale getLocale() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public SystemDefaultRoutePlanner proxy() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
@@ -95,22 +96,22 @@ public void setConfigRoot(Path configRoot) {
@Override
public Path getConfigRoot() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public String getOauthTokenUrl() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public String getOauthApplicationId() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
public String getOauthSecret() {
- return null;
+ throw new UnsupportedOperationException();
}
@Override
From d4582a36502687791e4dc049fff2288e05b04b95 Mon Sep 17 00:00:00 2001
From: Antti
Date: Mon, 6 Feb 2017 13:56:12 +0200
Subject: [PATCH 06/86] Settings password migration
---
.../tmc/core/holders/TmcSettingsHolder.java | 26 +++++++++++++++++++
.../DownloadOrUpdateExercisesTest.java | 4 ++-
.../core/commands/GetCourseDetailsTest.java | 4 ++-
.../commands/GetUpdatableExercisesTest.java | 4 ++-
.../cs/tmc/core/commands/ListCoursesTest.java | 5 +++-
.../core/commands/PasteWithCommentTest.java | 4 ++-
.../tmc/core/commands/RunCheckstyleTest.java | 4 ++-
.../cs/tmc/core/commands/RunTestsTest.java | 4 ++-
.../tmc/core/commands/SendFeedbackTest.java | 5 ++--
.../cs/tmc/core/commands/SubmitTest.java | 5 ++--
.../http/HttpRequestExecutorTest.java | 9 ++++---
.../core/holders/TmcSettingsHolderTest.java | 5 ++--
.../tmc/core/spyware/EventSendBufferTest.java | 4 ++-
.../cs/tmc/core/utils/MockSettings.java | 10 +++----
14 files changed, 70 insertions(+), 23 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolder.java b/src/main/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolder.java
index ddf01629..d646f6d1 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolder.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolder.java
@@ -1,12 +1,23 @@
package fi.helsinki.cs.tmc.core.holders;
+import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.exceptions.UninitializedHolderException;
+import com.google.common.base.Optional;
+
+import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
+import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public final class TmcSettingsHolder {
private static TmcSettings settings;
+ private static final Logger logger = LoggerFactory.getLogger(TmcSettingsHolder.class);
+
private TmcSettingsHolder() {}
public static synchronized TmcSettings get() {
@@ -18,5 +29,20 @@ public static synchronized TmcSettings get() {
public static synchronized void set(TmcSettings settings) {
TmcSettingsHolder.settings = settings;
+ if (settings != null) {
+ migrateOldSettings();
+ }
+ }
+ // TODO delete at some point
+ private static void migrateOldSettings() {
+ try {
+ Optional password = settings.getPassword();
+ if (password.isPresent()) {
+ Oauth.getInstance().fetchNewToken(password.get());
+ settings.setPassword(Optional.absent());
+ }
+ } catch (OAuthSystemException | OAuthProblemException e) {
+ logger.warn("Settings migration failed.");
+ }
}
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java
index af246ed8..cbe6c043 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java
@@ -18,6 +18,7 @@
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.core.utils.TestUtils;
import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
@@ -31,6 +32,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -42,7 +44,7 @@ public class DownloadOrUpdateExercisesTest {
@Rule public TemporaryFolder testFolder = new TemporaryFolder();
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course mockCourse;
@Mock Exercise mockExerciseOne;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java
index ba215e7e..af5b4230 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java
@@ -9,19 +9,21 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.util.concurrent.Callable;
public class GetCourseDetailsTest {
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course mockCourse;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java
index c5c0c669..b9858c73 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java
@@ -15,6 +15,7 @@
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
@@ -27,6 +28,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.nio.file.Path;
import java.util.concurrent.Callable;
@@ -36,7 +38,7 @@ public class GetUpdatableExercisesTest {
@Rule public TemporaryFolder testFolder = new TemporaryFolder();
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course mockCurrentCourse;
@Mock Course mockRefreshedCourse;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java
index a0518c9e..392f29a9 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java
@@ -9,13 +9,16 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import com.google.common.collect.ImmutableList;
import org.junit.Before;
import org.junit.Test;
+
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.util.List;
import java.util.concurrent.Callable;
@@ -23,7 +26,7 @@
public class ListCoursesTest {
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course courseOne;
@Mock Course courseTwo;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java
index 2fddeeb2..1c863044 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java
@@ -14,6 +14,7 @@
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.core.utils.TestUtils;
import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
@@ -25,6 +26,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.net.URI;
import java.nio.file.Path;
@@ -37,7 +39,7 @@ public class PasteWithCommentTest {
@Rule public TemporaryFolder testFolder = new TemporaryFolder();
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course mockCourse;
@Mock Exercise mockExercise;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/RunCheckstyleTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/RunCheckstyleTest.java
index d60bf695..a6e63195 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/RunCheckstyleTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/RunCheckstyleTest.java
@@ -12,6 +12,7 @@
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.core.utils.TestUtils;
import fi.helsinki.cs.tmc.langs.abstraction.ValidationResult;
import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
@@ -24,6 +25,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.nio.file.Path;
import java.util.Locale;
@@ -33,7 +35,7 @@ public class RunCheckstyleTest {
@Rule public TemporaryFolder testFolder = new TemporaryFolder();
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock Course mockCourse;
@Mock Exercise mockExercise;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java
index d2de1915..41eb925f 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/RunTestsTest.java
@@ -12,6 +12,7 @@
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.core.utils.TestUtils;
import fi.helsinki.cs.tmc.langs.domain.RunResult.Status;
import fi.helsinki.cs.tmc.langs.domain.RunResult;
@@ -25,6 +26,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.nio.file.Path;
@@ -34,7 +36,7 @@ public class RunTestsTest {
Path project;
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock Course mockCourse;
@Mock Exercise mockExercise;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java
index 9ac26f43..46874ed8 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java
@@ -3,7 +3,6 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@@ -15,6 +14,7 @@
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackQuestion;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import com.google.common.collect.ImmutableList;
@@ -25,6 +25,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.net.URI;
import java.util.List;
@@ -35,7 +36,7 @@ public class SendFeedbackTest {
@Rule public TemporaryFolder testFolder = new TemporaryFolder();
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course mockCourse;
@Mock Exercise mockExercise;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java
index d202c7e3..9042ab77 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java
@@ -2,7 +2,6 @@
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verifyZeroInteractions;
@@ -17,6 +16,7 @@
import fi.helsinki.cs.tmc.core.domain.submission.SubmissionResult;
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.core.utils.TestUtils;
import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
@@ -28,6 +28,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.net.URI;
import java.nio.file.Path;
@@ -40,7 +41,7 @@ public class SubmitTest {
@Rule public TemporaryFolder testFolder = new TemporaryFolder();
@Mock ProgressObserver mockObserver;
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock Course mockCourse;
@Mock Exercise mockExercise;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutorTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutorTest.java
index ac03d277..d6d3b886 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutorTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutorTest.java
@@ -6,10 +6,10 @@
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
@@ -23,15 +23,15 @@
import org.junit.Rule;
import org.junit.Test;
-import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.net.URI;
import java.nio.charset.Charset;
public class HttpRequestExecutorTest {
- @Mock TmcSettings settings;
+ @Spy TmcSettings settings = new MockSettings();
@Rule public WireMockRule wireMockRule = new WireMockRule(0);
@@ -39,7 +39,8 @@ public class HttpRequestExecutorTest {
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
TmcSettingsHolder.set(settings);
- verifyNoMoreInteractions(settings);
+// TODO uncomment this after removing migration from TmcSettingsHolder
+// verifyNoMoreInteractions(settings);
wireMockRule.start();
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolderTest.java b/src/test/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolderTest.java
index 3830c6ad..7f650cc3 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolderTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/holders/TmcSettingsHolderTest.java
@@ -4,18 +4,19 @@
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.exceptions.UninitializedHolderException;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
public class TmcSettingsHolderTest {
private TmcSettingsHolder holder;
- @Mock private TmcSettings settings;
+ @Spy private TmcSettings settings = new MockSettings();
@Before
public void setUp() {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java b/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
index a639c0b8..5263551e 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
@@ -15,6 +15,7 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import fi.helsinki.cs.tmc.spyware.EventSendBuffer;
import fi.helsinki.cs.tmc.spyware.EventStore;
import fi.helsinki.cs.tmc.spyware.LoggableEvent;
@@ -30,6 +31,7 @@
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
import java.io.IOException;
import java.net.URI;
@@ -46,7 +48,7 @@ public class EventSendBufferTest {
private Course mockCourse;
- @Mock TmcSettings tmcSettings;
+ @Spy TmcSettings tmcSettings = new MockSettings();
@Mock TmcServerCommunicationTaskFactory factory;
@Mock private SpywareSettings settings;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index ec14433a..9b78fb25 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -26,7 +26,7 @@ public String getServerAddress() {
@Override
public Optional getPassword() {
- throw new UnsupportedOperationException();
+ return Optional.absent();
}
@Override
@@ -46,7 +46,7 @@ public boolean userDataExists() {
@Override
public Optional getCurrentCourse() {
- throw new UnsupportedOperationException();
+ return null;
}
@Override
@@ -71,17 +71,17 @@ public String getFormattedUserData() {
@Override
public Path getTmcProjectDirectory() {
- throw new UnsupportedOperationException();
+ return null;
}
@Override
public Locale getLocale() {
- throw new UnsupportedOperationException();
+ return null;
}
@Override
public SystemDefaultRoutePlanner proxy() {
- throw new UnsupportedOperationException();
+ return null;
}
@Override
From a1afa9499338694a2dbe488411a0ba1e92372d93 Mon Sep 17 00:00:00 2001
From: Antti
Date: Thu, 16 Feb 2017 16:43:29 +0200
Subject: [PATCH 07/86] New oauth stuff
---
pom.xml | 2 +-
.../TmcServerCommunicationTaskFactory.java | 7 ++++
.../tmc/core/configuration/TmcSettings.java | 4 +++
.../cs/tmc/core/domain/OauthCredentials.java | 33 +++++++++++++++++++
4 files changed, 45 insertions(+), 1 deletion(-)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
diff --git a/pom.xml b/pom.xml
index 16186961..7ea9584c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -3,7 +3,7 @@
fi.helsinki.cs.tmc
core
- 0.9.12-SNAPSHOT
+ 0.10.0-SNAPSHOT
jar
tmc-core
http://testmycode.net
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 9b8d00fe..cdc3515f 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -10,6 +10,7 @@
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
import fi.helsinki.cs.tmc.core.domain.Review;
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.exceptions.FailedHttpResponseException;
@@ -25,6 +26,8 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
+import java.net.MalformedURLException;
+import org.apache.commons.io.IOUtils;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
@@ -357,6 +360,10 @@ public Object call() throws Exception {
});
}
+ public Callable getOauthCredentialsTask(URI credentialsUrl) throws IOException {
+ OauthCredentials credentials = new Gson().fromJson(IOUtils.toString(credentialsUrl.toURL()), OauthCredentials.class);
+ }
+
private byte[] eventListToPostBody(List events) throws IOException {
ByteArrayOutputStream bufferBos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(bufferBos);
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index fc0b0ee5..9e093d8b 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -68,8 +68,12 @@ public interface TmcSettings {
String getOauthApplicationId();
+ void setOauthApplicationId(String oauthApplicationId);
+
String getOauthSecret();
+ void setOauthSecret(String oauthSecret);
+
void setToken(String token);
Optional getToken();
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java b/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
new file mode 100644
index 00000000..c85d7ac8
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
@@ -0,0 +1,33 @@
+package fi.helsinki.cs.tmc.core.domain;
+
+import com.google.gson.annotations.SerializedName;
+import java.io.Serializable;
+
+public class OauthCredentials implements Serializable {
+
+ @SerializedName("application_id")
+ private String oauthApplicationId;
+
+ @SerializedName("secret")
+ private String oauthSecret;
+
+ public OauthCredentials() {
+
+ }
+
+ public void setOauthApplicationId(String oauthApplicationId) {
+ this.oauthApplicationId = oauthApplicationId;
+ }
+
+ public String getOauthApplicationId() {
+ return oauthApplicationId;
+ }
+
+ public void setOauthSecret(String oauthSecret) {
+ this.oauthSecret = oauthSecret;
+ }
+
+ public String getOauthSecret() {
+ return oauthSecret;
+ }
+}
From 3b7a402f2e751dc62f399b12956f6a1c8f691d32 Mon Sep 17 00:00:00 2001
From: Antti Leinonen
Date: Fri, 24 Feb 2017 16:57:26 +0200
Subject: [PATCH 08/86] Continued oauth stuff
---
.../cs/tmc/core/commands/AuthenticateUser.java | 5 ++++-
.../TmcServerCommunicationTaskFactory.java | 12 +++++++++---
.../cs/tmc/core/configuration/TmcSettings.java | 2 --
.../cs/tmc/core/domain/OauthCredentials.java | 1 +
.../fi/helsinki/cs/tmc/core/utils/MockSettings.java | 10 ++++++++++
5 files changed, 24 insertions(+), 6 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java
index c22476bd..7eb9bb99 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java
@@ -9,6 +9,8 @@
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
+import java.io.IOException;
+
public class AuthenticateUser extends Command {
private String password;
private final Oauth oauth;
@@ -23,8 +25,9 @@ public AuthenticateUser(ProgressObserver observer, String password, Oauth oauth)
public Void call() throws AuthenticationFailedException {
TmcSettings tmcSettings = TmcSettingsHolder.get();
try {
+ tmcServerCommunicationTaskFactory.getOauthCredentialsTask();
oauth.fetchNewToken(password);
- } catch (OAuthSystemException | OAuthProblemException e) {
+ } catch (OAuthSystemException | OAuthProblemException | IOException e) {
throw new AuthenticationFailedException(e);
}
return null;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index cdc3515f..3dcf3d8d 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -26,7 +26,7 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
-import java.net.MalformedURLException;
+
import org.apache.commons.io.IOUtils;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
@@ -360,8 +360,14 @@ public Object call() throws Exception {
});
}
- public Callable getOauthCredentialsTask(URI credentialsUrl) throws IOException {
- OauthCredentials credentials = new Gson().fromJson(IOUtils.toString(credentialsUrl.toURL()), OauthCredentials.class);
+ public Callable getOauthCredentialsTask() throws IOException {
+ URI credentialsUrl = URI.create(
+ settings.getServerAddress() + "/api/v" + API_VERSION
+ + "/application/" + settings.clientName() + "credentials");
+ OauthCredentials credentials =
+ new Gson().fromJson(
+ IOUtils.toString(credentialsUrl.toURL()), OauthCredentials.class);
+ return null;
}
private byte[] eventListToPostBody(List events) throws IOException {
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index 9e093d8b..1838b05d 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -30,8 +30,6 @@ public interface TmcSettings {
Optional getCurrentCourse();
- String apiVersion();
-
String clientName();
String clientVersion();
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java b/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
index c85d7ac8..ec81a7dd 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
@@ -1,6 +1,7 @@
package fi.helsinki.cs.tmc.core.domain;
import com.google.gson.annotations.SerializedName;
+
import java.io.Serializable;
public class OauthCredentials implements Serializable {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index 9b78fb25..938c67c6 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -109,11 +109,21 @@ public String getOauthApplicationId() {
throw new UnsupportedOperationException();
}
+ @Override
+ public void setOauthApplicationId(String oauthApplicationId) {
+
+ }
+
@Override
public String getOauthSecret() {
throw new UnsupportedOperationException();
}
+ @Override
+ public void setOauthSecret(String oauthSecret) {
+
+ }
+
@Override
public void setToken(String token) {
this.token = Optional.of(token);
From aa0419552994fb3e32a82c2e3db37374fa4f814f Mon Sep 17 00:00:00 2001
From: Antti Leinonen
Date: Tue, 28 Feb 2017 13:14:55 +0200
Subject: [PATCH 09/86] Fix tests
---
.../cs/tmc/core/commands/AuthenticateUser.java | 11 +++++++++++
.../TmcServerCommunicationTaskFactory.java | 11 +++++++++--
.../tmc/core/commands/AuthenticateUserTest.java | 15 ++++++++++++---
.../tmc/core/communication/oauth2/OauthTest.java | 2 +-
.../helsinki/cs/tmc/core/utils/MockSettings.java | 5 -----
5 files changed, 33 insertions(+), 11 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java
index 7eb9bb99..88b1d4fe 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUser.java
@@ -1,11 +1,14 @@
package fi.helsinki.cs.tmc.core.commands;
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.exceptions.AuthenticationFailedException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import com.google.common.annotations.VisibleForTesting;
+
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
@@ -21,6 +24,14 @@ public AuthenticateUser(ProgressObserver observer, String password, Oauth oauth)
this.oauth = oauth;
}
+ @VisibleForTesting
+ AuthenticateUser(ProgressObserver observer, String password, Oauth oauth,
+ TmcServerCommunicationTaskFactory tmcServerCommunicationTaskFactory) {
+ super(observer, tmcServerCommunicationTaskFactory);
+ this.password = password;
+ this.oauth = oauth;
+ }
+
@Override
public Void call() throws AuthenticationFailedException {
TmcSettings tmcSettings = TmcSettingsHolder.get();
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 3dcf3d8d..35999791 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -361,9 +361,16 @@ public Object call() throws Exception {
}
public Callable getOauthCredentialsTask() throws IOException {
- URI credentialsUrl = URI.create(
+ URI credentialsUrl;
+ if (settings.getServerAddress().endsWith("/")) {
+ credentialsUrl = URI.create(
+ settings.getServerAddress() + "api/v" + API_VERSION
+ + "/application/" + settings.clientName() + "/credentials");
+ } else {
+ credentialsUrl = URI.create(
settings.getServerAddress() + "/api/v" + API_VERSION
- + "/application/" + settings.clientName() + "credentials");
+ + "/application/" + settings.clientName() + "/credentials");
+ }
OauthCredentials credentials =
new Gson().fromJson(
IOUtils.toString(credentialsUrl.toURL()), OauthCredentials.class);
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
index 08a28232..d0775c4b 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
@@ -3,7 +3,9 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.when;
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
@@ -22,6 +24,8 @@
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import java.io.IOException;
+
public class AuthenticateUserTest {
@Mock
ProgressObserver mockObserver;
@@ -29,11 +33,13 @@ public class AuthenticateUserTest {
TmcSettings settings;
@Mock
Oauth oauth;
+ @Mock
+ TmcServerCommunicationTaskFactory tmcServerCommunicationTaskFactory;
private Command command;
@Before
- public void setUp() throws OAuthProblemException, OAuthSystemException {
+ public void setUp() throws OAuthProblemException, OAuthSystemException, IOException {
MockitoAnnotations.initMocks(this);
settings = new MockSettings();
TmcSettingsHolder.set(settings);
@@ -50,11 +56,13 @@ public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
throw new OAuthSystemException();
}
}).when(oauth).fetchNewToken("wrongPassword");
+ when(tmcServerCommunicationTaskFactory.getOauthCredentialsTask()).thenReturn(null);
}
@Test
public void testCallSucceeds() throws Exception {
- command = new AuthenticateUser(mockObserver, "password", oauth);
+ command = new AuthenticateUser(mockObserver, "password",
+ oauth, tmcServerCommunicationTaskFactory);
command.call();
assertTrue(settings.getToken().isPresent());
assertEquals(settings.getToken().get(), "testToken");
@@ -62,7 +70,8 @@ public void testCallSucceeds() throws Exception {
@Test(expected = AuthenticationFailedException.class)
public void testCallFails() throws Exception {
- command = new AuthenticateUser(mockObserver, "wrongPassword", oauth);
+ command = new AuthenticateUser(mockObserver, "wrongPassword",
+ oauth, tmcServerCommunicationTaskFactory);
command.call();
}
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
index 4cce45fe..c397b976 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
@@ -38,7 +38,7 @@ public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
settings = new MockSettings();
TmcSettingsHolder.set(settings);
- oauth = spy(Oauth.getInstance());
+ oauth = spy(new Oauth());
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index 938c67c6..dc5c74aa 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -49,11 +49,6 @@ public Optional getCurrentCourse() {
return null;
}
- @Override
- public String apiVersion() {
- throw new UnsupportedOperationException();
- }
-
@Override
public String clientName() {
return "testClient";
From c7641f321a84c74564aabddbc0727b0610f59422 Mon Sep 17 00:00:00 2001
From: Antti Leinonen
Date: Wed, 1 Mar 2017 15:35:33 +0200
Subject: [PATCH 10/86] Remove OauthTokenUrl from TmcSettings and add few tests
---
.../tmc/core/communication/oauth2/Oauth.java | 18 +++++++++---------
.../cs/tmc/core/configuration/TmcSettings.java | 2 --
.../core/commands/AuthenticateUserTest.java | 10 ++++++++++
.../core/communication/oauth2/OauthTest.java | 13 ++++++++++---
.../cs/tmc/core/utils/MockSettings.java | 5 -----
5 files changed, 29 insertions(+), 19 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
index 66429338..eb23c0c4 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
@@ -71,8 +71,16 @@ public boolean hasToken() {
*/
public void fetchNewToken(String password) throws OAuthSystemException, OAuthProblemException {
log.info("Fetching new oauth token from server");
+
+ String oauthTokenUrl;
+ if (settings.getServerAddress().endsWith("/")) {
+ oauthTokenUrl = settings.getServerAddress() + "oauth/token";
+ } else {
+ oauthTokenUrl = settings.getServerAddress() + "/oauth/token";
+ }
+
OAuthClientRequest request = OAuthClientRequest
- .tokenLocation(settings.getOauthTokenUrl())
+ .tokenLocation(oauthTokenUrl)
.setGrantType(GrantType.PASSWORD)
.setClientId(settings.getOauthApplicationId())
.setClientSecret(settings.getOauthSecret())
@@ -82,14 +90,6 @@ public void fetchNewToken(String password) throws OAuthSystemException, OAuthPro
OAuthClient client = new OAuthClient(new URLConnectionClient());
String token = client.accessToken(request, OAuthJSONAccessTokenResponse.class)
.getAccessToken();
- setToken(token);
- }
-
- /**
- * Sets given oauth token to TmcSettings.
- * @param token to be set to settings
- */
- private void setToken(String token) {
settings.setToken(token);
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index 1838b05d..40bcd9d3 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -62,8 +62,6 @@ public interface TmcSettings {
boolean getSendDiagnostics();
- String getOauthTokenUrl();
-
String getOauthApplicationId();
void setOauthApplicationId(String oauthApplicationId);
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
index d0775c4b..1333678a 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
@@ -3,6 +3,8 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
@@ -74,4 +76,12 @@ public void testCallFails() throws Exception {
oauth, tmcServerCommunicationTaskFactory);
command.call();
}
+
+ @Test
+ public void callsTmcServerCommunicationTaskFactorysGetOauthCredentialsTask() throws Exception {
+ command = new AuthenticateUser(mockObserver, "password",
+ oauth, tmcServerCommunicationTaskFactory);
+ command.call();
+ verify(tmcServerCommunicationTaskFactory, times(1)).getOauthCredentialsTask();
+ }
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
index c397b976..8c3ddebd 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
@@ -11,6 +11,7 @@
import static org.mockito.Mockito.verify;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utils.MockSettings;
@@ -36,7 +37,7 @@ public class OauthTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- settings = new MockSettings();
+ settings = spy(new MockSettings());
TmcSettingsHolder.set(settings);
oauth = spy(new Oauth());
doAnswer(new Answer() {
@@ -56,11 +57,11 @@ public void tearDown() throws NoSuchFieldException, IllegalAccessException {
}
@Test
- public void hasTokenWhenFetched() {
+ public void hasTokenWhenFetched() throws NotLoggedInException {
try {
oauth.fetchNewToken("password");
assertTrue(oauth.hasToken());
- assertEquals("testToken", settings.getToken().get());
+ assertEquals("testToken", oauth.getToken());
} catch (OAuthSystemException | OAuthProblemException ex) {
fail("Got exception: " + ex.toString());
}
@@ -71,4 +72,10 @@ public void hasNoTokenWhenInitialized() throws Exception {
assertFalse(oauth.hasToken());
verify(oauth, times(0)).fetchNewToken(anyString());
}
+
+ @Test
+ public void setsTokenToSettings() throws OAuthProblemException, OAuthSystemException {
+ oauth.fetchNewToken("password");
+ verify(settings, times(1)).setToken(anyString());
+ }
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index dc5c74aa..470d0b79 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -94,11 +94,6 @@ public Path getConfigRoot() {
throw new UnsupportedOperationException();
}
- @Override
- public String getOauthTokenUrl() {
- throw new UnsupportedOperationException();
- }
-
@Override
public String getOauthApplicationId() {
throw new UnsupportedOperationException();
From 887f048cf7e7f8cec4ad198efebacb8cf65bcb01 Mon Sep 17 00:00:00 2001
From: Antti Leinonen
Date: Wed, 5 Apr 2017 17:09:39 +0300
Subject: [PATCH 11/86] Normalize server address, dont send crashes when
NotLoggedInException
---
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 2 +
.../TmcServerCommunicationTaskFactory.java | 10 +-
.../tmc/core/communication/oauth2/Oauth.java | 7 +-
.../tmc/core/configuration/TmcSettings.java | 15 +-
.../cs/tmc/core/domain/OauthCredentials.java | 5 +
.../utilities/ExceptionTrackingCallable.java | 3 +-
.../utilities/TmcServerAddressNormalizer.java | 30 +++
.../core/commands/SendDiagnosticsTest.java | 9 +-
.../ExceptionTrackingCallableTest.java | 12 +-
.../cs/tmc/core/utils/MockSettings.java | 39 +++-
tmc-core.iml | 179 ------------------
11 files changed, 93 insertions(+), 218 deletions(-)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java
delete mode 100644 tmc-core.iml
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 7e3a2312..15999979 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -29,6 +29,7 @@
import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utilities.ExceptionTrackingCallable;
+import fi.helsinki.cs.tmc.core.utilities.TmcServerAddressNormalizer;
import fi.helsinki.cs.tmc.langs.abstraction.ValidationResult;
import fi.helsinki.cs.tmc.langs.domain.RunResult;
import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
@@ -74,6 +75,7 @@ public TmcCore() {}
public TmcCore(TmcSettings settings, TaskExecutor tmcLangs) {
TmcSettingsHolder.set(settings);
TmcLangsHolder.set(tmcLangs);
+ TmcServerAddressNormalizer.normalize();
}
public Callable authenticate(ProgressObserver observer, String password) {
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 35999791..2019d853 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -122,20 +122,19 @@ private URI getCourseListUrl()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
String serverAddress = settings.getServerAddress();
String url;
+ String urlLastPart = "api/v" + API_VERSION + "/core/org/" + settings.getOrganization() + "/courses.json";
if (serverAddress.endsWith("/")) {
- url = serverAddress + "courses.json";
+ url = serverAddress + urlLastPart;
} else {
- url = serverAddress + "/courses.json";
+ url = serverAddress + "/" + urlLastPart;
}
return addApiCallQueryParameters(URI.create(url));
}
private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
- url = UriUtils.withQueryParam(url, "api_version", "" + API_VERSION);
url = UriUtils.withQueryParam(url, "client", settings.clientName());
url = UriUtils.withQueryParam(url, "client_version", clientVersion);
- String token = oauth.getToken();
- url = UriUtils.withQueryParam(url, "access_token", token);
+ url = UriUtils.withQueryParam(url, "access_token", oauth.getToken());
return url;
}
@@ -374,6 +373,7 @@ public Callable getOauthCredentialsTask() throws IOException {
OauthCredentials credentials =
new Gson().fromJson(
IOUtils.toString(credentialsUrl.toURL()), OauthCredentials.class);
+ settings.setOauthCredentials(credentials);
return null;
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
index eb23c0c4..90d3753c 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
@@ -1,6 +1,7 @@
package fi.helsinki.cs.tmc.core.communication.oauth2;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.exceptions.TmcCoreException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
@@ -79,13 +80,15 @@ public void fetchNewToken(String password) throws OAuthSystemException, OAuthPro
oauthTokenUrl = settings.getServerAddress() + "/oauth/token";
}
+ OauthCredentials credentials = settings.getOauthCredentials();
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(oauthTokenUrl)
.setGrantType(GrantType.PASSWORD)
- .setClientId(settings.getOauthApplicationId())
- .setClientSecret(settings.getOauthSecret())
+ .setClientId(credentials.getOauthApplicationId())
+ .setClientSecret(credentials.getOauthSecret())
.setUsername(settings.getUsername())
.setPassword(password)
+ .setRedirectURI("urn:ietf:wg:oauth:2.0:oob")
.buildQueryMessage();
OAuthClient client = new OAuthClient(new URLConnectionClient());
String token = client.accessToken(request, OAuthJSONAccessTokenResponse.class)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index 40bcd9d3..96b3bea9 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -1,6 +1,7 @@
package fi.helsinki.cs.tmc.core.configuration;
import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
@@ -14,6 +15,8 @@ public interface TmcSettings {
String getServerAddress();
+ void setServerAddress(String address);
+
/**
* Used for old login credentials, new ones use oauth.
*/
@@ -62,15 +65,15 @@ public interface TmcSettings {
boolean getSendDiagnostics();
- String getOauthApplicationId();
-
- void setOauthApplicationId(String oauthApplicationId);
-
- String getOauthSecret();
+ OauthCredentials getOauthCredentials();
- void setOauthSecret(String oauthSecret);
+ void setOauthCredentials(OauthCredentials credentials);
void setToken(String token);
Optional getToken();
+
+ String getOrganization();
+
+ void setOrganization(String organization);
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java b/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
index ec81a7dd..530429f7 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/domain/OauthCredentials.java
@@ -16,6 +16,11 @@ public OauthCredentials() {
}
+ public OauthCredentials(String oauthApplicationId, String oauthSecret) {
+ this.oauthApplicationId = oauthApplicationId;
+ this.oauthSecret = oauthSecret;
+ }
+
public void setOauthApplicationId(String oauthApplicationId) {
this.oauthApplicationId = oauthApplicationId;
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallable.java b/src/main/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallable.java
index d5f9541b..364bdda4 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallable.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallable.java
@@ -3,6 +3,7 @@
import fi.helsinki.cs.tmc.core.communication.TmcBandicootCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.bandicoot.Crash;
+import fi.helsinki.cs.tmc.core.exceptions.NotLoggedInException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import com.google.common.annotations.VisibleForTesting;
@@ -33,7 +34,7 @@ public T call() throws Exception {
try {
return command.call();
} catch (Exception ex) {
- if (settings.getSendDiagnostics()) {
+ if (settings.getSendDiagnostics() && !(ex instanceof NotLoggedInException)) {
tmcBandicootCommunicationTaskFactory.sendCrash(new Crash(ex)).call();
}
throw ex;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java b/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java
new file mode 100644
index 00000000..fc0278fe
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java
@@ -0,0 +1,30 @@
+package fi.helsinki.cs.tmc.core.utilities;
+
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+
+public class TmcServerAddressNormalizer {
+
+ public static void normalize() {
+ TmcSettings tmcSettings = TmcSettingsHolder.get();
+ String address = tmcSettings.getServerAddress();
+
+ if (!address.contains("/org/") && address.contains("/hy")) {
+ int last = address.lastIndexOf("/");
+ tmcSettings.setServerAddress(address.substring(0, last));
+ tmcSettings.setOrganization(address.substring(last + 1, address.length()));
+ } else if (!address.contains("/org/")) {
+ return;
+ } else {
+ String[] split = address.split("/org/");
+
+ tmcSettings.setServerAddress(split[0]);
+
+ String organization = split[1];
+ if (organization.charAt(organization.length() - 1) == '/') {
+ organization = organization.substring(0, organization.length());
+ }
+ tmcSettings.setOrganization(organization);
+ }
+ }
+}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/SendDiagnosticsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/SendDiagnosticsTest.java
index 96b2d38f..0933f02c 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/SendDiagnosticsTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/SendDiagnosticsTest.java
@@ -4,13 +4,13 @@
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import fi.helsinki.cs.tmc.core.communication.TmcBandicootCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.domain.bandicoot.Diagnostics;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import org.junit.Before;
import org.junit.Test;
@@ -20,12 +20,10 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.util.Locale;
import java.util.concurrent.Callable;
public class SendDiagnosticsTest {
- @Mock
TmcSettings settings;
@Mock
@@ -40,11 +38,8 @@ public class SendDiagnosticsTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+ this.settings = new MockSettings();
TmcSettingsHolder.set(settings);
- when(settings.getServerAddress()).thenReturn("testAddress");
- when(settings.clientName()).thenReturn("testClient");
- when(settings.clientVersion()).thenReturn("testVersion");
- when(settings.getLocale()).thenReturn(new Locale("en"));
doReturn(new Callable() {
@Override
public Object call() throws Exception {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallableTest.java b/src/test/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallableTest.java
index e91d7e88..da9532ed 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallableTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utilities/ExceptionTrackingCallableTest.java
@@ -8,19 +8,17 @@
import fi.helsinki.cs.tmc.core.domain.bandicoot.Crash;
import fi.helsinki.cs.tmc.core.exceptions.TmcCoreException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
import org.junit.Before;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.util.Locale;
import java.util.concurrent.Callable;
public class ExceptionTrackingCallableTest {
- @Mock
TmcSettings settings;
@Mock
TmcBandicootCommunicationTaskFactory factory;
@@ -28,14 +26,8 @@ public class ExceptionTrackingCallableTest {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
+ this.settings = new MockSettings();
TmcSettingsHolder.set(settings);
- when(settings.getServerAddress()).thenReturn("testAddress");
- when(settings.clientName()).thenReturn("testClient");
- when(settings.clientVersion()).thenReturn("testVersion");
- when(settings.hostProgramName()).thenReturn("testHostProgram");
- when(settings.hostProgramVersion()).thenReturn("testHostProgramVersion");
- when(settings.getLocale()).thenReturn(new Locale("en"));
- when(settings.getSendDiagnostics()).thenReturn(true);
when(factory.sendCrash(any(Crash.class))).thenReturn(new Callable() {
@Override public Void call() throws Exception {
return null;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index 470d0b79..4969bdf4 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -2,6 +2,7 @@
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
import com.google.common.base.Optional;
@@ -24,6 +25,11 @@ public String getServerAddress() {
return "testAddress";
}
+ @Override
+ public void setServerAddress(String address) {
+
+ }
+
@Override
public Optional getPassword() {
return Optional.absent();
@@ -56,7 +62,7 @@ public String clientName() {
@Override
public String clientVersion() {
- return "testClient";
+ return "testVersion";
}
@Override
@@ -71,7 +77,7 @@ public Path getTmcProjectDirectory() {
@Override
public Locale getLocale() {
- return null;
+ return new Locale("en");
}
@Override
@@ -95,22 +101,30 @@ public Path getConfigRoot() {
}
@Override
- public String getOauthApplicationId() {
- throw new UnsupportedOperationException();
+ public String hostProgramName() {
+ return "testHostProgram";
}
@Override
- public void setOauthApplicationId(String oauthApplicationId) {
+ public String hostProgramVersion() {
+ return "testHostProgramVersion";
+ }
+ @Override
+ public boolean getSendDiagnostics() {
+ return true;
}
@Override
- public String getOauthSecret() {
- throw new UnsupportedOperationException();
+ public OauthCredentials getOauthCredentials() {
+ OauthCredentials credentials = new OauthCredentials();
+ credentials.setOauthApplicationId("testOauthApplicationId");
+ credentials.setOauthSecret("testOauthSecret");
+ return credentials;
}
@Override
- public void setOauthSecret(String oauthSecret) {
+ public void setOauthCredentials(OauthCredentials credentials) {
}
@@ -123,4 +137,13 @@ public void setToken(String token) {
public Optional getToken() {
return token;
}
+
+ @Override
+ public String getOrganization() {
+ return "testOrganization";
+ }
+
+ @Override
+ public void setOrganization(String organization) {
+ }
}
diff --git a/tmc-core.iml b/tmc-core.iml
deleted file mode 100644
index 85a232b4..00000000
--- a/tmc-core.iml
+++ /dev/null
@@ -1,179 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
From 3b133064374d37f02e17892afd1066671f78fb86 Mon Sep 17 00:00:00 2001
From: Antti Leinonen
Date: Mon, 15 May 2017 10:52:11 +0300
Subject: [PATCH 12/86] Functionality for getting organizations and courses
from server
---
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 7 +++
.../tmc/core/commands/GetOrganizations.java | 26 ++++++++++
.../TmcServerCommunicationTaskFactory.java | 15 ++++++
.../tmc/core/configuration/TmcSettings.java | 1 +
.../helsinki/cs/tmc/core/domain/Course.java | 18 +++++++
.../cs/tmc/core/domain/Organization.java | 49 +++++++++++++++++++
.../utilities/TmcServerAddressNormalizer.java | 1 +
.../core/commands/GetOrganizationsTest.java | 49 +++++++++++++++++++
.../cs/tmc/core/utils/MockSettings.java | 1 +
9 files changed, 167 insertions(+)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/commands/GetOrganizations.java
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/domain/Organization.java
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 15999979..54fae4df 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -5,6 +5,7 @@
import fi.helsinki.cs.tmc.core.commands.DownloadModelSolution;
import fi.helsinki.cs.tmc.core.commands.DownloadOrUpdateExercises;
import fi.helsinki.cs.tmc.core.commands.GetCourseDetails;
+import fi.helsinki.cs.tmc.core.commands.GetOrganizations;
import fi.helsinki.cs.tmc.core.commands.GetUnreadReviews;
import fi.helsinki.cs.tmc.core.commands.GetUpdatableExercises;
import fi.helsinki.cs.tmc.core.commands.ListCourses;
@@ -22,6 +23,7 @@
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.Organization;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import fi.helsinki.cs.tmc.core.domain.Review;
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
@@ -78,6 +80,11 @@ public TmcCore(TmcSettings settings, TaskExecutor tmcLangs) {
TmcServerAddressNormalizer.normalize();
}
+ public Callable> getOrganizations(ProgressObserver observer) {
+ logger.info("Creating new GetOrganizations command");
+ return new GetOrganizations(observer);
+ }
+
public Callable authenticate(ProgressObserver observer, String password) {
logger.info("Creating new AuthenticateUser command");
return new AuthenticateUser(observer, password, Oauth.getInstance());
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/GetOrganizations.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/GetOrganizations.java
new file mode 100644
index 00000000..1172e889
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/GetOrganizations.java
@@ -0,0 +1,26 @@
+package fi.helsinki.cs.tmc.core.commands;
+
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
+import fi.helsinki.cs.tmc.core.domain.Organization;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import java.util.List;
+
+public class GetOrganizations extends Command> {
+
+ public GetOrganizations(ProgressObserver observer) {
+ super(observer);
+ }
+
+ @VisibleForTesting
+ GetOrganizations(ProgressObserver observer, TmcServerCommunicationTaskFactory tmcServerCommunicationTaskFactory) {
+ super(observer, tmcServerCommunicationTaskFactory);
+ }
+
+ @Override
+ public List call() throws Exception {
+ return tmcServerCommunicationTaskFactory.getOrganizationListTask();
+ }
+}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 2019d853..0b9d00ce 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -11,6 +11,7 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
+import fi.helsinki.cs.tmc.core.domain.Organization;
import fi.helsinki.cs.tmc.core.domain.Review;
import fi.helsinki.cs.tmc.core.domain.submission.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.exceptions.FailedHttpResponseException;
@@ -377,6 +378,20 @@ public Callable getOauthCredentialsTask() throws IOException {
return null;
}
+ public List getOrganizationListTask() throws IOException {
+ String url;
+ String serverAddress = settings.getServerAddress();
+ String urlLastPart = "api/v" + API_VERSION + "/org";
+ if (serverAddress.endsWith("/")) {
+ url = settings.getServerAddress() + urlLastPart;
+ } else {
+ url = serverAddress + "/" + urlLastPart;
+ }
+ URI organizationUrl = URI.create(url);
+ List organizations = new Gson().fromJson(IOUtils.toString(organizationUrl.toURL()), new TypeToken>(){}.getType());
+ return organizations;
+ }
+
private byte[] eventListToPostBody(List events) throws IOException {
ByteArrayOutputStream bufferBos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(bufferBos);
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index 96b3bea9..67f35818 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -2,6 +2,7 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
+import fi.helsinki.cs.tmc.core.domain.Organization;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/domain/Course.java b/src/main/java/fi/helsinki/cs/tmc/core/domain/Course.java
index 29074b9f..37042281 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/domain/Course.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/domain/Course.java
@@ -10,6 +10,8 @@ public class Course {
private int id;
private String name;
+ private String title;
+ private String description;
private List exercises;
@@ -81,6 +83,22 @@ public void setName(String name) {
this.name = name;
}
+ public String getTitle() {
+ return this.title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
public URI getDetailsUrl() {
return detailsUrl;
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/domain/Organization.java b/src/main/java/fi/helsinki/cs/tmc/core/domain/Organization.java
new file mode 100644
index 00000000..5b988d0c
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/domain/Organization.java
@@ -0,0 +1,49 @@
+package fi.helsinki.cs.tmc.core.domain;
+
+import com.google.gson.annotations.SerializedName;
+
+public class Organization {
+
+ @SerializedName("name")
+ private String name;
+
+ @SerializedName("information")
+ private String information;
+
+ @SerializedName("slug")
+ private String slug;
+
+ @SerializedName("logo_path")
+ private String logoPath;
+
+ @SerializedName("pinned")
+ private boolean pinned;
+
+ public Organization(String name, String information, String slug, String logoPath, boolean pinned) {
+ this.name = name;
+ this.information = information;
+ this.slug = slug;
+ this.logoPath = logoPath;
+ this.pinned = pinned;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getInformation() {
+ return information;
+ }
+
+ public String getSlug() {
+ return slug;
+ }
+
+ public String getLogoPath() {
+ return logoPath;
+ }
+
+ public boolean isPinned() {
+ return pinned;
+ }
+}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java b/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java
index fc0278fe..99f16d2f 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/utilities/TmcServerAddressNormalizer.java
@@ -1,6 +1,7 @@
package fi.helsinki.cs.tmc.core.utilities;
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Organization;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
public class TmcServerAddressNormalizer {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java
new file mode 100644
index 00000000..b25fec23
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java
@@ -0,0 +1,49 @@
+package fi.helsinki.cs.tmc.core.commands;
+
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Organization;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class GetOrganizationsTest {
+ @Mock
+ ProgressObserver mockObserver;
+ @Mock
+ TmcServerCommunicationTaskFactory tmcServerCommunicationTaskFactory;
+
+ TmcSettings settings;
+ private Command> command;
+
+ @Before
+ public void setUp() throws IOException {
+ MockitoAnnotations.initMocks(this);
+ settings = new MockSettings();
+ TmcSettingsHolder.set(settings);
+ List organizations = new ArrayList();
+ organizations.add(new Organization("test", "test", "test", "test", false));
+ when(tmcServerCommunicationTaskFactory.getOrganizationListTask()).thenReturn(organizations);
+ }
+
+ @Test
+ public void callsTmcServerCommunicationTaskFactoryGetOrganizationsList() throws Exception {
+ command = new GetOrganizations(mockObserver, tmcServerCommunicationTaskFactory);
+ command.call();
+ verify(tmcServerCommunicationTaskFactory, times(1)).getOrganizationListTask();
+ }
+}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index 4969bdf4..c760ed64 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -3,6 +3,7 @@
import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
+import fi.helsinki.cs.tmc.core.domain.Organization;
import com.google.common.base.Optional;
From 8be752756be918aa3c09133e60a9567ee9f3c146 Mon Sep 17 00:00:00 2001
From: Antti Leinonen
Date: Mon, 15 May 2017 10:53:09 +0300
Subject: [PATCH 13/86] Use Optional.of for oauth tokens
---
.../fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java | 3 ++-
.../fi/helsinki/cs/tmc/core/configuration/TmcSettings.java | 3 +--
.../helsinki/cs/tmc/core/commands/AuthenticateUserTest.java | 4 +++-
.../cs/tmc/core/communication/oauth2/OauthTest.java | 6 ++++--
.../java/fi/helsinki/cs/tmc/core/utils/MockSettings.java | 4 ++--
5 files changed, 12 insertions(+), 8 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
index 90d3753c..3c7cffc3 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/oauth2/Oauth.java
@@ -6,6 +6,7 @@
import fi.helsinki.cs.tmc.core.exceptions.TmcCoreException;
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import com.google.common.base.Optional;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
@@ -93,6 +94,6 @@ public void fetchNewToken(String password) throws OAuthSystemException, OAuthPro
OAuthClient client = new OAuthClient(new URLConnectionClient());
String token = client.accessToken(request, OAuthJSONAccessTokenResponse.class)
.getAccessToken();
- settings.setToken(token);
+ settings.setToken(Optional.of(token));
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
index 67f35818..e6b22332 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/configuration/TmcSettings.java
@@ -2,7 +2,6 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.OauthCredentials;
-import fi.helsinki.cs.tmc.core.domain.Organization;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
@@ -70,7 +69,7 @@ public interface TmcSettings {
void setOauthCredentials(OauthCredentials credentials);
- void setToken(String token);
+ void setToken(Optional token);
Optional getToken();
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
index 1333678a..a16c58f8 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
@@ -15,6 +15,8 @@
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utils.MockSettings;
+import com.google.common.base.Optional;
+
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
@@ -48,7 +50,7 @@ public void setUp() throws OAuthProblemException, OAuthSystemException, IOExcept
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
- settings.setToken("testToken");
+ settings.setToken(Optional.of("testToken"));
return null;
}
}).when(oauth).fetchNewToken("password");
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
index 8c3ddebd..5fff0a64 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/oauth2/OauthTest.java
@@ -15,6 +15,8 @@
import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
import fi.helsinki.cs.tmc.core.utils.MockSettings;
+import com.google.common.base.Optional;
+
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
@@ -43,7 +45,7 @@ public void setUp() throws Exception {
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
- settings.setToken("testToken");
+ settings.setToken(Optional.of("testToken"));
return null;
}
}).when(oauth).fetchNewToken(anyString());
@@ -76,6 +78,6 @@ public void hasNoTokenWhenInitialized() throws Exception {
@Test
public void setsTokenToSettings() throws OAuthProblemException, OAuthSystemException {
oauth.fetchNewToken("password");
- verify(settings, times(1)).setToken(anyString());
+ verify(settings, times(1)).setToken(Optional.of(anyString()));
}
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
index c760ed64..2b668cb3 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/utils/MockSettings.java
@@ -130,8 +130,8 @@ public void setOauthCredentials(OauthCredentials credentials) {
}
@Override
- public void setToken(String token) {
- this.token = Optional.of(token);
+ public void setToken(Optional token) {
+ this.token = token;
}
@Override
From 89777360e3ed4648df3e28bc7596b3c2cf8542ed Mon Sep 17 00:00:00 2001
From: Ville Tanttu
Date: Tue, 16 May 2017 13:43:24 +0300
Subject: [PATCH 14/86] Added test method to get next.json URI
---
.../TmcServerCommunicationTaskFactory.java | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 0b9d00ce..172729a1 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -132,6 +132,19 @@ private URI getCourseListUrl()
return addApiCallQueryParameters(URI.create(url));
}
+ /**
+ * Test for returning skillifier stuff.
+ *
+ * @return next.json URI
+ * @throws OAuthSystemException
+ * @throws OAuthProblemException
+ * @throws NotLoggedInException
+ */
+ private URI getNextJson()
+ throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
+ return addApiCallQueryParameters(URI.create("localhost:3200/next.json"));
+ }
+
private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
url = UriUtils.withQueryParam(url, "client", settings.clientName());
url = UriUtils.withQueryParam(url, "client_version", clientVersion);
From 8e624237033c62f07d478366e8cb27d97584b560 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Tue, 16 May 2017 14:55:04 +0300
Subject: [PATCH 15/86] Connected commands and TaskFactory
---
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 6 ++++
.../GetAdaptiveExerciseAvailability.java | 31 +++++++++++++++++++
.../TmcServerCommunicationTaskFactory.java | 25 +++++++++------
3 files changed, 52 insertions(+), 10 deletions(-)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 54fae4df..2007d4aa 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -4,6 +4,7 @@
import fi.helsinki.cs.tmc.core.commands.DownloadCompletedExercises;
import fi.helsinki.cs.tmc.core.commands.DownloadModelSolution;
import fi.helsinki.cs.tmc.core.commands.DownloadOrUpdateExercises;
+import fi.helsinki.cs.tmc.core.commands.GetAdaptiveExerciseAvailability;
import fi.helsinki.cs.tmc.core.commands.GetCourseDetails;
import fi.helsinki.cs.tmc.core.commands.GetOrganizations;
import fi.helsinki.cs.tmc.core.commands.GetUnreadReviews;
@@ -173,6 +174,11 @@ public Callable downloadModelSolution(ProgressObserver observer, Exerc
logger.info("Creating new DownloadModelSolution command");
return new ExceptionTrackingCallable<>(new DownloadModelSolution(observer, exercise));
}
+
+ public Callable getStatusOfExercises(ProgressObserver observer) {
+ logger.info("Creating new GetStatusOfExercises command");
+ return new ExceptionTrackingCallable<>(new GetAdaptiveExerciseAvailability(observer));
+ }
/**
* NOT IMPLEMENTED!
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java
new file mode 100644
index 00000000..801a8321
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java
@@ -0,0 +1,31 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package fi.helsinki.cs.tmc.core.commands;
+
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ * @author sakuolin
+ */
+public class GetAdaptiveExerciseAvailability extends Command {
+
+ private static final Logger logger = LoggerFactory.getLogger(SendFeedback.class);
+
+ public GetAdaptiveExerciseAvailability(ProgressObserver observer) {
+ super(observer);
+ }
+
+ @Override
+ public Boolean call() throws Exception {
+ logger.info("Checking adaptive exercises availability");
+ //informObserver()
+ return tmcServerCommunicationTaskFactory.getNextJson().call();
+ }
+
+}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 172729a1..0d0034dd 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -131,7 +131,14 @@ private URI getCourseListUrl()
}
return addApiCallQueryParameters(URI.create(url));
}
-
+
+ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
+ url = UriUtils.withQueryParam(url, "client", settings.clientName());
+ url = UriUtils.withQueryParam(url, "client_version", clientVersion);
+ url = UriUtils.withQueryParam(url, "access_token", oauth.getToken());
+ return url;
+ }
+
/**
* Test for returning skillifier stuff.
*
@@ -140,16 +147,14 @@ private URI getCourseListUrl()
* @throws OAuthProblemException
* @throws NotLoggedInException
*/
- private URI getNextJson()
+ public Callable getNextJson()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
- return addApiCallQueryParameters(URI.create("localhost:3200/next.json"));
- }
-
- private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
- url = UriUtils.withQueryParam(url, "client", settings.clientName());
- url = UriUtils.withQueryParam(url, "client_version", clientVersion);
- url = UriUtils.withQueryParam(url, "access_token", oauth.getToken());
- return url;
+ return wrapWithNotLoggedInException(new Callable() {
+ @Override
+ public Boolean call() throws Exception {
+ return false;
+ }
+ });
}
public Callable> getDownloadingCourseListTask() {
From fdd87e5ab0e62b9f46e881974b5d86e7127d4ebb Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 08:27:15 +0300
Subject: [PATCH 16/86] Updating smaller parts for Skillifier connection
---
.../TmcServerCommunicationTaskFactory.java | 4 ++++
.../serialization/AdaptiveExerciseParser.java | 17 +++++++++++++++++
2 files changed, 21 insertions(+)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 0d0034dd..a2cad8e8 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -152,6 +152,10 @@ public Callable getNextJson()
return wrapWithNotLoggedInException(new Callable() {
@Override
public Boolean call() throws Exception {
+ // suoraan json?
+ Callable json = new HttpTasks().
+ getForText(URI.create("localhost:3200/next.json"));
+ // return AdaptiveExerciseParser.parseFromJson();
return false;
}
});
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
new file mode 100644
index 00000000..4b0889b9
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -0,0 +1,17 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package fi.helsinki.cs.tmc.core.communication.serialization;
+
+/**
+ *
+ * @author sakuolin
+ */
+public class AdaptiveExerciseParser {
+
+ // TODO: Parse exercise from address
+ // TODO: Parse Boolean from JSON
+
+}
From 2d7076d424c87923a0d05e651909d69bc77379f6 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 09:47:16 +0300
Subject: [PATCH 17/86] Added functionality, added tests
---
.../TmcServerCommunicationTaskFactory.java | 21 ++++++++----
.../serialization/AdaptiveExerciseParser.java | 27 +++++++++++++++
.../AdaptiveExerciseParserTest.java | 34 +++++++++++++++++++
3 files changed, 76 insertions(+), 6 deletions(-)
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index a2cad8e8..48b012ec 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -3,6 +3,7 @@
import fi.helsinki.cs.tmc.core.communication.http.HttpTasks;
import fi.helsinki.cs.tmc.core.communication.http.UriUtils;
import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
+import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
import fi.helsinki.cs.tmc.core.communication.serialization.ByteArrayGsonSerializer;
import fi.helsinki.cs.tmc.core.communication.serialization.CourseInfoParser;
import fi.helsinki.cs.tmc.core.communication.serialization.CourseListParser;
@@ -58,6 +59,7 @@ public class TmcServerCommunicationTaskFactory {
private TmcSettings settings;
private Oauth oauth;
+ private AdaptiveExerciseParser adaptiveExerciseParser;
private CourseListParser courseListParser;
private CourseInfoParser courseInfoParser;
private ReviewListParser reviewListParser;
@@ -68,18 +70,20 @@ public TmcServerCommunicationTaskFactory() {
}
public TmcServerCommunicationTaskFactory(TmcSettings settings, Oauth oauth) {
- this(settings, oauth, new CourseListParser(),
+ this(settings, oauth, new AdaptiveExerciseParser(), new CourseListParser(),
new CourseInfoParser(), new ReviewListParser());
}
public TmcServerCommunicationTaskFactory(
TmcSettings settings,
Oauth oauth,
+ AdaptiveExerciseParser adaptiveExerciseParser,
CourseListParser courseListParser,
CourseInfoParser courseInfoParser,
ReviewListParser reviewListParser) {
this.settings = settings;
this.oauth = oauth;
+ this.adaptiveExerciseParser = adaptiveExerciseParser;
this.courseListParser = courseListParser;
this.courseInfoParser = courseInfoParser;
this.reviewListParser = reviewListParser;
@@ -152,11 +156,16 @@ public Callable getNextJson()
return wrapWithNotLoggedInException(new Callable() {
@Override
public Boolean call() throws Exception {
- // suoraan json?
- Callable json = new HttpTasks().
- getForText(URI.create("localhost:3200/next.json"));
- // return AdaptiveExerciseParser.parseFromJson();
- return false;
+ try {
+ Callable download = new HttpTasks().
+ getForText(URI.create("localhost:3200/next.json"));
+ String json = download.call();
+ return adaptiveExerciseParser.parseFromJson(json);
+ }
+ catch (Exception ex) {
+ return false;
+ // do things
+ }
}
});
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 4b0889b9..b007500e 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -5,6 +5,14 @@
*/
package fi.helsinki.cs.tmc.core.communication.serialization;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
+import java.util.Date;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
*
* @author sakuolin
@@ -14,4 +22,23 @@ public class AdaptiveExerciseParser {
// TODO: Parse exercise from address
// TODO: Parse Boolean from JSON
+ private static final Logger logger = LoggerFactory.getLogger(AdaptiveExerciseParser.class);
+
+ // miksi static?
+ public Boolean parseFromJson(String json) {
+ if (json == null) {
+ throw new NullPointerException("Json string is null");
+ }
+ if (json.trim().isEmpty()) {
+ throw new IllegalArgumentException("Empty input");
+ }
+ try {
+ System.out.println(json);
+ return true;
+ } catch (RuntimeException ex) {
+ logger.warn("Failed to parse adaptive course availability", ex);
+ throw new RuntimeException("Failed to parse adaptive course availability: " + ex.getMessage(), ex);
+ }
+ }
+
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
new file mode 100644
index 00000000..98b37835
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -0,0 +1,34 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package fi.helsinki.cs.tmc.core.communication.http.serialization;
+
+import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ *
+ * @author sakuolin
+ */
+public class AdaptiveExerciseParserTest {
+
+ private AdaptiveExerciseParser aep;
+
+ @Before
+ public void setUp() {
+ this.aep = new AdaptiveExerciseParser();
+ }
+
+ @Test
+ public void testAvailability() {
+ assertFalse(aep.parseFromJson("ögodfogdfog"));
+ }
+
+}
From 46c5411cfce265097788f0634dd74f4066a3b264 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 10:08:36 +0300
Subject: [PATCH 18/86] Always return a Boolean from AdaptiveExerciseParser
---
.../TmcServerCommunicationTaskFactory.java | 2 +-
.../serialization/AdaptiveExerciseParser.java | 13 ++++++++++---
.../serialization/AdaptiveExerciseParserTest.java | 6 ++----
3 files changed, 13 insertions(+), 8 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 48b012ec..8f07fe3e 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -160,7 +160,7 @@ public Boolean call() throws Exception {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
String json = download.call();
- return adaptiveExerciseParser.parseFromJson(json);
+ return adaptiveExerciseParser.parseBooleanFromJson(json);
}
catch (Exception ex) {
return false;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index b007500e..0dbd27f9 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -10,6 +10,7 @@
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import java.util.Date;
+import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -24,8 +25,7 @@ public class AdaptiveExerciseParser {
private static final Logger logger = LoggerFactory.getLogger(AdaptiveExerciseParser.class);
- // miksi static?
- public Boolean parseFromJson(String json) {
+ private Boolean parseFromJson(String json) {
if (json == null) {
throw new NullPointerException("Json string is null");
}
@@ -34,11 +34,18 @@ public Boolean parseFromJson(String json) {
}
try {
System.out.println(json);
- return true;
+ JSONObject obj = new JSONObject(json);
+ return obj.getBoolean("available");
} catch (RuntimeException ex) {
logger.warn("Failed to parse adaptive course availability", ex);
throw new RuntimeException("Failed to parse adaptive course availability: " + ex.getMessage(), ex);
}
}
+ public Boolean parseBooleanFromJson(String json) {
+ Boolean availability = parseFromJson(json);
+ if (availability) return true;
+ else return false;
+ }
+
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 98b37835..7f7c1233 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -6,10 +6,8 @@
package fi.helsinki.cs.tmc.core.communication.http.serialization;
import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
-import org.junit.After;
-import org.junit.AfterClass;
+
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -28,7 +26,7 @@ public void setUp() {
@Test
public void testAvailability() {
- assertFalse(aep.parseFromJson("ögodfogdfog"));
+ assertTrue(aep.parseBooleanFromJson("dgnsfogjdpfog"));
}
}
From 2178d63592fc5766f8e8f00eebd2b3703bc9e898 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 10:19:26 +0300
Subject: [PATCH 19/86] Parser working for JSON Objects
---
.../communication/serialization/AdaptiveExerciseParser.java | 1 -
.../http/serialization/AdaptiveExerciseParserTest.java | 2 +-
2 files changed, 1 insertion(+), 2 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 0dbd27f9..492026ec 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -33,7 +33,6 @@ private Boolean parseFromJson(String json) {
throw new IllegalArgumentException("Empty input");
}
try {
- System.out.println(json);
JSONObject obj = new JSONObject(json);
return obj.getBoolean("available");
} catch (RuntimeException ex) {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 7f7c1233..44fdd31d 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -26,7 +26,7 @@ public void setUp() {
@Test
public void testAvailability() {
- assertTrue(aep.parseBooleanFromJson("dgnsfogjdpfog"));
+ assertTrue(aep.parseBooleanFromJson("{ available: true }"));
}
}
From ffbfb4a47167dc93cf984dfc0800f861b191e372 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 10:28:03 +0300
Subject: [PATCH 20/86] Reverted changes; Makes for a better design
---
.../communication/TmcServerCommunicationTaskFactory.java | 2 +-
.../serialization/AdaptiveExerciseParser.java | 8 +-------
.../http/serialization/AdaptiveExerciseParserTest.java | 2 +-
3 files changed, 3 insertions(+), 9 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 8f07fe3e..48b012ec 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -160,7 +160,7 @@ public Boolean call() throws Exception {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
String json = download.call();
- return adaptiveExerciseParser.parseBooleanFromJson(json);
+ return adaptiveExerciseParser.parseFromJson(json);
}
catch (Exception ex) {
return false;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 492026ec..3c59a86e 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -25,7 +25,7 @@ public class AdaptiveExerciseParser {
private static final Logger logger = LoggerFactory.getLogger(AdaptiveExerciseParser.class);
- private Boolean parseFromJson(String json) {
+ public Boolean parseFromJson(String json) {
if (json == null) {
throw new NullPointerException("Json string is null");
}
@@ -41,10 +41,4 @@ private Boolean parseFromJson(String json) {
}
}
- public Boolean parseBooleanFromJson(String json) {
- Boolean availability = parseFromJson(json);
- if (availability) return true;
- else return false;
- }
-
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 44fdd31d..d5adf8f7 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -26,7 +26,7 @@ public void setUp() {
@Test
public void testAvailability() {
- assertTrue(aep.parseBooleanFromJson("{ available: true }"));
+ assertTrue(aep.parseFromJson("{ available: true }"));
}
}
From fad710e9497818c22a31dfe8e47643ba588ffe6f Mon Sep 17 00:00:00 2001
From: Mavai
Date: Wed, 17 May 2017 11:00:42 +0300
Subject: [PATCH 21/86] testi parserille
---
.../AdaptiveExerciseParserTest.java | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 44fdd31d..aeb85c24 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -9,24 +9,29 @@
import org.junit.Before;
import org.junit.Test;
+
import static org.junit.Assert.*;
/**
- *
* @author sakuolin
*/
public class AdaptiveExerciseParserTest {
-
+
private AdaptiveExerciseParser aep;
-
+
@Before
public void setUp() {
this.aep = new AdaptiveExerciseParser();
}
-
+
@Test
- public void testAvailability() {
+ public void testAvailabilityTrue() {
assertTrue(aep.parseBooleanFromJson("{ available: true }"));
}
-
+
+ @Test
+ public void testAvailabilityFalse() {
+ assertFalse(aep.parseBooleanFromJson("{ available: false }"));
+ }
+
}
From d63fc1f76bfe078841a5bd38200eb94acb3d425e Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 11:47:48 +0300
Subject: [PATCH 22/86] Broken things
---
src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java | 8 ++++----
...Availability.java => DownloadAdaptiveExercise.java} | 10 ++++++----
.../TmcServerCommunicationTaskFactory.java | 9 ++++-----
.../serialization/AdaptiveExerciseParser.java | 9 ++++++---
.../fi/helsinki/cs/tmc/spyware/EventSendBuffer.java | 1 +
.../cs/tmc/core/commands/AuthenticateUserTest.java | 3 +++
.../core/commands/DownloadOrUpdateExercisesTest.java | 5 +++++
.../cs/tmc/core/commands/GetCourseDetailsTest.java | 1 +
.../cs/tmc/core/commands/GetOrganizationsTest.java | 1 +
.../tmc/core/commands/GetUpdatableExercisesTest.java | 4 ++++
.../helsinki/cs/tmc/core/commands/ListCoursesTest.java | 1 +
.../cs/tmc/core/commands/PasteWithCommentTest.java | 2 ++
.../cs/tmc/core/commands/SendFeedbackTest.java | 3 +++
.../fi/helsinki/cs/tmc/core/commands/SubmitTest.java | 2 ++
.../cs/tmc/core/spyware/EventSendBufferTest.java | 6 ++++++
15 files changed, 49 insertions(+), 16 deletions(-)
rename src/main/java/fi/helsinki/cs/tmc/core/commands/{GetAdaptiveExerciseAvailability.java => DownloadAdaptiveExercise.java} (66%)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 2007d4aa..91b33bbf 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -4,7 +4,7 @@
import fi.helsinki.cs.tmc.core.commands.DownloadCompletedExercises;
import fi.helsinki.cs.tmc.core.commands.DownloadModelSolution;
import fi.helsinki.cs.tmc.core.commands.DownloadOrUpdateExercises;
-import fi.helsinki.cs.tmc.core.commands.GetAdaptiveExerciseAvailability;
+import fi.helsinki.cs.tmc.core.commands.DownloadAdaptiveExercise;
import fi.helsinki.cs.tmc.core.commands.GetCourseDetails;
import fi.helsinki.cs.tmc.core.commands.GetOrganizations;
import fi.helsinki.cs.tmc.core.commands.GetUnreadReviews;
@@ -175,9 +175,9 @@ public Callable downloadModelSolution(ProgressObserver observer, Exerc
return new ExceptionTrackingCallable<>(new DownloadModelSolution(observer, exercise));
}
- public Callable getStatusOfExercises(ProgressObserver observer) {
- logger.info("Creating new GetStatusOfExercises command");
- return new ExceptionTrackingCallable<>(new GetAdaptiveExerciseAvailability(observer));
+ public Callable downloadAdaptiveExercise(ProgressObserver observer) {
+ logger.info("Creating new DownloadAdaptiveExercise command");
+ return new ExceptionTrackingCallable<>(new DownloadAdaptiveExercise(observer));
}
/**
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
similarity index 66%
rename from src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java
rename to src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 801a8321..2055d9f9 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/GetAdaptiveExerciseAvailability.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -5,7 +5,9 @@
*/
package fi.helsinki.cs.tmc.core.commands;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -13,19 +15,19 @@
*
* @author sakuolin
*/
-public class GetAdaptiveExerciseAvailability extends Command {
+public class DownloadAdaptiveExercise extends Command {
private static final Logger logger = LoggerFactory.getLogger(SendFeedback.class);
- public GetAdaptiveExerciseAvailability(ProgressObserver observer) {
+ public DownloadAdaptiveExercise(ProgressObserver observer) {
super(observer);
}
@Override
- public Boolean call() throws Exception {
+ public Exercise call() throws Exception {
logger.info("Checking adaptive exercises availability");
//informObserver()
- return tmcServerCommunicationTaskFactory.getNextJson().call();
+ return tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 48b012ec..071b9408 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -151,11 +151,11 @@ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
* @throws OAuthProblemException
* @throws NotLoggedInException
*/
- public Callable getNextJson()
+ public Callable getAdaptiveExercise()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
- return wrapWithNotLoggedInException(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
- public Boolean call() throws Exception {
+ public Exercise call() throws Exception {
try {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
@@ -163,8 +163,7 @@ public Boolean call() throws Exception {
return adaptiveExerciseParser.parseFromJson(json);
}
catch (Exception ex) {
- return false;
- // do things
+ return null;
}
}
});
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 3c59a86e..58f17b46 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -21,11 +21,10 @@
public class AdaptiveExerciseParser {
// TODO: Parse exercise from address
- // TODO: Parse Boolean from JSON
private static final Logger logger = LoggerFactory.getLogger(AdaptiveExerciseParser.class);
- public Boolean parseFromJson(String json) {
+ public Exercise parseFromJson(String json) {
if (json == null) {
throw new NullPointerException("Json string is null");
}
@@ -34,7 +33,11 @@ public Boolean parseFromJson(String json) {
}
try {
JSONObject obj = new JSONObject(json);
- return obj.getBoolean("available");
+ // Check status
+ if (obj.getBoolean("available")) {
+ // Gson
+
+ }
} catch (RuntimeException ex) {
logger.warn("Failed to parse adaptive course availability", ex);
throw new RuntimeException("Failed to parse adaptive course availability: " + ex.getMessage(), ex);
diff --git a/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java b/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
index 678734d7..af54ca2b 100644
--- a/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
+++ b/src/main/java/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java
@@ -25,6 +25,7 @@
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static com.google.common.base.Preconditions.checkArgument;
/**
* Buffers {@link LoggableEvent}s and sends them to the server and/or syncs them to the disk
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
index a16c58f8..c1e9f979 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/AuthenticateUserTest.java
@@ -29,6 +29,9 @@
import org.mockito.stubbing.Answer;
import java.io.IOException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.verify;
public class AuthenticateUserTest {
@Mock
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java
index cbe6c043..26069fb7 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadOrUpdateExercisesTest.java
@@ -38,6 +38,11 @@
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.Callable;
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.verify;
public class DownloadOrUpdateExercisesTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java
index af5b4230..56c73389 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetCourseDetailsTest.java
@@ -19,6 +19,7 @@
import org.mockito.Spy;
import java.util.concurrent.Callable;
+import static com.google.common.truth.Truth.assertThat;
public class GetCourseDetailsTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java
index b25fec23..43034183 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetOrganizationsTest.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
+import static org.mockito.Mockito.verify;
public class GetOrganizationsTest {
@Mock
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java
index b9858c73..5b45a0c1 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/GetUpdatableExercisesTest.java
@@ -32,6 +32,10 @@
import java.nio.file.Path;
import java.util.concurrent.Callable;
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.mockito.Matchers.any;
public class GetUpdatableExercisesTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java
index 392f29a9..29f2f362 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/ListCoursesTest.java
@@ -22,6 +22,7 @@
import java.util.List;
import java.util.concurrent.Callable;
+import static com.google.common.truth.Truth.assertThat;
public class ListCoursesTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java
index 1c863044..6782d4a5 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/PasteWithCommentTest.java
@@ -33,6 +33,8 @@
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
public class PasteWithCommentTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java
index 46874ed8..f2d7cdab 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/SendFeedbackTest.java
@@ -30,6 +30,9 @@
import java.net.URI;
import java.util.List;
import java.util.concurrent.Callable;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
public class SendFeedbackTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java
index 9042ab77..aadf2720 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/SubmitTest.java
@@ -35,6 +35,8 @@
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
public class SubmitTest {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java b/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
index 5263551e..0099b958 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/spyware/EventSendBufferTest.java
@@ -43,6 +43,12 @@
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.verify;
public class EventSendBufferTest {
From 7375056a4c37b84aa264faccfecc4d61106457c0 Mon Sep 17 00:00:00 2001
From: Qianyue Jin
Date: Wed, 17 May 2017 11:57:13 +0300
Subject: [PATCH 23/86] download exercise by zip string
---
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 8 +++-
.../commands/DownloadExerciseByZipString.java | 39 +++++++++++++++++++
2 files changed, 46 insertions(+), 1 deletion(-)
create mode 100644 src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 2007d4aa..9379fd56 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -2,6 +2,7 @@
import fi.helsinki.cs.tmc.core.commands.AuthenticateUser;
import fi.helsinki.cs.tmc.core.commands.DownloadCompletedExercises;
+import fi.helsinki.cs.tmc.core.commands.DownloadExerciseByZipString;
import fi.helsinki.cs.tmc.core.commands.DownloadModelSolution;
import fi.helsinki.cs.tmc.core.commands.DownloadOrUpdateExercises;
import fi.helsinki.cs.tmc.core.commands.GetAdaptiveExerciseAvailability;
@@ -39,6 +40,7 @@
import fi.helsinki.cs.tmc.spyware.LoggableEvent;
import com.google.common.annotations.Beta;
+import fi.helsinki.cs.tmc.core.commands.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -179,7 +181,11 @@ public Callable getStatusOfExercises(ProgressObserver observer) {
logger.info("Creating new GetStatusOfExercises command");
return new ExceptionTrackingCallable<>(new GetAdaptiveExerciseAvailability(observer));
}
-
+
+ public Callable downloadExerciseByZipString(ProgressObserver observer, String zip) {
+ return new ExceptionTrackingCallable<>(new DownloadExerciseByZipString(observer,zip));
+ }
+
/**
* NOT IMPLEMENTED!
*
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java
new file mode 100644
index 00000000..a1a6757d
--- /dev/null
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java
@@ -0,0 +1,39 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package fi.helsinki.cs.tmc.core.commands;
+
+import fi.helsinki.cs.tmc.core.communication.http.HttpTasks;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import java.net.URI;
+import java.util.concurrent.Callable;
+
+/**
+ *
+ * @author lai
+ */
+public class DownloadExerciseByZipString extends Command{
+ private String zip;
+ public DownloadExerciseByZipString(ProgressObserver observer,String zip) {
+ super(observer);
+ this.zip=zip;
+ }
+
+ private String ToUrlByZipAndServerPath(String zip, String serverPath) {
+ return serverPath + zip;
+ }
+
+ private Exercise ExtractExerciseByBytes(byte[] input){
+ return null; //ExerciseDownloadingCommand.java
+ }
+
+ @Override
+ public Exercise call() throws Exception {
+ Callable download = new HttpTasks().getForBinary(URI.create(ToUrlByZipAndServerPath(zip, ""))); //mooc.helsin
+ return ExtractExerciseByBytes(download.call());
+ }
+
+}
From 098ec6547a632a612eaad90948162df6a99242cd Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 13:00:51 +0300
Subject: [PATCH 24/86] Gson is supposed to work, you fools
---
.../communication/serialization/AdaptiveExerciseParser.java | 5 ++++-
.../http/serialization/AdaptiveExerciseParserTest.java | 4 ++--
2 files changed, 6 insertions(+), 3 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 58f17b46..7f21ebca 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -36,8 +36,11 @@ public Exercise parseFromJson(String json) {
// Check status
if (obj.getBoolean("available")) {
// Gson
-
+ Gson gson = new GsonBuilder().create();
+ Exercise exercise = gson.fromJson(json, Exercise.class);
+ return exercise;
}
+ return null;
} catch (RuntimeException ex) {
logger.warn("Failed to parse adaptive course availability", ex);
throw new RuntimeException("Failed to parse adaptive course availability: " + ex.getMessage(), ex);
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index d5adf8f7..580a25a2 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -25,8 +25,8 @@ public void setUp() {
}
@Test
- public void testAvailability() {
- assertTrue(aep.parseFromJson("{ available: true }"));
+ public void parseFromJson() {
+ assertEquals(aep.parseFromJson("ögjdojgdpog"), null);
}
}
From 7daa16e5b17a1b0db7ce99e0eef4a5026b7a1adf Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 13:06:28 +0300
Subject: [PATCH 25/86] pls work
---
.../serialization/AdaptiveExerciseParserTest.java | 12 ------------
1 file changed, 12 deletions(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 56617bd3..91e5d12e 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -24,21 +24,9 @@ public void setUp() {
this.aep = new AdaptiveExerciseParser();
}
- /*
@Test
- public void testAvailabilityTrue() {
- assertTrue(aep.parseBooleanFromJson("{ available: true }"));
- }
-
- @Test
-<<<<<<< HEAD
public void parseFromJson() {
assertEquals(aep.parseFromJson("ögjdojgdpog"), null);
-=======
- public void testAvailabilityFalse() {
- assertFalse(aep.parseBooleanFromJson("{ available: false }"));
->>>>>>> eb18c730b91dfd34bccac7ffbe143605c26de7fb
}
- */
}
From 556d567ea04ae3ef54f97d486562960b4a3453c9 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Wed, 17 May 2017 13:17:37 +0300
Subject: [PATCH 26/86] Zip needed for Gson construction
---
.../serialization/AdaptiveExerciseParser.java | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 7f21ebca..5a4a098b 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -35,10 +35,14 @@ public Exercise parseFromJson(String json) {
JSONObject obj = new JSONObject(json);
// Check status
if (obj.getBoolean("available")) {
+ // Zip exercise
+ // ...
+ byte[] zip;
// Gson
Gson gson = new GsonBuilder().create();
- Exercise exercise = gson.fromJson(json, Exercise.class);
- return exercise;
+ //Exercise exercise = gson.fromJson(zip, Exercise.class);
+ //return exercise;
+ return null;
}
return null;
} catch (RuntimeException ex) {
From 5b0a2a6b851a6599b6c901ac584a5bb785fce4b7 Mon Sep 17 00:00:00 2001
From: fogre
Date: Wed, 17 May 2017 15:14:32 +0300
Subject: [PATCH 27/86] test
---
.../TmcServerCommunicationTaskFactory.java | 3 +-
.../serialization/AdaptiveExerciseParser.java | 28 +++++++++++++------
2 files changed, 22 insertions(+), 9 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 071b9408..a9eb6369 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -160,7 +160,8 @@ public Exercise call() throws Exception {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
String json = download.call();
- return adaptiveExerciseParser.parseFromJson(json);
+ Exercise ex = adaptiveExerciseParser.parseFromJson(json);
+ Callable b = getDownloadingExerciseZipTask(ex);
}
catch (Exception ex) {
return null;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 5a4a098b..4c984e6d 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -7,8 +7,11 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonParser;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
+import java.net.URI;
import java.util.Date;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -31,18 +34,27 @@ public Exercise parseFromJson(String json) {
if (json.trim().isEmpty()) {
throw new IllegalArgumentException("Empty input");
}
- try {
- JSONObject obj = new JSONObject(json);
+ try {;
+ Gson gson = new Gson();
+ JsonParser parser = new JsonParser();
+ JsonArray array = parser.parse(json).getAsJsonArray();
+ Boolean availability = gson.fromJson(array.get(0), Boolean.class);
+ //JSONObject obj = new JSONObject(json);
// Check status
- if (obj.getBoolean("available")) {
- // Zip exercise
+ if (availability) {
+ String zip_url = gson.fromJson(array.get(1), String.class);
+ Exercise ex = new Exercise();
+ ex.setDownloadUrl(URI.create(zip_url));
+ return ex;
+
// ...
- byte[] zip;
+
+ //byte[] zip;
// Gson
- Gson gson = new GsonBuilder().create();
- //Exercise exercise = gson.fromJson(zip, Exercise.class);
+ //gson = new GsonBuilder().create();
+ //ercise exercise = gson.fromJson(array.get(1), Exercise.class);
//return exercise;
- return null;
+ //return zip_url;
}
return null;
} catch (RuntimeException ex) {
From c66e64897ab906e4f3816329cf57882326c11101 Mon Sep 17 00:00:00 2001
From: Qianyue Jin
Date: Wed, 17 May 2017 15:55:09 +0300
Subject: [PATCH 28/86] download and extract, return void, build fail
---
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 2 +-
.../commands/DownloadAdaptiveExercise.java | 7 +++---
.../TmcServerCommunicationTaskFactory.java | 22 ++++++++++++++-----
3 files changed, 22 insertions(+), 9 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 35adada7..b458d1a6 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -177,7 +177,7 @@ public Callable downloadModelSolution(ProgressObserver observer, Exerc
return new ExceptionTrackingCallable<>(new DownloadModelSolution(observer, exercise));
}
- public Callable downloadAdaptiveExercise(ProgressObserver observer) {
+ public Callable downloadAdaptiveExercise(ProgressObserver observer) {
logger.info("Creating new DownloadAdaptiveExercise command");
return new ExceptionTrackingCallable<>(new DownloadAdaptiveExercise(observer));
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 2055d9f9..f82aabcd 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -15,7 +15,7 @@
*
* @author sakuolin
*/
-public class DownloadAdaptiveExercise extends Command {
+public class DownloadAdaptiveExercise extends Command {
private static final Logger logger = LoggerFactory.getLogger(SendFeedback.class);
@@ -24,10 +24,11 @@ public DownloadAdaptiveExercise(ProgressObserver observer) {
}
@Override
- public Exercise call() throws Exception {
+ public Void call() throws Exception {
logger.info("Checking adaptive exercises availability");
//informObserver()
- return tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
+ tmcServerCommunicationTaskFactory.downloadAndExtractAdaptiveExercise().call();
+ return null;
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index a9eb6369..f64049d4 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -1,5 +1,7 @@
package fi.helsinki.cs.tmc.core.communication;
+import fi.helsinki.cs.tmc.core.commands.*;
+
import fi.helsinki.cs.tmc.core.communication.http.HttpTasks;
import fi.helsinki.cs.tmc.core.communication.http.UriUtils;
import fi.helsinki.cs.tmc.core.communication.oauth2.Oauth;
@@ -28,6 +30,7 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
+import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
import org.apache.commons.io.IOUtils;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
@@ -38,6 +41,9 @@
import java.io.OutputStreamWriter;
import java.net.URI;
import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -151,24 +157,30 @@ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
* @throws OAuthProblemException
* @throws NotLoggedInException
*/
- public Callable getAdaptiveExercise()
+ public Callable downloadAndExtractAdaptiveExercise()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
- return wrapWithNotLoggedInException(new Callable() {
+ return wrapWithNotLoggedInException(new Callable() {
@Override
- public Exercise call() throws Exception {
+ public Void call() throws Exception {
try {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
String json = download.call();
Exercise ex = adaptiveExerciseParser.parseFromJson(json);
- Callable b = getDownloadingExerciseZipTask(ex);
+ byte[] b = getDownloadingExerciseZipTask(ex).call();
+ Path temp = Files.createTempFile("tmc-exercise-", ".zip");
+ Files.write(temp, b);
+ Path target = TmcSettingsHolder.get().getTmcProjectDirectory().resolve("target-example");
+ TmcLangsHolder.get().extractAndRewriteEveryhing(temp, target);
+
}
catch (Exception ex) {
- return null;
}
+ return null;
}
});
}
+
public Callable> getDownloadingCourseListTask() {
return wrapWithNotLoggedInException(new Callable>() {
From bcd2a4698d8e1a1d92afa5070267e202866b97a2 Mon Sep 17 00:00:00 2001
From: fogre
Date: Wed, 17 May 2017 16:36:41 +0300
Subject: [PATCH 29/86] Adapt command changes... again.
---
.../commands/DownloadAdaptiveExercise.java | 20 ++++++++++++++++---
.../TmcServerCommunicationTaskFactory.java | 20 +++++++++++++++++++
.../AdaptiveExerciseParserTest.java | 4 ++--
3 files changed, 39 insertions(+), 5 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 2055d9f9..de0e9559 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -5,8 +5,11 @@
*/
package fi.helsinki.cs.tmc.core.commands;
+import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.Progress;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -15,7 +18,7 @@
*
* @author sakuolin
*/
-public class DownloadAdaptiveExercise extends Command {
+public class DownloadAdaptiveExercise extends ExerciseDownloadingCommand {
private static final Logger logger = LoggerFactory.getLogger(SendFeedback.class);
@@ -25,9 +28,20 @@ public DownloadAdaptiveExercise(ProgressObserver observer) {
@Override
public Exercise call() throws Exception {
+ Progress progress = new Progress(3);
logger.info("Checking adaptive exercises availability");
- //informObserver()
- return tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
+ //informObserver
+ String json = tmcServerCommunicationTaskFactory.getJsonString().call();
+ AdaptiveExerciseParser aparser = new AdaptiveExerciseParser();
+ Exercise ex = aparser.parseFromJson(json);
+ //ex.setName = "jotain"
+ //ex.setCourseName = "Jotain
+ //Tallennuspolku riippuu edellämainituista nimistä (TMCroot)
+ byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(ex).call();
+ //checkInterrupt();
+ extractProject(zipb, ex, progress);
+ return ex;
+ // byte[] zip = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index a9eb6369..4a807afb 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -151,6 +151,25 @@ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
* @throws OAuthProblemException
* @throws NotLoggedInException
*/
+
+ public Callable getJsonString(){
+ return wrapWithNotLoggedInException(new Callable(){
+ @Override
+ public String call() throws Exception {
+ try{
+ Callable download = new HttpTasks().
+ getForText(URI.create("localhost:3200/next.json"));
+ String json = download.call();
+ return json;
+ }
+ catch (Exception ex) {
+ return null;
+ }
+ }
+ });
+
+
+ }
public Callable getAdaptiveExercise()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
return wrapWithNotLoggedInException(new Callable() {
@@ -162,6 +181,7 @@ public Exercise call() throws Exception {
String json = download.call();
Exercise ex = adaptiveExerciseParser.parseFromJson(json);
Callable b = getDownloadingExerciseZipTask(ex);
+ return ex;
}
catch (Exception ex) {
return null;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 91e5d12e..4583f17d 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -18,7 +18,7 @@
public class AdaptiveExerciseParserTest {
private AdaptiveExerciseParser aep;
-
+/*
@Before
public void setUp() {
this.aep = new AdaptiveExerciseParser();
@@ -28,5 +28,5 @@ public void setUp() {
public void parseFromJson() {
assertEquals(aep.parseFromJson("ögjdojgdpog"), null);
}
-
+ */
}
From 454b87afaad6035c783d8a6d253b101c54f16ffd Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 08:49:14 +0300
Subject: [PATCH 30/86] Fix for core command, Json return
---
src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java | 2 +-
.../cs/tmc/core/commands/DownloadAdaptiveExercise.java | 2 +-
.../communication/TmcServerCommunicationTaskFactory.java | 6 +++---
.../communication/serialization/AdaptiveExerciseParser.java | 4 ++--
4 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 35adada7..249dba43 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -177,7 +177,7 @@ public Callable downloadModelSolution(ProgressObserver observer, Exerc
return new ExceptionTrackingCallable<>(new DownloadModelSolution(observer, exercise));
}
- public Callable downloadAdaptiveExercise(ProgressObserver observer) {
+ public ExceptionTrackingCallable downloadAdaptiveExercise(ProgressObserver observer) {
logger.info("Creating new DownloadAdaptiveExercise command");
return new ExceptionTrackingCallable<>(new DownloadAdaptiveExercise(observer));
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index de0e9559..0193c59f 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -18,7 +18,7 @@
*
* @author sakuolin
*/
-public class DownloadAdaptiveExercise extends ExerciseDownloadingCommand {
+public class DownloadAdaptiveExercise extends ExerciseDownloadingCommand {
private static final Logger logger = LoggerFactory.getLogger(SendFeedback.class);
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 4a807afb..60a11fbd 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -156,14 +156,14 @@ public Callable getJsonString(){
return wrapWithNotLoggedInException(new Callable(){
@Override
public String call() throws Exception {
- try{
+ try {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
String json = download.call();
return json;
- }
+ }
catch (Exception ex) {
- return null;
+ return "{}";
}
}
});
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 4c984e6d..6f01b710 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -58,8 +58,8 @@ public Exercise parseFromJson(String json) {
}
return null;
} catch (RuntimeException ex) {
- logger.warn("Failed to parse adaptive course availability", ex);
- throw new RuntimeException("Failed to parse adaptive course availability: " + ex.getMessage(), ex);
+ logger.warn("Failed to parse an adaptive course from URL", ex);
+ throw new RuntimeException("Failed to parse an adaptive course from URL: " + ex.getMessage(), ex);
}
}
From 43ebad86366cc46ee7a35fa4360d9ee60cad50d8 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 09:08:40 +0300
Subject: [PATCH 31/86] Git, what are you doing?
---
src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 249dba43..35adada7 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -177,7 +177,7 @@ public Callable downloadModelSolution(ProgressObserver observer, Exerc
return new ExceptionTrackingCallable<>(new DownloadModelSolution(observer, exercise));
}
- public ExceptionTrackingCallable downloadAdaptiveExercise(ProgressObserver observer) {
+ public Callable downloadAdaptiveExercise(ProgressObserver observer) {
logger.info("Creating new DownloadAdaptiveExercise command");
return new ExceptionTrackingCallable<>(new DownloadAdaptiveExercise(observer));
}
From 0e35a55574bfb85529ffd0403407b9e7c61fa641 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 09:53:50 +0300
Subject: [PATCH 32/86] Problems fixed, continuing with the style previously
adapted
---
.../commands/DownloadAdaptiveExercise.java | 13 +++-----
.../TmcServerCommunicationTaskFactory.java | 31 +------------------
.../serialization/AdaptiveExerciseParser.java | 26 ++++++----------
3 files changed, 16 insertions(+), 54 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 0193c59f..ef73b807 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -5,11 +5,9 @@
*/
package fi.helsinki.cs.tmc.core.commands;
-import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.Progress;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
-import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,16 +29,15 @@ public Exercise call() throws Exception {
Progress progress = new Progress(3);
logger.info("Checking adaptive exercises availability");
//informObserver
- String json = tmcServerCommunicationTaskFactory.getJsonString().call();
- AdaptiveExerciseParser aparser = new AdaptiveExerciseParser();
- Exercise ex = aparser.parseFromJson(json);
+ Exercise exercise =
+ tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
//ex.setName = "jotain"
//ex.setCourseName = "Jotain
//Tallennuspolku riippuu edellämainituista nimistä (TMCroot)
- byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(ex).call();
+ byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
//checkInterrupt();
- extractProject(zipb, ex, progress);
- return ex;
+ extractProject(zipb, exercise, progress);
+ return exercise;
// byte[] zip = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 60a11fbd..242bae48 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -142,34 +142,7 @@ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
url = UriUtils.withQueryParam(url, "access_token", oauth.getToken());
return url;
}
-
- /**
- * Test for returning skillifier stuff.
- *
- * @return next.json URI
- * @throws OAuthSystemException
- * @throws OAuthProblemException
- * @throws NotLoggedInException
- */
-
- public Callable getJsonString(){
- return wrapWithNotLoggedInException(new Callable(){
- @Override
- public String call() throws Exception {
- try {
- Callable download = new HttpTasks().
- getForText(URI.create("localhost:3200/next.json"));
- String json = download.call();
- return json;
- }
- catch (Exception ex) {
- return "{}";
- }
- }
- });
-
- }
public Callable getAdaptiveExercise()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
return wrapWithNotLoggedInException(new Callable() {
@@ -179,9 +152,7 @@ public Exercise call() throws Exception {
Callable download = new HttpTasks().
getForText(URI.create("localhost:3200/next.json"));
String json = download.call();
- Exercise ex = adaptiveExerciseParser.parseFromJson(json);
- Callable b = getDownloadingExerciseZipTask(ex);
- return ex;
+ return adaptiveExerciseParser.parseFromJson(json);
}
catch (Exception ex) {
return null;
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 6f01b710..38a11cfc 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -35,26 +35,20 @@ public Exercise parseFromJson(String json) {
throw new IllegalArgumentException("Empty input");
}
try {;
- Gson gson = new Gson();
- JsonParser parser = new JsonParser();
- JsonArray array = parser.parse(json).getAsJsonArray();
- Boolean availability = gson.fromJson(array.get(0), Boolean.class);
- //JSONObject obj = new JSONObject(json);
+ JSONObject obj = new JSONObject(json);
// Check status
- if (availability) {
- String zip_url = gson.fromJson(array.get(1), String.class);
+ if (obj.getBoolean("availability")) {
+ String zip_url = obj.getString("zip_url");
Exercise ex = new Exercise();
ex.setDownloadUrl(URI.create(zip_url));
+ // Käytä GSonia parseemaan kuin Course
+ Gson gson =
+ new GsonBuilder()
+ .registerTypeAdapter(Date.class, new CustomDateDeserializer())
+ .create();
+ Exercise exercise = gson.fromJson(json, Exercise.class);
+ // vanha return
return ex;
-
- // ...
-
- //byte[] zip;
- // Gson
- //gson = new GsonBuilder().create();
- //ercise exercise = gson.fromJson(array.get(1), Exercise.class);
- //return exercise;
- //return zip_url;
}
return null;
} catch (RuntimeException ex) {
From e457740395f3b90c19a11c7e0c22b66a4ed8dcb0 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 09:55:26 +0300
Subject: [PATCH 33/86] Problems fixed, continuing with the style previously
adapted
---
.../core/communication/serialization/AdaptiveExerciseParser.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 38a11cfc..d4162769 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -48,6 +48,7 @@ public Exercise parseFromJson(String json) {
.create();
Exercise exercise = gson.fromJson(json, Exercise.class);
// vanha return
+ // tyhjä kommentti koska branch llälä
return ex;
}
return null;
From dcba43705db18bc8fe6213814e6d36fe6b829bbd Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 09:57:53 +0300
Subject: [PATCH 34/86] Problems fixed, continuing with the style previously
adapted
---
.../core/communication/serialization/AdaptiveExerciseParser.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index d4162769..fe5985c0 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -49,6 +49,7 @@ public Exercise parseFromJson(String json) {
Exercise exercise = gson.fromJson(json, Exercise.class);
// vanha return
// tyhjä kommentti koska branch llälä
+ // posdjgpofpgdfojofgjpofgjhfgojhgogf
return ex;
}
return null;
From 207ba32031bd7bbcaa48c4dc9951a69e37e6da05 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:21:59 +0300
Subject: [PATCH 35/86] Added Tests for AdaptiveExerciseParser
---
.../AdaptiveExerciseParserTest.java | 23 ++++++++++++++-----
1 file changed, 17 insertions(+), 6 deletions(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 4583f17d..defc37ad 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -6,6 +6,7 @@
package fi.helsinki.cs.tmc.core.communication.http.serialization;
import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
import org.junit.Before;
import org.junit.Test;
@@ -17,16 +18,26 @@
*/
public class AdaptiveExerciseParserTest {
- private AdaptiveExerciseParser aep;
-/*
+ private AdaptiveExerciseParser adaptiveParser;
+
@Before
public void setUp() {
- this.aep = new AdaptiveExerciseParser();
+ this.adaptiveParser = new AdaptiveExerciseParser();
}
@Test
- public void parseFromJson() {
- assertEquals(aep.parseFromJson("ögjdojgdpog"), null);
+ public void jsonEmptyException() {
+ assertEquals(null, new NullPointerException("Json string is null"));
+ }
+
+ @Test
+ public void jsonIllegalException() {
+ assertEquals(" ", new IllegalArgumentException("Empty input"));
+ }
+
+ @Test
+ public void exerciseHasZipUrl() {
+ Exercise exercise = adaptiveParser.parseFromJson("{ zip_url: not-empty }");
+ assertEquals(exercise.getZipUrl(), "not-empty");
}
- */
}
From 1ef28d28915c70930633059479de467d5144ae80 Mon Sep 17 00:00:00 2001
From: Mavai
Date: Thu, 18 May 2017 10:27:44 +0300
Subject: [PATCH 36/86] parser editing and tests
---
.../serialization/AdaptiveExerciseParser.java | 20 +++++++++----------
.../AdaptiveExerciseParserTest.java | 17 ++++++++++++----
2 files changed, 23 insertions(+), 14 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 6f01b710..a47072b3 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -5,10 +5,7 @@
*/
package fi.helsinki.cs.tmc.core.communication.serialization;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonParser;
+import com.google.gson.*;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import java.net.URI;
@@ -35,14 +32,17 @@ public Exercise parseFromJson(String json) {
throw new IllegalArgumentException("Empty input");
}
try {;
- Gson gson = new Gson();
- JsonParser parser = new JsonParser();
- JsonArray array = parser.parse(json).getAsJsonArray();
- Boolean availability = gson.fromJson(array.get(0), Boolean.class);
- //JSONObject obj = new JSONObject(json);
+ //Gson gson = new Gson();
+ //JsonParser parser = new JsonParser();
+ //JsonElement element = parser.parse(json);
+ //JsonArray array = element.getAsJsonArray();
+ //Boolean availability = gson.fromJson(array.get(0), Boolean.class);
+ JSONObject obj = new JSONObject(json);
+ boolean availability = obj.getBoolean("available");
// Check status
if (availability) {
- String zip_url = gson.fromJson(array.get(1), String.class);
+ String zip_url = obj.getString("zip_url");
+ //String zip_url = gson.fromJson(array.get(1), String.class);
Exercise ex = new Exercise();
ex.setDownloadUrl(URI.create(zip_url));
return ex;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 4583f17d..12b302e4 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -7,9 +7,12 @@
import fi.helsinki.cs.tmc.core.communication.serialization.AdaptiveExerciseParser;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
import org.junit.Before;
import org.junit.Test;
+import java.net.URI;
+
import static org.junit.Assert.*;
/**
@@ -18,15 +21,21 @@
public class AdaptiveExerciseParserTest {
private AdaptiveExerciseParser aep;
-/*
+
@Before
public void setUp() {
this.aep = new AdaptiveExerciseParser();
}
@Test
- public void parseFromJson() {
- assertEquals(aep.parseFromJson("ögjdojgdpog"), null);
+ public void adaptiveParserReturnsNullWhenNotAvailable() {
+ assertEquals(aep.parseFromJson("{ available: false }"), null);
}
- */
+
+ @Test
+ public void adaptiveParserReturnsExerciseWhenAvailable() {
+ Exercise ex = aep.parseFromJson("{ available: true, zip_url: \"/path/to/zip\" }");
+ assertEquals(URI.create("/path/to/zip"), ex.getZipUrl());
+ }
+
}
From e8b9c31a9609cab1a3c765dd28e1277efd45843a Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:28:32 +0300
Subject: [PATCH 37/86] Fixes for new Tests
---
.../http/serialization/AdaptiveExerciseParserTest.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index defc37ad..65ebf29b 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -27,12 +27,12 @@ public void setUp() {
@Test
public void jsonEmptyException() {
- assertEquals(null, new NullPointerException("Json string is null"));
+ assertEquals(adaptiveParser.parseFromJson(null), new NullPointerException("Json string is null"));
}
@Test
public void jsonIllegalException() {
- assertEquals(" ", new IllegalArgumentException("Empty input"));
+ assertEquals(adaptiveParser.parseFromJson(" "), new IllegalArgumentException("Empty input"));
}
@Test
From 4272963081bf2dad6ae94dc59b877a052bc97d3d Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:33:56 +0300
Subject: [PATCH 38/86] Fixes for new Tests
---
.../http/serialization/AdaptiveExerciseParserTest.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 65ebf29b..039de675 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -25,14 +25,14 @@ public void setUp() {
this.adaptiveParser = new AdaptiveExerciseParser();
}
- @Test
+ @Test(expected = NullPointerException.class)
public void jsonEmptyException() {
- assertEquals(adaptiveParser.parseFromJson(null), new NullPointerException("Json string is null"));
+ adaptiveParser.parseFromJson(null);
}
- @Test
+ @Test(expected = IllegalArgumentException.class)
public void jsonIllegalException() {
- assertEquals(adaptiveParser.parseFromJson(" "), new IllegalArgumentException("Empty input"));
+ adaptiveParser.parseFromJson(" ");
}
@Test
From 44e9cb6db0b2920c3ac451c02b4fa9fe4d32260b Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:36:29 +0300
Subject: [PATCH 39/86] Fixes for new Tests
---
.../serialization/AdaptiveExerciseParser.java | 2 +-
.../http/serialization/AdaptiveExerciseParserTest.java | 8 +++++++-
2 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index fe5985c0..de0103b3 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -37,7 +37,7 @@ public Exercise parseFromJson(String json) {
try {;
JSONObject obj = new JSONObject(json);
// Check status
- if (obj.getBoolean("availability")) {
+ if (obj.getBoolean("available")) {
String zip_url = obj.getString("zip_url");
Exercise ex = new Exercise();
ex.setDownloadUrl(URI.create(zip_url));
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 039de675..87742cd9 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -37,7 +37,13 @@ public void jsonIllegalException() {
@Test
public void exerciseHasZipUrl() {
- Exercise exercise = adaptiveParser.parseFromJson("{ zip_url: not-empty }");
+ Exercise exercise = adaptiveParser.parseFromJson("{ available: true, zip_url: not-empty }");
+ assertEquals(exercise.getZipUrl(), "not-empty");
+ }
+
+ @Test
+ public void exerciseNotAvailable() {
+ Exercise exercise = adaptiveParser.parseFromJson("{ available: false, zip_url: not-empty }");
assertEquals(exercise.getZipUrl(), "not-empty");
}
}
From 950057507d9b751ba24e9bf50e0186e46768fcc9 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:39:35 +0300
Subject: [PATCH 40/86] Fixes for new Tests
---
.../http/serialization/AdaptiveExerciseParserTest.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 87742cd9..036d74b1 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -38,12 +38,13 @@ public void jsonIllegalException() {
@Test
public void exerciseHasZipUrl() {
Exercise exercise = adaptiveParser.parseFromJson("{ available: true, zip_url: not-empty }");
+ System.out.println(exercise.getZipUrl());
assertEquals(exercise.getZipUrl(), "not-empty");
}
@Test
public void exerciseNotAvailable() {
Exercise exercise = adaptiveParser.parseFromJson("{ available: false, zip_url: not-empty }");
- assertEquals(exercise.getZipUrl(), "not-empty");
+ assertEquals(exercise, null);
}
}
From b38761cc50b06cfcf4531e0a548de78657866619 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:46:19 +0300
Subject: [PATCH 41/86] Fixes for new Tests
---
.../http/serialization/AdaptiveExerciseParserTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 036d74b1..9e5e28be 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -39,7 +39,7 @@ public void jsonIllegalException() {
public void exerciseHasZipUrl() {
Exercise exercise = adaptiveParser.parseFromJson("{ available: true, zip_url: not-empty }");
System.out.println(exercise.getZipUrl());
- assertEquals(exercise.getZipUrl(), "not-empty");
+ assertEquals(exercise.getZipUrl().toString(), "not-empty");
}
@Test
From 4ba5c733694895acb888ade6e776cce4034dbc27 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 10:54:20 +0300
Subject: [PATCH 42/86] Imports and such little things fixed
---
.../serialization/AdaptiveExerciseParser.java | 12 +++++-------
1 file changed, 5 insertions(+), 7 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index de0103b3..0ec41903 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -5,14 +5,14 @@
*/
package fi.helsinki.cs.tmc.core.communication.serialization;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonParser;
-import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
+
import java.net.URI;
import java.util.Date;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -23,8 +23,6 @@
*/
public class AdaptiveExerciseParser {
- // TODO: Parse exercise from address
-
private static final Logger logger = LoggerFactory.getLogger(AdaptiveExerciseParser.class);
public Exercise parseFromJson(String json) {
From 8d550e2caa77177ea88ff7866dfa6a54e402b2b2 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 11:19:42 +0300
Subject: [PATCH 43/86] New Tests for DownloadAdaptiveExercise
---
.../DownloadAdaptiveExerciseTest.java | 61 +++++++++++++++++++
1 file changed, 61 insertions(+)
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
new file mode 100644
index 00000000..985d5d7c
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
@@ -0,0 +1,61 @@
+package fi.helsinki.cs.tmc.core.commands;
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+import fi.helsinki.cs.tmc.core.commands.DownloadAdaptiveExercise;
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
+
+import java.util.concurrent.Callable;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.mockito.Mock;
+import static org.mockito.Mockito.spy;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
+/**
+ *
+ * @author sakuolin
+ */
+public class DownloadAdaptiveExerciseTest {
+
+ @Mock ProgressObserver mockObserver;
+ @Spy TmcSettings settings = new MockSettings();
+ @Mock Exercise exercise;
+
+ TaskExecutor langs;
+
+ private Command command;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ langs = spy(new TaskExecutorImpl());
+ TmcSettingsHolder.set(settings);
+ TmcLangsHolder.set(langs);
+ command = new DownloadAdaptiveExercise(mockObserver);
+ }
+
+ @Test
+ public void exerciseExists() throws Exception {
+ exercise = command.call();
+ assertNotEquals(null, exercise);
+ }
+
+}
From 5bfa059462a71300bc3d173f8bff1e3df05617e3 Mon Sep 17 00:00:00 2001
From: Saku Olin
Date: Thu, 18 May 2017 11:25:44 +0300
Subject: [PATCH 44/86] Tests not viable, check functionality otherwise
---
.../DownloadAdaptiveExerciseTest.java | 61 -------------------
1 file changed, 61 deletions(-)
delete mode 100644 src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
deleted file mode 100644
index 985d5d7c..00000000
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package fi.helsinki.cs.tmc.core.commands;
-
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-
-import fi.helsinki.cs.tmc.core.commands.DownloadAdaptiveExercise;
-import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
-import fi.helsinki.cs.tmc.core.domain.Exercise;
-import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
-import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
-import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
-import fi.helsinki.cs.tmc.core.utils.MockSettings;
-import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
-import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
-
-import java.util.concurrent.Callable;
-
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import static org.junit.Assert.*;
-import org.mockito.Mock;
-import static org.mockito.Mockito.spy;
-import org.mockito.MockitoAnnotations;
-import org.mockito.Spy;
-
-/**
- *
- * @author sakuolin
- */
-public class DownloadAdaptiveExerciseTest {
-
- @Mock ProgressObserver mockObserver;
- @Spy TmcSettings settings = new MockSettings();
- @Mock Exercise exercise;
-
- TaskExecutor langs;
-
- private Command command;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- langs = spy(new TaskExecutorImpl());
- TmcSettingsHolder.set(settings);
- TmcLangsHolder.set(langs);
- command = new DownloadAdaptiveExercise(mockObserver);
- }
-
- @Test
- public void exerciseExists() throws Exception {
- exercise = command.call();
- assertNotEquals(null, exercise);
- }
-
-}
From bc15546b2feeabe168eb19f2b4c42b4742fdf1f8 Mon Sep 17 00:00:00 2001
From: Qianyue Jin
Date: Thu, 18 May 2017 13:11:44 +0300
Subject: [PATCH 45/86] failed
---
.../commands/DownloadAdaptiveExercise.java | 30 +++++++++++++++----
.../serialization/AdaptiveExerciseParser.java | 29 ++++++++++--------
2 files changed, 42 insertions(+), 17 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index ef73b807..7c29241f 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -31,14 +31,34 @@ public Exercise call() throws Exception {
//informObserver
Exercise exercise =
tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
- //ex.setName = "jotain"
- //ex.setCourseName = "Jotain
+
+ //long nanotime = System.nanoTime();
+ //exercise.setName("exname " + nanotime); // set temp exercise name
+ //exercise.setCourseName("coname " + nanotime); // set temp course name
//Tallennuspolku riippuu edellämainituista nimistä (TMCroot)
+
byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
- //checkInterrupt();
+ //checkInterrupt(); // jos tarvi???
+
extractProject(zipb, exercise, progress);
+
+ // säättää kurssi nimet puratun polun perusteella
+ //Path exerciseDirectory = TmcSettingsHolder.get().getTmcProjectDirectory(); // menee exercise directory (mihin unzippattu)
+ //Path unzipTempConameNanotime = exerciseDirectory.resolve(exercise.getCourseName()); // menee kansioon "coname " + nanotime
+ //Path unzipTempExnameNanotime = unzipTempConameNanotime.resolve(exercise.getName()); // menee kansioon "exname " + nanotime
+ //File unzipTempFolder = unzipTempExnameNanotime.toFile();
+ //File superFolderWithNameOsaa = unzipTempFolder.listFiles()[0]; // menee ainoaan kansioon, esim. "osaa01"
+ //exercise.setCourseName(superFolderWithNameOsaa.getName()); // set course name "osaa01" //tai???
+ //File exerciseFolder = superFolderWithNameOsaa.listFiles()[0]; // menee ainoaan tehtävän kansioon, esim. "Osaa01_01.AdaLovelace"
+ //exercise.setName(exerciseFolder.getName()); // exercise.setName(exer.getName().split(".")[1]); // set exercise name "AdaLovelace" //tai??
+
+ // siirtää purattu tiedosto exercise directoryyn
+ // mv exercise_directory/"coname "+ nanotime / "exname " + nanotime / "osaa01" exercise_directocty
+ //Files.move(superFolderWithNameOsaa.toPath(), exerciseDirectory);
+ // cleanup temp
+ // rmdir "coname " + nanotime
+ //Files.deleteIfExists(unzipTempConameNanotime);
+
return exercise;
- // byte[] zip = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
}
-
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 0ec41903..a9923d59 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -37,18 +37,23 @@ public Exercise parseFromJson(String json) {
// Check status
if (obj.getBoolean("available")) {
String zip_url = obj.getString("zip_url");
- Exercise ex = new Exercise();
- ex.setDownloadUrl(URI.create(zip_url));
- // Käytä GSonia parseemaan kuin Course
- Gson gson =
- new GsonBuilder()
- .registerTypeAdapter(Date.class, new CustomDateDeserializer())
- .create();
- Exercise exercise = gson.fromJson(json, Exercise.class);
- // vanha return
- // tyhjä kommentti koska branch llälä
- // posdjgpofpgdfojofgjpofgjhfgojhgogf
- return ex;
+
+ if (true){
+ Exercise ex = new Exercise();
+ ex.setDownloadUrl(URI.create(zip_url));
+ return ex;
+ }else{
+ // Käytä GSonia parseemaan kuin Course
+ Gson gson =
+ new GsonBuilder()
+ .registerTypeAdapter(Date.class, new CustomDateDeserializer())
+ .create();
+ Exercise exercise = gson.fromJson(json, Exercise.class);
+ // vanha return
+ // tyhjä kommentti koska branch llälä
+ // posdjgpofpgdfojofgjpofgjhfgojhgogf
+ return exercise;
+ }
}
return null;
} catch (RuntimeException ex) {
From 7901d4fdf7b554d8607a7399eaa9846b21eaa7e9 Mon Sep 17 00:00:00 2001
From: Qianyue Jin
Date: Thu, 18 May 2017 14:55:17 +0300
Subject: [PATCH 46/86] new
---
.../commands/DownloadAdaptiveExercise.java | 108 +++++++++++++++---
.../ExerciseDownloadFailedException.java | 5 +
.../ExtractingExericeFailedException.java | 7 ++
3 files changed, 106 insertions(+), 14 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 7c29241f..2866129d 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -8,6 +8,16 @@
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.Progress;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.exceptions.ExerciseDownloadFailedException;
+import fi.helsinki.cs.tmc.core.exceptions.ExtractingExericeFailedException;
+import fi.helsinki.cs.tmc.core.exceptions.TmcInterruptionException;
+import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,25 +50,95 @@ public Exercise call() throws Exception {
byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
//checkInterrupt(); // jos tarvi???
- extractProject(zipb, exercise, progress);
+ //extractProject(zipb, exercise, progress);
// säättää kurssi nimet puratun polun perusteella
- //Path exerciseDirectory = TmcSettingsHolder.get().getTmcProjectDirectory(); // menee exercise directory (mihin unzippattu)
+ Path exerciseDirectory = TmcSettingsHolder.get().getTmcProjectDirectory(); // menee exercise directory (mihin unzippattu)
+
+ Path unzippedFolderTemp = extractToTempFolder(zipb, exercise, progress);
+ cleanExtractedExerciseWithTempNames(exercise, unzippedFolderTemp, exerciseDirectory);
+
+ return exercise;
+ }
+
+ private Path extractToTempFolder (byte[] zipb, Exercise exercise, Progress progress)
+ throws ExtractingExericeFailedException, ExerciseDownloadFailedException, TmcInterruptionException{
+ logger.info("Extracting exercise");
+ Path zipTemp;
+ logger.debug("Writing zip to temporary location");
+ try {
+ zipTemp = Files.createTempFile("tmc-exercise-", ".zip");
+ Files.write(zipTemp, zipb);
+ logger.debug("Successfully write temporary exercise zip to dist");
+ } catch (IOException ex) {
+ logger.warn("Failed to write downloaded zip to disk", ex);
+ throw new ExerciseDownloadFailedException(exercise.getDownloadUrl(), ex);
+ }
+ checkInterrupt();
+ logger.debug("Zip file successfully written");
+
+
+ informObserver(progress.incrementAndGet(), "Extracting exercise from " + exercise.getDownloadUrl());
+ Path unzipFolderTemp = null;
+ try {
+ unzipFolderTemp = Files.createTempDirectory("tmc-exercise-unzipped-"+System.nanoTime());
+ try{
+ TmcLangsHolder.get().extractProject(zipTemp, unzipFolderTemp);
+ logger.info("Successfully extracted exercise");
+ } catch (Exception ex) {
+ logger.warn(
+ "Failed to extract project from "
+ + zipTemp
+ + " to "
+ + unzipFolderTemp,
+ ex);
+ throw new ExtractingExericeFailedException(exercise.getDownloadUrl(), ex);
+ }
+ }
+ catch (IOException ex) {
+ logger.warn("Failed to create temporary folder tmc-exercise-unzipped");
+ throw new ExtractingExericeFailedException(exercise.getDownloadUrl(), ex);
+ }
+
+ try {
+ Files.deleteIfExists(zipTemp);
+ logger.debug("Cleaned up temporary zip files");
+ } catch (IOException ex) {
+ logger.warn("Failed to delete temporary exercise zip from " + zipTemp, ex);
+ }
+
+ return unzipFolderTemp;
+ }
+
+ private void cleanExtractedExerciseWithTempNames(Exercise exercise, Path unzipFolderTemp, Path exerciseDirectory) {
//Path unzipTempConameNanotime = exerciseDirectory.resolve(exercise.getCourseName()); // menee kansioon "coname " + nanotime
//Path unzipTempExnameNanotime = unzipTempConameNanotime.resolve(exercise.getName()); // menee kansioon "exname " + nanotime
//File unzipTempFolder = unzipTempExnameNanotime.toFile();
//File superFolderWithNameOsaa = unzipTempFolder.listFiles()[0]; // menee ainoaan kansioon, esim. "osaa01"
- //exercise.setCourseName(superFolderWithNameOsaa.getName()); // set course name "osaa01" //tai???
- //File exerciseFolder = superFolderWithNameOsaa.listFiles()[0]; // menee ainoaan tehtävän kansioon, esim. "Osaa01_01.AdaLovelace"
- //exercise.setName(exerciseFolder.getName()); // exercise.setName(exer.getName().split(".")[1]); // set exercise name "AdaLovelace" //tai??
-
- // siirtää purattu tiedosto exercise directoryyn
- // mv exercise_directory/"coname "+ nanotime / "exname " + nanotime / "osaa01" exercise_directocty
- //Files.move(superFolderWithNameOsaa.toPath(), exerciseDirectory);
- // cleanup temp
- // rmdir "coname " + nanotime
- //Files.deleteIfExists(unzipTempConameNanotime);
-
- return exercise;
+ File superFolderWithNameOsaa = unzipFolderTemp.toFile().listFiles()[0]; // menee ainoaan kansioon, esim. "osaa01"
+ exercise.setCourseName(superFolderWithNameOsaa.getName()); // set course name "osaa01" //tai???
+ File exerciseFolder = superFolderWithNameOsaa.listFiles()[0]; // menee ainoaan tehtävän kansioon, esim. "Osaa01_01.AdaLovelace"
+ exercise.setName(exerciseFolder.getName()); // exercise.setName(exer.getName().split(".")[1]); // set exercise name "AdaLovelace" //tai??
+ try {
+ // siirtää purattu tiedosto exercise directoryyn
+ // mv exercise_directory/"coname "+ nanotime / "exname " + nanotime / "osaa01" exercise_directocty
+ logger.info("start moving temporary unzip to final location");
+ Files.move(superFolderWithNameOsaa.toPath(), exerciseDirectory);
+ logger.debug("successfully moved temporary unzip to final location");
+ }
+ catch (IOException ex) {
+ logger.warn("Failed to move temporary unzip exercise to final location" + unzipFolderTemp, ex);
+ // throw jtn
+ }
+ try {
+ // cleanup temp
+ // rmdir "coname " + nanotime
+ //Files.deleteIfExists(unzipTempConameNanotime);
+ Files.deleteIfExists(unzipFolderTemp);
+ logger.debug("successfully deleted temporary unzip folder");
+ }
+ catch (IOException ex) {
+ logger.warn("Failed to delete temporary unzip folder");
+ }
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExerciseDownloadFailedException.java b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExerciseDownloadFailedException.java
index 691b1c8c..0e8fe71d 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExerciseDownloadFailedException.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExerciseDownloadFailedException.java
@@ -3,10 +3,15 @@
import fi.helsinki.cs.tmc.core.domain.Exercise;
import java.io.IOException;
+import java.net.URI;
public class ExerciseDownloadFailedException extends TmcCoreException {
public ExerciseDownloadFailedException(Exercise exercise, Exception ex) {
super("Downloading exercise " + exercise.getName() + " failed", ex);
}
+
+ public ExerciseDownloadFailedException(URI url, Exception ex){
+ super("Write exercise zip to disk from " + url.toString() + " failed", ex);
+ }
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExtractingExericeFailedException.java b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExtractingExericeFailedException.java
index 88dc5af5..98364294 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExtractingExericeFailedException.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/exceptions/ExtractingExericeFailedException.java
@@ -1,9 +1,16 @@
package fi.helsinki.cs.tmc.core.exceptions;
import fi.helsinki.cs.tmc.core.domain.Exercise;
+import java.net.URI;
public class ExtractingExericeFailedException extends TmcCoreException {
public ExtractingExericeFailedException(Exercise exercise, Exception ex) {
super("Extracting zip for " + exercise.getName() + " failed", ex);
}
+
+ // extract exercise when name is unknown,
+ public ExtractingExericeFailedException(URI url, Exception ex) {
+ super("Extracting zip from " + url.toString() + " failed", ex);
+ }
+
}
From 599a489205de3cf13efc66a4fe94a522407d15c7 Mon Sep 17 00:00:00 2001
From: Mavai
Date: Thu, 18 May 2017 15:05:47 +0300
Subject: [PATCH 47/86] tests??
---
.../commands/DownloadAdaptiveExercise.java | 11 ++
.../DownloadAdaptiveExerciseTest.java | 102 ++++++++++++++++++
2 files changed, 113 insertions(+)
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 7c29241f..472f17de 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -5,6 +5,8 @@
*/
package fi.helsinki.cs.tmc.core.commands;
+import com.google.common.annotations.VisibleForTesting;
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.Progress;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
@@ -12,6 +14,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.List;
+
/**
*
* @author sakuolin
@@ -24,6 +28,13 @@ public DownloadAdaptiveExercise(ProgressObserver observer) {
super(observer);
}
+ @VisibleForTesting
+ DownloadAdaptiveExercise(
+ ProgressObserver observer,
+ TmcServerCommunicationTaskFactory tmcServerCommunicationTaskFactory) {
+ super(observer, tmcServerCommunicationTaskFactory);
+ }
+
@Override
public Exercise call() throws Exception {
Progress progress = new Progress(3);
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
new file mode 100644
index 00000000..307cfdf0
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
@@ -0,0 +1,102 @@
+package fi.helsinki.cs.tmc.core.commands;
+
+import com.google.common.collect.Lists;
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Course;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
+import fi.helsinki.cs.tmc.core.utils.TestUtils;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
+
+/**
+ * Created by markovai on 18.5.2017.
+ */
+public class DownloadAdaptiveExerciseTest {
+
+ @Rule
+ public TemporaryFolder testFolder = new TemporaryFolder();
+
+ @Mock
+ ProgressObserver mockObserver;
+ @Spy
+ TmcSettings settings = new MockSettings();
+ @Mock
+ TmcServerCommunicationTaskFactory factory;
+ @Mock
+ Course mockCourse;
+ @Mock
+ Exercise mockExerciseOne;
+ @Mock
+ Callable mockGetAdaptiveExercise;
+
+ TaskExecutor langs;
+ Path arithFuncsTempDir;
+
+ private Command command;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ langs = spy(new TaskExecutorImpl());
+ TmcSettingsHolder.set(settings);
+ TmcLangsHolder.set(langs);
+ arithFuncsTempDir = testFolder.getRoot().toPath().resolve("arith_funcs");
+ command = new DownloadAdaptiveExercise(mockObserver, factory);
+
+ doCallRealMethod().when(langs).extractProject(any(Path.class), any(Path.class));
+ mockExerciseOne.setName("ex1");
+ mockExerciseOne.setCourseName("course1");
+ }
+
+ @Test
+ public void testSuccess() throws Exception {
+ verifyZeroInteractions(langs);
+
+ when(factory.getAdaptiveExercise()).thenReturn(mockGetAdaptiveExercise);
+ when(mockGetAdaptiveExercise.call()).thenReturn(mockExerciseOne);
+
+ when(mockExerciseOne.getExtractionTarget(any(Path.class))).thenReturn(arithFuncsTempDir);
+ when(settings.getTmcProjectDirectory()).thenReturn(testFolder.getRoot().toPath());
+
+ when(factory.getDownloadingExerciseZipTask(mockExerciseOne))
+ .thenReturn(
+ new Callable() {
+ @Override
+ public byte[] call() throws Exception {
+ return Files.readAllBytes(
+ TestUtils.getZip(this.getClass(), "arith_funcs.zip"));
+ }
+ });
+
+ Exercise exercise = command.call();
+
+ verify(factory).getDownloadingExerciseZipTask(mockExerciseOne);
+ //verifyNoMoreInteractions(factory);
+
+ assertTrue(Files.exists(arithFuncsTempDir));
+ // TODO: check for contents?
+ }
+
+}
From 5a57b183d2101739c7136e6a3094b27e1ddcd705 Mon Sep 17 00:00:00 2001
From: Qianyue Jin
Date: Thu, 18 May 2017 16:17:13 +0300
Subject: [PATCH 48/86] jtn
---
.../cs/tmc/core/commands/DownloadAdaptiveExercise.java | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 2866129d..d69b6549 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -52,10 +52,11 @@ public Exercise call() throws Exception {
//extractProject(zipb, exercise, progress);
- // säättää kurssi nimet puratun polun perusteella
Path exerciseDirectory = TmcSettingsHolder.get().getTmcProjectDirectory(); // menee exercise directory (mihin unzippattu)
Path unzippedFolderTemp = extractToTempFolder(zipb, exercise, progress);
+ // säättää kurssi nimet puratun polun perusteella
+ // unzip temp pois
cleanExtractedExerciseWithTempNames(exercise, unzippedFolderTemp, exerciseDirectory);
return exercise;
@@ -116,7 +117,7 @@ private void cleanExtractedExerciseWithTempNames(Exercise exercise, Path unzipFo
//File unzipTempFolder = unzipTempExnameNanotime.toFile();
//File superFolderWithNameOsaa = unzipTempFolder.listFiles()[0]; // menee ainoaan kansioon, esim. "osaa01"
File superFolderWithNameOsaa = unzipFolderTemp.toFile().listFiles()[0]; // menee ainoaan kansioon, esim. "osaa01"
- exercise.setCourseName(superFolderWithNameOsaa.getName()); // set course name "osaa01" //tai???
+ //exercise.setCourseName(superFolderWithNameOsaa.getName()); // set course name "osaa01" //tai???
File exerciseFolder = superFolderWithNameOsaa.listFiles()[0]; // menee ainoaan tehtävän kansioon, esim. "Osaa01_01.AdaLovelace"
exercise.setName(exerciseFolder.getName()); // exercise.setName(exer.getName().split(".")[1]); // set exercise name "AdaLovelace" //tai??
try {
From 137b0fade5e92f8447684e9c299f32466c767f66 Mon Sep 17 00:00:00 2001
From: fogre
Date: Thu, 18 May 2017 16:23:44 +0300
Subject: [PATCH 49/86] Json parser finished
---
.../java/fi/helsinki/cs/tmc/core/TmcCore.java | 5 --
.../commands/DownloadAdaptiveExercise.java | 4 +-
.../commands/DownloadExerciseByZipString.java | 39 ----------
.../TmcServerCommunicationTaskFactory.java | 9 ++-
.../serialization/AdaptiveExerciseParser.java | 15 +---
.../DownloadAdaptiveExerciseTest.java | 73 +++++++++++++++++++
.../AdaptiveExerciseParserTest.java | 2 +-
7 files changed, 86 insertions(+), 61 deletions(-)
delete mode 100644 src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java
create mode 100644 src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
index 35adada7..e3fa73a3 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/TmcCore.java
@@ -2,7 +2,6 @@
import fi.helsinki.cs.tmc.core.commands.AuthenticateUser;
import fi.helsinki.cs.tmc.core.commands.DownloadCompletedExercises;
-import fi.helsinki.cs.tmc.core.commands.DownloadExerciseByZipString;
import fi.helsinki.cs.tmc.core.commands.DownloadModelSolution;
import fi.helsinki.cs.tmc.core.commands.DownloadOrUpdateExercises;
import fi.helsinki.cs.tmc.core.commands.DownloadAdaptiveExercise;
@@ -182,10 +181,6 @@ public Callable downloadAdaptiveExercise(ProgressObserver observer) {
return new ExceptionTrackingCallable<>(new DownloadAdaptiveExercise(observer));
}
- public Callable downloadExerciseByZipString(ProgressObserver observer, String zip) {
- return new ExceptionTrackingCallable<>(new DownloadExerciseByZipString(observer,zip));
- }
-
/**
* NOT IMPLEMENTED!
*
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index ef73b807..9028d515 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -34,9 +34,9 @@ public Exercise call() throws Exception {
//ex.setName = "jotain"
//ex.setCourseName = "Jotain
//Tallennuspolku riippuu edellämainituista nimistä (TMCroot)
- byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
+ //byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
//checkInterrupt();
- extractProject(zipb, exercise, progress);
+ //extractProject(zipb, exercise, progress);
return exercise;
// byte[] zip = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java
deleted file mode 100644
index a1a6757d..00000000
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadExerciseByZipString.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package fi.helsinki.cs.tmc.core.commands;
-
-import fi.helsinki.cs.tmc.core.communication.http.HttpTasks;
-import fi.helsinki.cs.tmc.core.domain.Exercise;
-import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
-import java.net.URI;
-import java.util.concurrent.Callable;
-
-/**
- *
- * @author lai
- */
-public class DownloadExerciseByZipString extends Command{
- private String zip;
- public DownloadExerciseByZipString(ProgressObserver observer,String zip) {
- super(observer);
- this.zip=zip;
- }
-
- private String ToUrlByZipAndServerPath(String zip, String serverPath) {
- return serverPath + zip;
- }
-
- private Exercise ExtractExerciseByBytes(byte[] input){
- return null; //ExerciseDownloadingCommand.java
- }
-
- @Override
- public Exercise call() throws Exception {
- Callable download = new HttpTasks().getForBinary(URI.create(ToUrlByZipAndServerPath(zip, ""))); //mooc.helsin
- return ExtractExerciseByBytes(download.call());
- }
-
-}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index 242bae48..fc1f441b 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -28,6 +28,7 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
+import java.io.BufferedReader;
import org.apache.commons.io.IOUtils;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
@@ -35,8 +36,10 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
+import java.net.URL;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
@@ -142,15 +145,17 @@ private URI addApiCallQueryParameters(URI url) throws NotLoggedInException {
url = UriUtils.withQueryParam(url, "access_token", oauth.getToken());
return url;
}
-
+
public Callable getAdaptiveExercise()
throws OAuthSystemException, OAuthProblemException, NotLoggedInException {
return wrapWithNotLoggedInException(new Callable() {
@Override
public Exercise call() throws Exception {
try {
+ //Testit menee lävitse generaattorilla luodulla json tiedostolla.
+ //Seuraavaksi pitäisi ajaa skillifier lokaalisesti ja tarkistaa että metodi toimii next.jsonilla
Callable download = new HttpTasks().
- getForText(URI.create("localhost:3200/next.json"));
+ getForText(URI.create("http://www.json-generator.com/api/json/get/bRTQibwrNe?indent=2"));
String json = download.call();
return adaptiveExerciseParser.parseFromJson(json);
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 0ec41903..887bfb03 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -32,22 +32,13 @@ public Exercise parseFromJson(String json) {
if (json.trim().isEmpty()) {
throw new IllegalArgumentException("Empty input");
}
- try {;
+ try {
JSONObject obj = new JSONObject(json);
// Check status
- if (obj.getBoolean("available")) {
+ if (obj.getBoolean("available")) {
String zip_url = obj.getString("zip_url");
Exercise ex = new Exercise();
- ex.setDownloadUrl(URI.create(zip_url));
- // Käytä GSonia parseemaan kuin Course
- Gson gson =
- new GsonBuilder()
- .registerTypeAdapter(Date.class, new CustomDateDeserializer())
- .create();
- Exercise exercise = gson.fromJson(json, Exercise.class);
- // vanha return
- // tyhjä kommentti koska branch llälä
- // posdjgpofpgdfojofgjpofgjhfgojhgogf
+ ex.setZipUrl(URI.create("localhost:3200/"+zip_url));//localhost
return ex;
}
return null;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
new file mode 100644
index 00000000..fa6d361b
--- /dev/null
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
@@ -0,0 +1,73 @@
+package fi.helsinki.cs.tmc.core.commands;
+
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.concurrent.Callable;
+import static com.google.common.truth.Truth.assertThat;
+import fi.helsinki.cs.tmc.core.communication.TmcServerCommunicationTaskFactory;
+import fi.helsinki.cs.tmc.core.configuration.TmcSettings;
+import fi.helsinki.cs.tmc.core.domain.Exercise;
+import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
+import fi.helsinki.cs.tmc.core.holders.TmcLangsHolder;
+import fi.helsinki.cs.tmc.core.holders.TmcSettingsHolder;
+import fi.helsinki.cs.tmc.core.utils.MockSettings;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutor;
+import fi.helsinki.cs.tmc.langs.util.TaskExecutorImpl;
+import java.net.URI;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.verify;
+
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+/**
+ *
+ * @author fogh
+ */
+public class DownloadAdaptiveExerciseTest {
+
+ @Mock ProgressObserver mockObserver;
+ @Spy TmcSettings settings = new MockSettings();
+ @Mock TmcServerCommunicationTaskFactory factory;
+ TaskExecutor langs;
+ private Command command;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ langs = spy(new TaskExecutorImpl());
+ TmcSettingsHolder.set(settings);
+ TmcLangsHolder.set(langs);
+ command = new DownloadAdaptiveExercise(mockObserver);
+
+ }
+
+ @Test
+ public void checkExerciseZipUrl() throws Exception {
+ DownloadAdaptiveExercise e = new DownloadAdaptiveExercise(mockObserver);
+ Exercise exercise = e.call();
+ System.out.println(exercise.getZipUrl().toString());
+ }
+
+
+ // TODO add test methods here.
+ // The methods must be annotated with annotation @Test. For example:
+ //
+ // @Test
+ // public void hello() {}
+}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 9e5e28be..92e9450c 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -39,7 +39,7 @@ public void jsonIllegalException() {
public void exerciseHasZipUrl() {
Exercise exercise = adaptiveParser.parseFromJson("{ available: true, zip_url: not-empty }");
System.out.println(exercise.getZipUrl());
- assertEquals(exercise.getZipUrl().toString(), "not-empty");
+ assertEquals(exercise.getZipUrl().toString(), "localhost:3200/not-empty");
}
@Test
From 8164218275e7b2c6de07114fe351a2cbaa39c018 Mon Sep 17 00:00:00 2001
From: sakuolin
Date: Thu, 18 May 2017 20:53:14 +0300
Subject: [PATCH 50/86] Skillifier connecting fixed, downloading exercises
fixed
---
.../cs/tmc/core/commands/DownloadAdaptiveExercise.java | 8 ++++----
.../communication/TmcServerCommunicationTaskFactory.java | 4 ++--
.../tmc/core/communication/http/HttpRequestExecutor.java | 2 +-
.../serialization/AdaptiveExerciseParser.java | 2 +-
.../tmc/core/commands/DownloadAdaptiveExerciseTest.java | 1 -
5 files changed, 8 insertions(+), 9 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 9028d515..9e0f4c82 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -31,14 +31,14 @@ public Exercise call() throws Exception {
//informObserver
Exercise exercise =
tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
- //ex.setName = "jotain"
- //ex.setCourseName = "Jotain
+ exercise.setName("ass!");
+ exercise.setCourseName("porsk!");
//Tallennuspolku riippuu edellämainituista nimistä (TMCroot)
- //byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
+ byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
+ System.out.println(zipb.length);
//checkInterrupt();
//extractProject(zipb, exercise, progress);
return exercise;
- // byte[] zip = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
}
}
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
index fc1f441b..8a8ec320 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/TmcServerCommunicationTaskFactory.java
@@ -155,7 +155,7 @@ public Exercise call() throws Exception {
//Testit menee lävitse generaattorilla luodulla json tiedostolla.
//Seuraavaksi pitäisi ajaa skillifier lokaalisesti ja tarkistaa että metodi toimii next.jsonilla
Callable download = new HttpTasks().
- getForText(URI.create("http://www.json-generator.com/api/json/get/bRTQibwrNe?indent=2"));
+ getForText(URI.create("http://localhost:3200/next.json"));
String json = download.call();
return adaptiveExerciseParser.parseFromJson(json);
}
@@ -227,7 +227,7 @@ public Callable getDownloadingExerciseZipTask(Exercise exercise) {
URI zipUrl = exercise.getDownloadUrl();
return new HttpTasks().getForBinary(zipUrl);
}
-
+
public Callable getDownloadingExerciseSolutionZipTask(Exercise exercise) {
URI zipUrl = exercise.getSolutionDownloadUrl();
return new HttpTasks().getForBinary(zipUrl);
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutor.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutor.java
index c5287e09..f8877cc0 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutor.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/http/HttpRequestExecutor.java
@@ -47,7 +47,7 @@
private final Object shutdownLock = new Object();
private int timeout = DEFAULT_TIMEOUT;
- private HttpUriRequest request;
+ public HttpUriRequest request;
private UsernamePasswordCredentials credentials; // May be null
/*package*/ HttpRequestExecutor(URI url) {
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index 887bfb03..e59caf37 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -38,7 +38,7 @@ public Exercise parseFromJson(String json) {
if (obj.getBoolean("available")) {
String zip_url = obj.getString("zip_url");
Exercise ex = new Exercise();
- ex.setZipUrl(URI.create("localhost:3200/"+zip_url));//localhost
+ ex.setDownloadUrl(URI.create("http://localhost:3200"+zip_url));//localhost
return ex;
}
return null;
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
index fa6d361b..ffc0b729 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
@@ -61,7 +61,6 @@ public void setUp() {
public void checkExerciseZipUrl() throws Exception {
DownloadAdaptiveExercise e = new DownloadAdaptiveExercise(mockObserver);
Exercise exercise = e.call();
- System.out.println(exercise.getZipUrl().toString());
}
From 0eb5471c3bd02fbc43bb475bf324d12eb086af8c Mon Sep 17 00:00:00 2001
From: sakuolin
Date: Thu, 18 May 2017 21:40:33 +0300
Subject: [PATCH 51/86] Tests fixed, other small fixes
---
.../serialization/AdaptiveExerciseParser.java | 14 +++++---------
.../serialization/AdaptiveExerciseParserTest.java | 7 +++----
2 files changed, 8 insertions(+), 13 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
index e59caf37..fc5f367f 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/communication/serialization/AdaptiveExerciseParser.java
@@ -8,10 +8,6 @@
import fi.helsinki.cs.tmc.core.domain.Exercise;
import java.net.URI;
-import java.util.Date;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -34,12 +30,12 @@ public Exercise parseFromJson(String json) {
}
try {
JSONObject obj = new JSONObject(json);
- // Check status
if (obj.getBoolean("available")) {
- String zip_url = obj.getString("zip_url");
- Exercise ex = new Exercise();
- ex.setDownloadUrl(URI.create("http://localhost:3200"+zip_url));//localhost
- return ex;
+ Exercise exercise = new Exercise();
+ exercise.setDownloadUrl
+ // localhost, where is Skillifier hosted?
+ (URI.create("http://localhost:3200" + obj.getString("zip_url")));
+ return exercise;
}
return null;
} catch (RuntimeException ex) {
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
index 92e9450c..6973abc7 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/communication/http/serialization/AdaptiveExerciseParserTest.java
@@ -37,14 +37,13 @@ public void jsonIllegalException() {
@Test
public void exerciseHasZipUrl() {
- Exercise exercise = adaptiveParser.parseFromJson("{ available: true, zip_url: not-empty }");
- System.out.println(exercise.getZipUrl());
- assertEquals(exercise.getZipUrl().toString(), "localhost:3200/not-empty");
+ Exercise exercise = adaptiveParser.parseFromJson("{ available: true, zip_url: additionToString }");
+ assertEquals(exercise.getDownloadUrl().toString(), "http://localhost:3200additionToString");
}
@Test
public void exerciseNotAvailable() {
- Exercise exercise = adaptiveParser.parseFromJson("{ available: false, zip_url: not-empty }");
+ Exercise exercise = adaptiveParser.parseFromJson("{ available: false, zip_url: additionToString }");
assertEquals(exercise, null);
}
}
From 02c2b2997fc237b4dd5d93e452f624c773e7350a Mon Sep 17 00:00:00 2001
From: Mavai
Date: Thu, 18 May 2017 22:11:33 +0300
Subject: [PATCH 52/86] uncommented extracting, tests work
---
.../cs/tmc/core/commands/DownloadAdaptiveExercise.java | 2 +-
.../cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java | 4 +---
2 files changed, 2 insertions(+), 4 deletions(-)
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 965fb49f..3f97e8ab 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -48,7 +48,7 @@ public Exercise call() throws Exception {
byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call();
System.out.println(zipb.length);
//checkInterrupt();
- //extractProject(zipb, exercise, progress);
+ extractProject(zipb, exercise, progress);
return exercise;
}
}
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
index a0936048..be4c3adc 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
@@ -77,7 +77,6 @@ public void setUp() throws IOException {
langs = spy(new TaskExecutorImpl());
TmcSettingsHolder.set(settings);
TmcLangsHolder.set(langs);
- command = new DownloadAdaptiveExercise(mockObserver);
arithFuncsTempDir = testFolder.getRoot().toPath().resolve("arith_funcs");
command = new DownloadAdaptiveExercise(mockObserver, factory);
@@ -87,7 +86,6 @@ public void setUp() throws IOException {
}
- //pari kohtaa kommentoitu pois koska tehtavia ei pureta DownloadAdaptiveExercise: ssa (viela)
@Test
public void checkExerciseZipUrl() throws Exception {
setUpMocks();
@@ -106,7 +104,7 @@ public void testDownloadAndExtractSuccess() throws Exception {
verifyNoMoreInteractions(factory);
- //assertTrue(Files.exists(arithFuncsTempDir));
+ assertTrue(Files.exists(arithFuncsTempDir));
// TODO: check for contents?
}
From f39c4ee0ac520ff9f46f80489151fe71d6561351 Mon Sep 17 00:00:00 2001
From: Mavai
Date: Fri, 19 May 2017 10:21:50 +0300
Subject: [PATCH 53/86] more tests
---
.../commands/DownloadAdaptiveExercise.java | 8 +++++---
.../commands/DownloadAdaptiveExerciseTest.java | 14 ++++++++++++++
src/test/resources/__files/test.zip | Bin 0 -> 729120 bytes
3 files changed, 19 insertions(+), 3 deletions(-)
create mode 100644 src/test/resources/__files/test.zip
diff --git a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
index 3f97e8ab..78ce4aec 100644
--- a/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
+++ b/src/main/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExercise.java
@@ -17,11 +17,10 @@
import java.util.List;
/**
- *
* @author sakuolin
*/
public class DownloadAdaptiveExercise extends ExerciseDownloadingCommand {
-
+
private static final Logger logger = LoggerFactory.getLogger(SendFeedback.class);
public DownloadAdaptiveExercise(ProgressObserver observer) {
@@ -40,8 +39,11 @@ public Exercise call() throws Exception {
Progress progress = new Progress(3);
logger.info("Checking adaptive exercises availability");
//informObserver
- Exercise exercise =
+ Exercise exercise =
tmcServerCommunicationTaskFactory.getAdaptiveExercise().call();
+ if (exercise == null) {
+ return null;
+ }
exercise.setName("ass!");
exercise.setCourseName("porsk!");
//Tallennuspolku riippuu edellämainituista nimistä, polku: maindirectory/courseName/exerciseName
diff --git a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
index be4c3adc..5c914a41 100644
--- a/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
+++ b/src/test/java/fi/helsinki/cs/tmc/core/commands/DownloadAdaptiveExerciseTest.java
@@ -108,6 +108,20 @@ public void testDownloadAndExtractSuccess() throws Exception {
// TODO: check for contents?
}
+ @Test
+ public void testDownloadAndExtractFailure() throws Exception {
+ setUpMocks();
+ when(mockGetAdaptiveExercise.call()).thenReturn(null);
+
+ Exercise exercise = command.call();
+
+ verify(factory).getAdaptiveExercise();
+
+ verifyNoMoreInteractions(factory);
+
+ // TODO: check for contents?
+ }
+
private void setUpMocks() throws Exception {
verifyZeroInteractions(langs);
diff --git a/src/test/resources/__files/test.zip b/src/test/resources/__files/test.zip
new file mode 100644
index 0000000000000000000000000000000000000000..c23c97cab7521c1c0635f9cf388a3e2a499aa177
GIT binary patch
literal 729120
zcmagFV~j39vo-n*pTQp6wz0>yZF`Sx+qP}n)*jooXZG0m-gE9vZocH^oTO`Y|EjJZ
zD=RBq)e6#J;HUrq01CjXTO_shQlhg70st^W007hgT!5XEAtMum{C}Z7BNM%#iJ^?0
ztEsi2u_*(+vALUPSL0HYK8SoJrM$VH!muQ$tR`hFFEIij?;>cMGh|r5~^uUp{RxWE&lU
ze@UFsvNf0~>fRK5*&lBjZ&;9JIsl&HT#ytsHSFtB^#Kb;a2rfCuBAG&Ex}gbI
zAPDF+mGo3PpOiAYLv3jYoJr@K+aX;ewY=i>8L&
zG&ipqg4>*H2a_Gp2!u?T{!5ahp=%?Mj1&-KXye4xRfYPHAX
z2Lgrvi#{E0MYs(AArt3+g64mrkF$-jy`!C_sj)M?rIVfQ|HPlF6D0s>$x-yu(bYlX
zM79bUO^9VZrbc&rF=Yek?;d2z%H*`Xv`X;Q%HzsoP{99P6H|dT+8H7n~W#C45g8hpWaQcW{p2>ril%)aMe|7n)adfnfZ%tNM$@xd$s?h|K#@caCUu@
z&F<@O3Xwc3aEtT+t5y8#74a=g8vJL&32hehp)~|6YP|0i3R}6$Yl3+G8Fbqq-ioqn
z$KYGT;dCO=j;#PU%NZo{p-iisRdK87zpD-9!Ks%p5zj0PsqM|%%nJur*2R+pzViEcn(>q35)jdf+fE{dl6+Rj6Wu2&_`xx$tB
zP!;OtfsO|As{9ia8Kj^x#BAHfVzTkYK`d0xkb0#w_WHd>h0_rb{}^EK@4|1@m(R>l-Uw
z5>&ENZyQC%#AhT~hpGg$lg
z{ym;l**mdkqEC98@E}m;a)`$~ECcErm2^J2Laxq?h&waxKvP13o#ZNbk#;b6(c%Lv
zU`v?-SD{zf|4Rz8Vd3Oe2BdHL6m=^c|7Cc&!E3kB?ZrT&x+BHxTo%wLZwG%9zB6!0
z5Vr&JOgawo9A@nPGS@3aRvS0iV;fFV>(-W+sDZK&JYRhmJTIv{o^-P2ZiH=Dk6gwn
zn4{E^2#RM&f5V+Y=};rn-KuN|cKYU_0&i?lJO^My+n-k;L%Zm=Np?E!zmajsnERGc
zPA@8nKJ_K#S)kWmsYxS_w{*!CD@bW2)7sden7g2wZm!a^kq}ElcOfxI9FRK+%lcyB
z_~OfTIA4?qE!bz0a|$v`b&9kik;VEpEj;|f#4Z(@
zLNpC*i>T;s8a;`LS0UFpZ9q}-n9rMtm%pQx%THQx3!aA`|L
zY()f*_H8dcZ(52`OrOzaj7O3kubYr$>r_Zal$~QLYwVW)WGQNw3~KrJ>0+#iYrmaw
zLEhxbLWX*p=ecy+GOMY?z*@;lf;NAj4-$v!PnoL+<3Vd|@V{*HgEV{5i)F5WypVBA
zId44q$y^xO+&A`J(eGq`A^ew$!u&_a0sn0b{`>I%0>S^RqSh8h4F8jw|9|qVq+KMH
zp5f`VUjYCNi~<1c|9fIn6BjyXQzvIS7iSA=Cpt!YR(fW7OGC&1zR;@o|JQyLe}To@
z3^ejXwb^X8{@3b~|9|$)n?=5Dr`&Ir7vJ6P_J7l{<#;r!Gpb#M#4LWADJdPO#Q}o(
zfbZ+3t34v9+n-l~Z=1$K>cHkiN25oWpK(Z#`o}a`)4vNVR}9A=Z3UnF>n0G#q$46J
zs%Iu6xh7?0CdC%#=msSg6=r3pnaP-`887nL=EY`zEs8Bd2>aurmJ{d8KO}j$8jF(S
zOHz_`9m_2h?DG>6(^C|D;>(hAzrTq`u4tG2){uy#G7IAU3$@d%QGN_gAf5@uR%#Y&
z!18bXLivB>hk)OkQ?%zlyI2O_K?8$Jqw5PZ?|p~CKNNDtr$3=sZ$D}4BP*|c9{zhj
zKVYTgwe+Pk^tJS28yP?BIdk8zIhdQ6
zT-=*$IGO2OUv7s)9~hnQf5!t}U-)o87S#j&0f6#;5Ww0`2w$?yw6zScgo&&!?Un2|
z@-OEfzJ6phT@MpM)E)AToK3Ovzlp;4W1b4i19bvy(E_j$6Z@
zKbU@kKIo$mpI_xWamt>f+fk|{7Lql!5u4fYFWPbsY1_X(_|e^<8$
zJ0PYno;aIzMgDHL%^MU4PV4O(J&@|bZN=dGLSz{@a
zULZ0g-lpt=z{ZGK(ItZhbo8Z24M
zVc%WivQk}ePg7})g`fR>*-ZIwGFYqRYY}T)9i5bOjDvBW9@H6~UgU?7zRhU`)*J5?$acPK-x=ft~@`zc#0=wMZ#)o!iob
z!!lk9<|7b;H6z>tm>>hF5^c;8yH2nQvQ{w>MUyv^Iayp0E%OXtr@Z*Q
z^1ABU#5Z~viiD21(B2#*$|;
zt9t30_y{6b%t7_~=$20;_0F59qpAU|u7}2o+}H8i>EC`66ssHYMN`V
zU+g^J$)8=o0x>?*`A*mKM%~mh86%)YtYLtEzHa#>{=w~IUk2#g+5qlkVV8mdzRY_e
zoM41UCo2%(#NBj<_7&R3H0qc?rqKE))V+-2QDA_VAm0%>;Yz$hv8x2KQlahdm`mtE
zwQScP!#Z3k(0}myT?$=JFSV|yLUUQZ>({ei`{z3DAmW8o_YqA#-5S)JcYw95$VpGH
zy+f9vlQtF-OD_&)u