Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract service logic from controllers #450

Merged
merged 19 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
411efcd
refactor: split AdminController into handler and service classes
ThanGerlek Oct 26, 2024
2bde169
refactor: move CasController::validateCasTicket into CasService class
ThanGerlek Oct 26, 2024
a32e932
refactor: split ConfigController into handler and service classes
ThanGerlek Oct 26, 2024
902f002
refactor: split SubmissionController into handler and service classes
ThanGerlek Oct 26, 2024
967c395
refactor: split UserController into handler and service classes
ThanGerlek Oct 26, 2024
9ff22c8
fix: replace Spark.halt() calls with Exceptions in SubmissionService
ThanGerlek Oct 26, 2024
c4ccb23
style: format files and remove unused imports
ThanGerlek Oct 26, 2024
8bfc2f0
style: format files, rmv imports, make methods private
ThanGerlek Oct 26, 2024
52509d5
refactor: move callbackGet() logic into service class
ThanGerlek Oct 26, 2024
6acc34e
fix: rmv duplicate logger calls
ThanGerlek Oct 26, 2024
d80a611
rmv unneeded TODO
ThanGerlek Oct 31, 2024
4b4cacd
removed unneeded exception constructors
ThanGerlek Oct 31, 2024
591c8f3
feat: make GradingObserverImpl class
ThanGerlek Nov 6, 2024
bc6fb5c
Merge branch 'main' into extract-service-logic-from-controllers
ThanGerlek Nov 7, 2024
1812c07
Merge branch 'main' into extract-service-logic-from-controllers
ThanGerlek Nov 7, 2024
6b6682c
Merge branch 'main' into extract-service-logic-from-controllers
ThanGerlek Nov 8, 2024
e3436b1
Remove unused constructor overloads
frozenfrank Nov 12, 2024
848be33
Move controller/*Exception.java classes into a sub-package...
frozenfrank Nov 12, 2024
f7e85b4
Merge branch 'main' into extract-service-logic-from-controllers
ThanGerlek Nov 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions src/main/java/edu/byu/cs/autograder/GradingObserverImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package edu.byu.cs.autograder;

import edu.byu.cs.controller.TrafficController;
import edu.byu.cs.dataAccess.DaoService;
import edu.byu.cs.dataAccess.DataAccessException;
import edu.byu.cs.model.Submission;
import edu.byu.cs.util.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class GradingObserverImpl implements GradingObserver {

private static final Logger LOGGER = LoggerFactory.getLogger(GradingObserverImpl.class);

private final String netId;

public GradingObserverImpl(String netId) {
this.netId = netId;
}

@Override
public void notifyStarted() {
try {
DaoService.getQueueDao().markStarted(netId);
} catch (DataAccessException e) {
LOGGER.error("Error marking queue item as started", e);
return;
}

notifySubscribers(Map.of("type", "started"));

try {
TrafficController.broadcastQueueStatus();
} catch (Exception e) {
LOGGER.error("Error broadcasting queue status", e);
}
}

@Override
public void update(String message) {
notifySubscribers(Map.of("type", "update", "message", message));
}

@Override
public void notifyError(String message) {
notifyError(message, Map.of());
}

@Override
public void notifyError(String message, Submission submission) {
notifyError(message, Map.of("results", Serializer.serialize(submission)));
}

private void notifyError(String message, Map<String, Object> contents) {
contents = new HashMap<>(contents);
contents.put("type", "error");
contents.put("message", message);
notifySubscribers(contents);
removeFromQueue();
}

@Override
public void notifyWarning(String message) {
notifySubscribers(Map.of("type", "warning", "message", message));
}

@Override
public void notifyDone(Submission submission) {
notifySubscribers(Map.of("type", "results", "results", Serializer.serialize(submission)));
removeFromQueue();
}

private void notifySubscribers(Map<String, Object> contents) {
try {
TrafficController.getInstance().notifySubscribers(netId, contents);
} catch (Exception e) {
LOGGER.error("Error updating subscribers", e);
}
}

private void removeFromQueue() {
TrafficController.sessions.remove(netId);
try {
DaoService.getQueueDao().remove(netId);
} catch (DataAccessException e) {
LOGGER.error("Error removing queue item", e);
}
}
}
96 changes: 19 additions & 77 deletions src/main/java/edu/byu/cs/controller/AdminController.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
package edu.byu.cs.controller;

import edu.byu.cs.analytics.CommitAnalyticsRouter;
import edu.byu.cs.canvas.CanvasException;
import edu.byu.cs.canvas.CanvasService;
import edu.byu.cs.canvas.model.CanvasSection;
import edu.byu.cs.dataAccess.DaoService;
import edu.byu.cs.dataAccess.DataAccessException;
import edu.byu.cs.dataAccess.UserDao;
import edu.byu.cs.honorChecker.HonorCheckerCompiler;
import edu.byu.cs.dataAccess.ItemNotFoundException;
import edu.byu.cs.model.User;
import edu.byu.cs.service.AdminService;
import edu.byu.cs.util.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Route;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Collection;

Expand All @@ -27,13 +22,10 @@ public class AdminController {
private static final Logger LOGGER = LoggerFactory.getLogger(AdminController.class);

public static final Route usersGet = (req, res) -> {
UserDao userDao = DaoService.getUserDao();

Collection<User> users;
try {
users = userDao.getUsers();
users = AdminService.getUsers();
} catch (DataAccessException e) {
LOGGER.error("Error getting users", e);
halt(500);
return null;
}
Expand All @@ -46,50 +38,15 @@ public class AdminController {
};

public static final Route testModeGet = (req, res) -> {
User latestTestStudent;
try {
latestTestStudent = CanvasService.getCanvasIntegration().getTestStudent();
} catch (CanvasException e) {
LOGGER.error("Error getting test student", e);
halt(500);
return null;
}

UserDao userDao = DaoService.getUserDao();
User user;
try {
user = userDao.getUser("test");
} catch (DataAccessException e) {
LOGGER.error("Error getting user", e);
halt(500);
return null;
}

try {

if (user == null) {
user = latestTestStudent;
userDao.insertUser(latestTestStudent);
} else {
userDao.setRepoUrl(user.netId(), latestTestStudent.repoUrl());
userDao.setCanvasUserId(user.netId(), latestTestStudent.canvasUserId());
}

} catch (DataAccessException e) {
LOGGER.error("Error updating user", e);
halt(500);
return null;
}

User testStudent;
try {
DaoService.getSubmissionDao().removeSubmissionsByNetId(user.netId(), 0);
} catch (DataAccessException e) {
LOGGER.error("Error removing submissions", e);
testStudent = AdminService.updateTestStudent();
} catch (CanvasException | DataAccessException e) {
halt(500);
return null;
}

res.cookie("/", "token", generateToken(user.netId()), 14400, false, false);
res.cookie("/", "token", generateToken(testStudent.netId()), 14400, false, false);

res.status(200);

Expand All @@ -101,12 +58,7 @@ public class AdminController {
String data;

try {
data = switch (option) {
case "update" -> CommitAnalyticsRouter.update();
case "cached" -> CommitAnalyticsRouter.cached();
case "when" -> CommitAnalyticsRouter.when();
default -> throw new IllegalStateException("Not found (invalid option: " + option + ")");
};
data = AdminService.getCommitAnalytics(option);
} catch (Exception e) {
LOGGER.error(e.getMessage());
if (e instanceof IllegalStateException) res.status(404);
Expand All @@ -121,38 +73,28 @@ public class AdminController {

public static final Route honorCheckerZipGet = (req, res) -> {
String sectionStr = req.params(":section");
String filePath;

res.header("Content-Type", "application/zip");
res.header("Content-Disposition", "attachment; filename=" + "downloaded_file.zip");
try (OutputStream os = res.raw().getOutputStream()) {
AdminService.streamHonorCheckerZip(sectionStr, os);

try {
filePath = HonorCheckerCompiler.compileSection(Integer.parseInt(sectionStr));
try (FileInputStream fis = new FileInputStream(filePath);
OutputStream os = res.raw().getOutputStream()) {

byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}

fis.close();
new File(filePath).delete();

res.status(200);
return res.raw();
}
} catch (Exception e) {
LOGGER.error("Error compiling honor checker", e);
res.status(500);
return e.getMessage();
}

res.status(200);

res.header("Content-Type", "application/zip");
res.header("Content-Disposition", "attachment; filename=" + "downloaded_file.zip");

return res.raw();

};

public static Route sectionsGet = (req, res) -> {
try {
CanvasSection[] sections = CanvasService.getCanvasIntegration().getAllSections();
CanvasSection[] sections = AdminService.getAllSections();
res.type("application/json");
res.status(200);
return Serializer.serialize(sections);
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/edu/byu/cs/controller/BadRequestException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package edu.byu.cs.controller;

public class BadRequestException extends Exception {
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}

public BadRequestException(String message) {
super(message);
}
}
Loading