diff --git a/maven-wrapper/pom.xml b/maven-wrapper/pom.xml index 2cf2a5b0..d93d411c 100644 --- a/maven-wrapper/pom.xml +++ b/maven-wrapper/pom.xml @@ -286,7 +286,7 @@ ${project.groupId} tmc-checkstyle-runner - 2.1.2-SNAPSHOT + 2.1.1 com.puppycrawl.tools diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/CheckForNewExercisesOrUpdates.java b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/CheckForNewExercisesOrUpdates.java index 38935720..b15c45f0 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/CheckForNewExercisesOrUpdates.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/CheckForNewExercisesOrUpdates.java @@ -141,7 +141,7 @@ public void bgTaskFailed(Throwable ex) { public Course call() throws Exception { logger.info("Downloading course to refresh cache"); currentCourseFuture = - tmcCore.getCourse(currentCourseBeforeUpdate.getDetailsUrlAsUri()); + tmcCore.getCourse(currentCourseBeforeUpdate.getDetailsUrl()); return currentCourseFuture.get(); } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/PastebinAction.java b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/PastebinAction.java index 12e9dacd..df197aef 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/PastebinAction.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/PastebinAction.java @@ -154,7 +154,8 @@ public void bgTaskCancelled() {} @Override public void bgTaskFailed(Throwable ex) { - dialogs.displayError("Failed to send exercise to pastebin", ex); + dialogs.displayError("Failed to send exercise to pastebin. \n" + + ServerErrorHelper.getServerExceptionMsg(ex)); } } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RequestReviewAction.java b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RequestReviewAction.java index 9a08fb9c..cfcd5ed4 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RequestReviewAction.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/RequestReviewAction.java @@ -172,7 +172,8 @@ public void bgTaskCancelled() {} @Override public void bgTaskFailed(Throwable ex) { dialogs.displayError( - "Failed to submit exercise for code review", ex); + "Failed to submit exercise for code review \n" + + ServerErrorHelper.getServerExceptionMsg(ex)); } }); } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/ReviewEventListener.java b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/ReviewEventListener.java index b93feada..ebdd2bf7 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/ReviewEventListener.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/ReviewEventListener.java @@ -24,6 +24,7 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; +import java.net.URI; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; @@ -175,7 +176,7 @@ private void sendLoggableEvent(Review review) { private static class ReviewOpened { public final int id; public final int submissionId; - public final String url; + public final URI url; public final boolean markedAsRead; public ReviewOpened(Review review) { diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/SendFeedbackAction.java b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/SendFeedbackAction.java index 1462eae1..12a03e25 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/actions/SendFeedbackAction.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/actions/SendFeedbackAction.java @@ -72,7 +72,7 @@ public void onSuccess(HttpResult v) { @Override public void onFailure(Throwable ex) { - String msg = "Failed to send feedback :-(\n" + ex.getMessage(); + String msg = "Failed to send feedback :-(\n" + ServerErrorHelper.getServerExceptionMsg(ex); String msgWithBacktrace = msg + "\n" + ExceptionUtils.backtraceToString(ex); log.log(Level.INFO, msgWithBacktrace); dialogs.displayError(msg); diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/exerciseSubmitter/ExerciseSubmitter.java b/tmc-plugin/src/fi/helsinki/cs/tmc/exerciseSubmitter/ExerciseSubmitter.java index 5f8040ee..bd14828f 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/exerciseSubmitter/ExerciseSubmitter.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/exerciseSubmitter/ExerciseSubmitter.java @@ -135,7 +135,7 @@ public void bgTaskFailed(Throwable ex) { log.log(Level.INFO, "Error waiting for results from server.", ex); String msg = ServerErrorHelper.getServerExceptionMsg(ex); if (!Strings.isNullOrEmpty(msg)) { - dialogDisplayer.displayError("Error trying to get test results.", ex); + dialogDisplayer.displayError("Error trying to get test results. \n" + msg); } dialog.close(); } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/layergen/UpdateCenterLayerGen.java b/tmc-plugin/src/fi/helsinki/cs/tmc/layergen/UpdateCenterLayerGen.java index 96dd7c9f..ad8dca97 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/layergen/UpdateCenterLayerGen.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/layergen/UpdateCenterLayerGen.java @@ -14,6 +14,7 @@ import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; +import java.nio.file.Paths; import java.util.Collection; /** @@ -44,7 +45,7 @@ public InputStream openInputStream() { public UpdateCenterLayerGen() { synchronized (UpdateCenterLayerGen.class) { if (!callbackRegistered) { - CallbackURLStreamHandler.registerCallback(CALLBACK_NAME, callback); + CallbackURLStreamHandler.registerCallback(Paths.get(CALLBACK_NAME), callback); } callbackRegistered = true; } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/CourseDb.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/CourseDb.java index b5fce710..a5995090 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/CourseDb.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/CourseDb.java @@ -11,6 +11,7 @@ import java.io.IOException; import java.io.Reader; import java.io.Writer; +import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -142,13 +143,13 @@ public List getCurrentCourseUnlockableExercises() { List result = new ArrayList(); Course course = getCurrentCourse(); if (course != null) { - List unlockables = course.getUnlockables(); + List unlockables = course.getUnlockables(); if (unlockables == null) { unlockables = Collections.emptyList(); } - for (String exerciseName : unlockables) { + for (URI exerciseName : unlockables) { for (Exercise ex : course.getExercises()) { - if (ex.getName().equals(exerciseName)) { + if (ex.getName().equals(exerciseName.toString())) { result.add(ex); } } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/NbTmcSettings.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/NbTmcSettings.java index 41be88f3..26ebd236 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/NbTmcSettings.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/NbTmcSettings.java @@ -7,6 +7,9 @@ import fi.helsinki.cs.tmc.tailoring.Tailoring; import fi.helsinki.cs.tmc.core.configuration.TmcSettings; import fi.helsinki.cs.tmc.core.domain.Course; + +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Locale; /** @@ -153,9 +156,10 @@ public boolean isSavingPassword() { @Override public String getTmcMainDirectory() { - String path = settings.get(PREF_PROJECT_ROOT_DIR, null); - if (path != null) { - return path; + String target = settings.get(PREF_PROJECT_ROOT_DIR, null); + //TODO: Change String to Path in TmcSettings + if (target != null) { + return target; } else { // Can sometimes take a while. That's why we don't pass it as a default above. return ProjectMediator.getDefaultProjectRootDir(); diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/ProjectMediator.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/ProjectMediator.java index 54a69877..9a2caa15 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/ProjectMediator.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/ProjectMediator.java @@ -2,8 +2,11 @@ import fi.helsinki.cs.tmc.core.domain.Exercise; import fi.helsinki.cs.tmc.utilities.ExceptionUtils; + import java.io.File; import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -113,13 +116,13 @@ public File getCourseRootDir(String courseName) { * The exercise must have a course name set. */ public File getProjectDirForExercise(Exercise ex) { - String path = + Path path = Paths.get( getProjectRootDir() + File.separator + ex.getCourseName() + File.separator - + ex.getName().replaceAll("-", "/"); - File file = new File(path); + + ex.getName().replaceAll("-", "/")); + File file = path.toFile(); return FileUtil.normalizeFile(file); } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/PushEventListener.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/PushEventListener.java index 08603c75..6a553bc0 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/PushEventListener.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/PushEventListener.java @@ -4,11 +4,14 @@ import fi.helsinki.cs.tmc.events.TmcEvent; import fi.helsinki.cs.tmc.events.TmcEventBus; import fi.helsinki.cs.tmc.events.TmcEventListener; + +import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; + import org.cometd.bayeux.Channel; import org.cometd.bayeux.Message; import org.cometd.bayeux.client.ClientSession; @@ -120,12 +123,12 @@ private synchronized void initClientIfPossible() { return; } - String cometUrl = course.getCometUrl(); + URI cometUrl = course.getCometUrl(); if (cometUrl == null) { return; } - ClientTransport transport = createWebSocketTransport(cometUrl); - client = new BayeuxClient(cometUrl, transport); + ClientTransport transport = createWebSocketTransport(cometUrl.toString()); + client = new BayeuxClient(cometUrl.toString(), transport); client.getChannel(Channel.META_HANDSHAKE).addListener(handshakeListener); client.getChannel(Channel.META_DISCONNECT).addListener(disconnectListener); diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/ServerAccess.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/ServerAccess.java index 932ab7db..420c436a 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/ServerAccess.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/ServerAccess.java @@ -134,8 +134,8 @@ public boolean cancel() { @Deprecated public CancellableCallable getFullCourseInfoTask(Course courseStub) { - String url = addApiCallQueryParameters(courseStub.getDetailsUrl()); - final CancellableCallable download = createHttpTasks().getForText(url); + URI url = URI.create(addApiCallQueryParameters(courseStub.getDetailsUrl().toString())); + final CancellableCallable download = createHttpTasks().getForText(url.toString()); return new CancellableCallable() { @Override public Course call() throws Exception { @@ -177,22 +177,22 @@ public boolean cancel() { } private String getUnlockUrl(Course course) { - return addApiCallQueryParameters(course.getUnlockUrl()); + return addApiCallQueryParameters(course.getUnlockUrl().toString()); } public CancellableCallable getDownloadingExerciseZipTask(Exercise exercise) { - String zipUrl = exercise.getDownloadUrl(); - return createHttpTasks().getForBinary(zipUrl); + URI zipUrl = exercise.getDownloadUrl(); + return createHttpTasks().getForBinary(zipUrl.toString()); } public CancellableCallable getDownloadingExerciseSolutionZipTask(Exercise exercise) { - String zipUrl = exercise.getSolutionDownloadUrl(); - return createHttpTasks().getForBinary(zipUrl); + URI zipUrl = exercise.getSolutionDownloadUrl(); + return createHttpTasks().getForBinary(zipUrl.toString()); } public CancellableCallable getSubmittingExerciseTask( final Exercise exercise, final byte[] sourceZip, Map extraParams) { - final String submitUrl = addApiCallQueryParameters(exercise.getReturnUrl()); + final URI submitUrl = URI.create(addApiCallQueryParameters(exercise.getReturnUrl().toString())); Map params = new LinkedHashMap(); params.put("client_time", "" + (System.currentTimeMillis() / 1000L)); @@ -202,7 +202,7 @@ public CancellableCallable getSubmittingExerciseTask( final CancellableCallable upload = createHttpTasks() .uploadFileForTextDownload( - submitUrl, params, "submission[file]", sourceZip); + submitUrl.toString(), params, "submission[file]", sourceZip); return new CancellableCallable() { @Override @@ -254,8 +254,8 @@ public CancellableCallable getSubmissionFetchTask(String submissionUrl) } public CancellableCallable> getDownloadingReviewListTask(Course course) { - String url = addApiCallQueryParameters(course.getReviewsUrl()); - final CancellableCallable download = createHttpTasks().getForText(url); + URI url = URI.create(addApiCallQueryParameters(course.getReviewsUrl().toString())); + final CancellableCallable download = createHttpTasks().getForText(url.toString()); return new CancellableCallable>() { @Override public List call() throws Exception { diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/SourceFileLookup.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/SourceFileLookup.java index c04a71c6..00d0712d 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/SourceFileLookup.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/SourceFileLookup.java @@ -2,6 +2,9 @@ import fi.helsinki.cs.tmc.core.domain.Exercise; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.netbeans.api.java.classpath.GlobalPathRegistry; import org.openide.filesystems.FileObject; @@ -24,13 +27,13 @@ private SourceFileLookup( public FileObject findSourceFileFor(Exercise exercise, String className) { String outerClassName = className.replaceAll("\\$.*$", ""); - String path = outerClassName.replace('.', '/') + ".java"; + Path path = Paths.get(outerClassName.replace('.', '/') + ".java"); TmcProjectInfo correctProject = projectMediator.tryGetProjectForExercise(exercise); for (FileObject sr : globalPathRegistry.getSourceRoots()) { TmcProjectInfo p = projectMediator.tryGetProjectOwningFile(sr); if (p != null && p.equals(correctProject)) { - FileObject result = sr.getFileObject(path); + FileObject result = sr.getFileObject(path.toString()); if (result != null) { return result; } @@ -38,6 +41,6 @@ public FileObject findSourceFileFor(Exercise exercise, String className) { } // Fall back to findResource picking a source root from any project. - return GlobalPathRegistry.getDefault().findResource(path); + return GlobalPathRegistry.getDefault().findResource(path.toString()); } } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/runners/TestRunHandler.java b/tmc-plugin/src/fi/helsinki/cs/tmc/runners/TestRunHandler.java index 8c69cbc3..4ff4073b 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/runners/TestRunHandler.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/runners/TestRunHandler.java @@ -3,6 +3,7 @@ import static fi.helsinki.cs.tmc.langs.domain.RunResult.Status.COMPILE_FAILED; import static java.util.logging.Level.INFO; +import fi.helsinki.cs.tmc.actions.ServerErrorHelper; import fi.helsinki.cs.tmc.core.domain.Exercise; import fi.helsinki.cs.tmc.data.ResultCollector; import fi.helsinki.cs.tmc.data.TestCaseResult; @@ -21,6 +22,7 @@ import fi.helsinki.cs.tmc.utilities.BgTaskListener; import fi.helsinki.cs.tmc.utilities.CancellableCallable; +import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; @@ -65,45 +67,47 @@ public void performAction(final ResultCollector resultCollector, Project... proj for (final Project project : projects) { final TmcProjectInfo projectInfo = projectMediator.wrapProject(project); eventBus.post(new InvokedEvent(projectInfo)); - BgTaskListener bgTaskListener = - new BgTaskListener() { - @Override - public void bgTaskReady(RunResult result) { - if (result.status == COMPILE_FAILED) { - dialogDisplayer.displayError("The code did not compile."); - return; - } - Exercise ex = - projectMediator.tryGetExerciseForProject(projectInfo, courseDb); - boolean canSubmit = ex.isReturnable(); - resultDisplayer.showLocalRunResult( - testResultsToTestCaseResults(result.testResults), - canSubmit, - new Runnable() { - @Override - public void run() { - exerciseSubmitter.performAction( - projectInfo.getProject()); - } - }, - resultCollector); - } - - @Override - public void bgTaskFailed(Throwable ex) { - log.log( - INFO, - "performAction of TestRunHandler failed with message: {0}, \ntrace: {1}", - new Object[] { - ex.getMessage(), Throwables.getStackTraceAsString(ex) - }); - dialogDisplayer.displayError( - "Failed to run the tests: " + ex.getMessage()); - } - - @Override - public void bgTaskCancelled() {} - }; + BgTaskListener bgTaskListener = new BgTaskListener() { + @Override + public void bgTaskReady(RunResult result) { + if (result.status == COMPILE_FAILED) { + dialogDisplayer.displayError("The code did not compile."); + return; + } + Exercise ex = projectMediator.tryGetExerciseForProject(projectInfo, courseDb); + boolean canSubmit = ex.isReturnable(); + resultDisplayer.showLocalRunResult( + testResultsToTestCaseResults(result.testResults), + canSubmit, + new Runnable() { + @Override + public void run() { + exerciseSubmitter.performAction( + projectInfo.getProject()); + } + }, + resultCollector); + } + + @Override + public void bgTaskFailed(Throwable ex) { + log.log( + INFO, + "performAction of TestRunHandler failed with message: {0}, \ntrace: {1}", + new Object[]{ + ex.getMessage(), Throwables.getStackTraceAsString(ex) + }); + String msg = ServerErrorHelper.getServerExceptionMsg(ex); + if (!Strings.isNullOrEmpty(msg)) { + dialogDisplayer.displayError( + "Failed to run the tests: \n" + msg); + } + } + + @Override + public void bgTaskCancelled() { + } + }; BgTask.start( "Running tests", new CancellableCallable() { @@ -112,9 +116,7 @@ public void bgTaskCancelled() {} @Override public RunResult call() throws Exception { - result = - TmcCoreSingleton.getInstance() - .test(projectInfo.getProjectDirAsPath()); + result = TmcCoreSingleton.getInstance().test(projectInfo.getProjectDirAsPath()); return result.get(); } @@ -131,8 +133,7 @@ private List testResultsToTestCaseResults( ImmutableList testresults) { List testCaseResults = new ArrayList(); for (TestResult result : testresults) { - TestCaseResult testCase = - new TestCaseResult(result.name, result.passed, result.errorMessage); + TestCaseResult testCase = new TestCaseResult(result.name, result.passed, result.errorMessage); testCaseResults.add(testCase); } return testCaseResults; diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java b/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java index 3501b9a3..ae1406b7 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/EventSendBuffer.java @@ -23,6 +23,7 @@ import org.openide.util.Exceptions; import java.io.IOException; +import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; @@ -248,7 +249,7 @@ private String pickDestinationUrl() { return null; } - List urls = course.getSpywareUrls(); + List urls = course.getSpywareUrls(); if (urls == null || urls.isEmpty()) { log.log( Level.INFO, @@ -256,7 +257,7 @@ private String pickDestinationUrl() { return null; } - String url = urls.get(random.nextInt(urls.size())); + String url = urls.get(random.nextInt(urls.size())).toString(); return url; } @@ -316,8 +317,8 @@ private void clearAfterSend(List success) { private void addCorrectSpywareUrl( final String url, Optional currentCourse) { - List spywareUrls = new ArrayList(); - String finalUrl = serverAccess.addApiCallQueryParameters(url); + List spywareUrls = new ArrayList(); + URI finalUrl = URI.create(serverAccess.addApiCallQueryParameters(url)); spywareUrls.add(finalUrl); currentCourse.get().setSpywareUrls(spywareUrls); } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/SourceSnapshotEventSource.java b/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/SourceSnapshotEventSource.java index 4395a50a..10383ac2 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/SourceSnapshotEventSource.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/SourceSnapshotEventSource.java @@ -23,6 +23,7 @@ import java.io.Closeable; import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; @@ -102,27 +103,27 @@ public void fileRenamed(FileRenameEvent fre) { public void fileAttributeChanged(FileAttributeEvent fae) {} private void reactToChange(final ChangeType changeType, final FileObject fileObject) { - String filePath = TmcFileUtils.tryGetPathRelativeToProject(fileObject); + Path filePath = TmcFileUtils.tryGetPathRelativeToProject(fileObject); if (filePath == null) { return; } String metadata = JsonMaker.create() .add("cause", changeType.name().toLowerCase()) - .add("file", filePath) + .add("file", filePath.toString()) .toString(); invokeSnapshotThreadViaEdt(fileObject, metadata); } private void reactToRename(final ChangeType changeType, final FileRenameEvent renameEvent) { - String filePath = TmcFileUtils.tryGetPathRelativeToProject(renameEvent.getFile()); + Path filePath = TmcFileUtils.tryGetPathRelativeToProject(renameEvent.getFile()); if (filePath == null) { return; } String metadata = JsonMaker.create() .add("cause", changeType.name().toLowerCase()) - .add("file", filePath) + .add("file", filePath.toString()) .add("previous_name", renameEvent.getName() + "." + renameEvent.getExt()) .toString(); invokeSnapshotThreadViaEdt(renameEvent.getFile(), metadata); diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/TextInsertEventSource.java b/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/TextInsertEventSource.java index 0e9ff652..45809ca5 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/TextInsertEventSource.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/spyware/eventsources/TextInsertEventSource.java @@ -25,6 +25,7 @@ import java.beans.PropertyChangeListener; import java.io.Closeable; import java.nio.charset.Charset; +import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -168,10 +169,10 @@ private void sendEvent(Exercise ex, String eventType, String text) { private String generatePatchDescription( FileObject fo, List patches, boolean patchContainsFullDocument) { - String filePath = TmcFileUtils.tryGetPathRelativeToProject(fo); + Path filePath = TmcFileUtils.tryGetPathRelativeToProject(fo); if (filePath != null) { return JsonMaker.create() - .add("file", filePath) + .add("file", filePath.toString()) .add("patches", PATCH_GENERATOR.patch_toText(patches)) .add("full_document", patchContainsFullDocument) .toString(); diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.form b/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.form index c0f7bfc6..5e3e663e 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.form +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.form @@ -7,6 +7,7 @@ + diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.java b/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.java index 79629d01..577127b3 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/ui/CodeReviewDialog.java @@ -59,7 +59,7 @@ private String getPointsAwardedText(Review review) { private void openInBrowser() { try { - HtmlBrowser.URLDisplayer.getDefault().showURLExternal(new URL(review.getUrl())); + HtmlBrowser.URLDisplayer.getDefault().showURLExternal(new URL(review.getUrl().toString())); } catch (MalformedURLException ex) { log.log(Level.WARNING, "Malformed URL: " + ex.getMessage(), ex); } diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/TmcFileUtils.java b/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/TmcFileUtils.java index fae2dd9b..9004ec73 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/TmcFileUtils.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/TmcFileUtils.java @@ -1,5 +1,7 @@ package fi.helsinki.cs.tmc.utilities; +import java.nio.file.Path; +import java.nio.file.Paths; import org.netbeans.api.project.FileOwnerQuery; import org.netbeans.api.project.Project; @@ -12,16 +14,16 @@ public class TmcFileUtils { * * Otherwise returns null. */ - public static String tryGetPathRelativeToProject(FileObject fileObject) { - String filePath = fileObject.getPath(); + public static Path tryGetPathRelativeToProject(FileObject fileObject) { + Path filePath = Paths.get(fileObject.getPath()); try { Project p = FileOwnerQuery.getOwner(fileObject); String projectDirectory = p.getProjectDirectory().getPath(); - if (filePath.contains(projectDirectory)) { + if (filePath.toString().contains(projectDirectory)) { filePath = - filePath.substring( - filePath.indexOf(projectDirectory) + projectDirectory.length()); + Paths.get(filePath.toString().substring( + filePath.toString().indexOf(projectDirectory) + projectDirectory.length())); } } catch (Exception e) { return null; diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/urlcallback/CallbackURLStreamHandler.java b/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/urlcallback/CallbackURLStreamHandler.java index 9fa0574e..0609530a 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/urlcallback/CallbackURLStreamHandler.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/urlcallback/CallbackURLStreamHandler.java @@ -9,6 +9,7 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; +import java.nio.file.Path; import java.util.Map; /** @@ -21,9 +22,9 @@ @URLStreamHandlerRegistration(protocol = "callback") public class CallbackURLStreamHandler extends URLStreamHandler { - private static final Map callbacks = Maps.newHashMap(); + private static final Map callbacks = Maps.newHashMap(); - public static void registerCallback(String path, URLCallback callback) { + public static void registerCallback(Path path, URLCallback callback) { if (callback == null) { callbacks.remove(path); } else { diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/zip/NbProjectUnzipper.java b/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/zip/NbProjectUnzipper.java index 6e554a65..2a97ea83 100644 --- a/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/zip/NbProjectUnzipper.java +++ b/tmc-plugin/src/fi/helsinki/cs/tmc/utilities/zip/NbProjectUnzipper.java @@ -12,6 +12,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -148,11 +150,11 @@ public Result unzipProject(byte[] data, File projectDir, boolean reallyWriteFile ZipEntry zent; while ((zent = zis.getNextEntry()) != null) { if (zent.getName().startsWith(projectDirInZip)) { - String restOfPath = zent.getName().substring(projectDirInZip.length()); - restOfPath = trimSlashes(restOfPath); + Path restOfPath = Paths.get(zent.getName().substring(projectDirInZip.length())); + restOfPath = trimSlashes(restOfPath.toString()); - String destFileRelativePath = trimSlashes(restOfPath.replace("/", File.separator)); - pathsInZip.add(destFileRelativePath); + Path destFileRelativePath = trimSlashes(restOfPath.toString().replace("/", File.separator)); + pathsInZip.add(destFileRelativePath.toString()); File destFile = new File(projectDir.toString() + File.separator + destFileRelativePath); @@ -167,17 +169,17 @@ public Result unzipProject(byte[] data, File projectDir, boolean reallyWriteFile if (destFile.exists()) { if (fileContentEquals(destFile, entryData)) { shouldWrite = false; - result.unchangedFiles.add(destFileRelativePath); - } else if (overwriting.mayOverwrite(destFileRelativePath)) { + result.unchangedFiles.add(destFileRelativePath.toString()); + } else if (overwriting.mayOverwrite(destFileRelativePath.toString())) { shouldWrite = true; - result.overwrittenFiles.add(destFileRelativePath); + result.overwrittenFiles.add(destFileRelativePath.toString()); } else { shouldWrite = false; - result.skippedFiles.add(destFileRelativePath); + result.skippedFiles.add(destFileRelativePath.toString()); } } else { shouldWrite = true; - result.newFiles.add(destFileRelativePath); + result.newFiles.add(destFileRelativePath.toString()); } if (shouldWrite && reallyWriteFiles) { FileUtils.forceMkdir(destFile.getParentFile()); @@ -204,40 +206,40 @@ private void deleteFilesNotInZip( boolean reallyWriteFiles) throws IOException { for (File file : curDir.listFiles()) { - String relPath = file.getPath().substring(projectDir.getPath().length()); - relPath = trimSlashes(relPath); + Path relPath = Paths.get(file.getPath().substring(projectDir.getPath().length())); + relPath = trimSlashes(relPath.toString()); if (file.isDirectory()) { deleteFilesNotInZip( projectDir, file, result, pathsInZip, overwriting, reallyWriteFiles); } - if (!pathsInZip.contains(relPath)) { - if (overwriting.mayDelete(relPath)) { + if (!pathsInZip.contains(relPath.toString())) { + if (overwriting.mayDelete(relPath.toString())) { if (file.isDirectory() && file.listFiles().length > 0) { // Won't delete directories if they still have contents - result.skippedDeletingFiles.add(relPath); + result.skippedDeletingFiles.add(relPath.toString()); } else { if (reallyWriteFiles) { file.delete(); } - result.deletedFiles.add(relPath); + result.deletedFiles.add(relPath.toString()); } } else { - result.skippedDeletingFiles.add(relPath); + result.skippedDeletingFiles.add(relPath.toString()); } } } } - private String trimSlashes(String s) { + private Path trimSlashes(String s) { while (s.startsWith("/") || s.startsWith(File.separator)) { s = s.substring(1); } while (s.endsWith("/") || s.startsWith(File.separator)) { s = s.substring(0, s.length() - 1); } - return s; + return Paths.get(s); } private String findProjectDirInZip(byte[] data) throws IOException { diff --git a/tmc-plugin/test/qa-functional/src/fi/helsinki/cs/tmc/functionaltests/utils/FakeTmcServer.java b/tmc-plugin/test/qa-functional/src/fi/helsinki/cs/tmc/functionaltests/utils/FakeTmcServer.java index 5c4540be..f14218eb 100644 --- a/tmc-plugin/test/qa-functional/src/fi/helsinki/cs/tmc/functionaltests/utils/FakeTmcServer.java +++ b/tmc-plugin/test/qa-functional/src/fi/helsinki/cs/tmc/functionaltests/utils/FakeTmcServer.java @@ -2,21 +2,25 @@ import fi.helsinki.cs.tmc.model.ServerAccess; import fi.helsinki.cs.tmc.testing.AdHocHttpServer; + import java.io.UnsupportedEncodingException; -import org.apache.http.entity.StringEntity; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; + import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.entity.StringEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; @@ -29,19 +33,19 @@ public class FakeTmcServer extends AdHocHttpServer { private String expectedPassword; private String coursesJson = "{}"; private Map courseDetails = new HashMap(); - + private HashMap zipFiles = new HashMap(); public FakeTmcServer() { setHandler(new Handler()); } - + public synchronized FakeTmcServer expectUser(String username, String password) { this.expectedUsername = username; this.expectedPassword = password; return this; } - + public synchronized void respondWithCourses(String coursesJson) { this.coursesJson = coursesJson; } @@ -49,11 +53,11 @@ public synchronized void respondWithCourses(String coursesJson) { public synchronized void respondWithCourseDetails(String id, String courseDetailsJson) { this.courseDetails.put(id, courseDetailsJson); } - + public synchronized void putZipFile(String path, byte[] data) { zipFiles.put(path, data); } - + public synchronized void clearResponses() { coursesJson = "{}"; courseDetails.clear(); @@ -63,6 +67,7 @@ public synchronized void clearResponses() { private static final Pattern courseRegex = Pattern.compile("/courses/(.+)\\.json"); private class Handler implements HttpRequestHandler { + @Override public void handle(HttpRequest req, HttpResponse resp, HttpContext hc) throws HttpException, IOException { synchronized (FakeTmcServer.this) { @@ -75,34 +80,32 @@ public void handle(HttpRequest req, HttpResponse resp, HttpContext hc) throws Ht Map params = parseQueryParameters(uri); - String path = uri.getPath(); - debug("Path: " + path); + Path path = Paths.get(uri.getPath()); + debug("Path: " + path.toString()); if (path.startsWith("/courses.json")) { authenticate(params); debug("Responding with course list: " + coursesJson); respondWithJson(resp, coursesJson); - } else if (courseRegex.matcher(path).matches()) { - Matcher m = courseRegex.matcher(path); + } else if (courseRegex.matcher(path.toString()).matches()) { + Matcher m = courseRegex.matcher(path.toString()); m.matches(); String id = m.group(1); -System.out.println(courseDetails); -System.out.println(id); String response = courseDetails.get(id); if (response != null) { authenticate(params); debug("Responding with course details: " + response); respondWithJson(resp, response); } else { - debug("Unknown course path: " + path); + debug("Unknown course path: " + path.toString()); resp.setStatusCode(404); resp.setEntity(new StringEntity("Not Found")); } - } else if (zipFiles.containsKey(path)) { - respondWithBinary(resp, zipFiles.get(path), "application/zip"); + } else if (zipFiles.containsKey(path.toString())) { + respondWithBinary(resp, zipFiles.get(path.toString()), "application/zip"); } else { - debug("Unknown path: " + path); + debug("Unknown path: " + path.toString()); resp.setStatusCode(404); resp.setEntity(new StringEntity("Not Found")); } @@ -137,7 +140,7 @@ private void respondWithJson(HttpResponse resp, String json) { } private void respondWithBinary(HttpResponse resp, byte[] data, String mimeType) { - ByteArrayEntity entity = new ByteArrayEntity(data); + ByteArrayEntity entity = new ByteArrayEntity(data); entity.setContentType(mimeType); resp.setEntity(entity); }