Skip to content

Commit

Permalink
Now uses custom exception class
Browse files Browse the repository at this point in the history
And a bunch of logic enhancements + code cleanup.
  • Loading branch information
lunarmint committed May 6, 2022
1 parent 87a2d12 commit e9b0272
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 137 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package edu.oswego.cs.daos;

import com.ibm.websphere.jaxrs20.multipart.IAttachment;
import edu.oswego.cs.util.CPRException;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.io.*;
import javax.ws.rs.core.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
Expand All @@ -18,6 +23,7 @@ public class FileDAO {

/**
* Takes form-data from a POST request for a csv file and reconstructs the content within the file
*
* @param attachments form-data
* @return FileDAO Instance
* @throws Exception File Corruption Exception
Expand All @@ -32,22 +38,22 @@ public static FileDAO FileFactory(List<IAttachment> attachments) throws Exceptio
if (fileName != null) {
InputStream stream = attachment.getDataHandler().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
String line;
try {
while ((line = reader.readLine()) != null)
if (!line.isEmpty()) csvLines.add(line);
if (csvLines.size() == 0) continue;
reader.close();

csvLines = csvLines.stream()
.map( str -> str.replaceAll("[!#$%^&*(){}|?<>:;]", "") )
.map(str -> str.replaceAll("[!#$%^&*(){}|?<>:;]", ""))
.collect(Collectors.toList());

return new FileDAO(fileName, csvLines);
} catch (IOException ignored) {}
} catch (IOException ignored) {
}
}
}
throw new Exception();
throw new CPRException(Response.Status.BAD_REQUEST, "File corrupted. Try again.");
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

import edu.oswego.cs.daos.CourseDAO;
import edu.oswego.cs.daos.FileDAO;
import edu.oswego.cs.daos.StudentDAO;
import edu.oswego.cs.util.CPRException;
import edu.oswego.cs.util.CourseUtil;

import org.bson.Document;
import org.bson.conversions.Bson;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
Expand All @@ -20,7 +17,6 @@
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -54,23 +50,28 @@ public CourseInterface() {
submissionCollection = assignmentDB.getCollection("submissions");
teamCollection = teamDB.getCollection("teams");
} catch (WebApplicationException e) {
throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Failed to retrieve collections.").build());
throw new CPRException(Response.Status.BAD_REQUEST, "Failed to retrieve collections.");
}
}

public void addCourse(SecurityContext securityContext, CourseDAO dao) {
String professorID = securityContext.getUserPrincipal().getName().split("@")[0];
dao.professorID = professorID;

Document courseDocument = courseCollection.find(and(eq("course_id", dao.courseID), eq("professor_id", professorID))).first();
if (courseDocument != null) throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity("Course already existed.").build());
Document courseDocument = courseCollection.find(and(
eq("course_id", dao.courseID),
eq("professor_id", professorID)
)).first();
if (courseDocument != null) throw new CPRException(Response.Status.CONFLICT, "Course already existed.");

Document professorDocument = professorCollection.find(eq("professor_id", professorID)).first();
if (professorDocument == null) throw new CPRException(Response.Status.NOT_FOUND, "This professor does not exist.");

Bson professorDocumentFilter = Filters.eq("professor_id", professorID);
Document professorDocument = professorCollection.find(professorDocumentFilter).first();
List<String> professorDocumentCourses = professorDocument.getList("courses", String.class);
if (professorDocumentCourses == null) throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity("Professor profile is not set up properly.").build());
if (professorDocumentCourses == null) throw new CPRException(Response.Status.CONFLICT, "Professor profile is not set up properly.");

professorDocumentCourses.add(dao.courseID);
professorCollection.updateOne(professorDocumentFilter, Updates.set("courses", professorDocumentCourses));
professorCollection.updateOne(eq("professor_id", professorID), Updates.set("courses", professorDocumentCourses));

Jsonb jsonb = JsonbBuilder.create();
Entity<String> courseDAOEntity = Entity.entity(jsonb.toJson(dao), MediaType.APPLICATION_JSON_TYPE);
Expand All @@ -84,32 +85,34 @@ public void addCourse(SecurityContext securityContext, CourseDAO dao) {
}
}

public String updateCourse(SecurityContext securityContext, CourseDAO dao) {
public void updateCourse(SecurityContext securityContext, CourseDAO dao) {
String professorID = securityContext.getUserPrincipal().getName().split("@")[0];

Document courseDocument = courseCollection.find(and(eq("course_id", dao.getCourseID()), eq("professor_id", professorID))).first();
if (courseDocument == null) throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("This course does not exist.").build());
if (courseDocument == null) throw new CPRException(Response.Status.NOT_FOUND, "This course does not exist.");

String originalCourseID = dao.courseID;
String newCourseID = dao.abbreviation + "-" + dao.courseSection + "-" + dao.crn + "-" + dao.semester + "-" + dao.year;
int originalTeamSize = courseDocument.getInteger("team_size");
int newTeamSize = dao.teamSize;
dao.courseID = newCourseID;
List<String> students = courseDocument.getList("students", String.class);
dao.students = students;
dao.students = courseDocument.getList("students", String.class);
dao.professorID = professorID;

if (!originalCourseID.equals(newCourseID)) {
Document duplicatedCourseDocument = courseCollection.find(and(eq("course_id", newCourseID), eq("professor_id", professorID))).first();
if (duplicatedCourseDocument != null) throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity("This course_id already exist.").build());
Document duplicatedCourseDocument = courseCollection.find(and(
eq("course_id", newCourseID),
eq("professor_id", professorID)
)).first();
if (duplicatedCourseDocument != null) throw new CPRException(Response.Status.CONFLICT, "This course_id already exist.");
}

if (originalTeamSize != newTeamSize) {
new CourseUtil().updateTeamSize(teamCollection, originalCourseID, originalTeamSize, newTeamSize);
new CourseUtil().updateTeamSize(teamCollection, originalCourseID, newTeamSize);
}

new CourseUtil().updateCoursesArrayInProfessorDb(securityContext, professorCollection, originalCourseID, newCourseID, "UPDATE");
new CourseUtil().updateCoursesArrayInStudenDb(studentCollection, originalCourseID, newCourseID, "UPDATE");
new CourseUtil().updateCoursesArrayInStudentDb(studentCollection, originalCourseID, newCourseID, "UPDATE");
new CourseUtil().updateCoursesKeyInDBs(assignmentCollection, originalCourseID, newCourseID, "UPDATE");
new CourseUtil().updateCoursesKeyInDBs(submissionCollection, originalCourseID, newCourseID, "UPDATE");
new CourseUtil().updateCoursesKeyInDBs(teamCollection, originalCourseID, newCourseID, "UPDATE");
Expand All @@ -118,8 +121,6 @@ public String updateCourse(SecurityContext securityContext, CourseDAO dao) {
Entity<String> courseDAOEntity = Entity.entity(jsonb.toJson(dao), MediaType.APPLICATION_JSON_TYPE);
Document course = Document.parse(courseDAOEntity.getEntity());
courseCollection.replaceOne(eq("course_id", originalCourseID), course);

return dao.courseID;
}

public void addStudent(SecurityContext securityContext, StudentDAO student, String courseID) {
Expand All @@ -129,20 +130,17 @@ public void addStudent(SecurityContext securityContext, StudentDAO student, Stri
String studentFirstName = student.fullName.split(", ")[1];

Document courseDocument = courseCollection.find(and(eq("course_id", courseID), eq("professor_id", professorID))).first();
if (courseDocument == null) throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("This course does not exist.").build());
if (courseDocument == null) throw new CPRException(Response.Status.NOT_FOUND, "This course does not exist.");

List<String> students = courseDocument.getList("students", String.class);
if (students.contains(studentId)) throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity("This student is already in the course.").build());
if (students.contains(studentId)) throw new CPRException(Response.Status.CONFLICT, "This student is already in the course.");
courseCollection.updateOne(eq("course_id", courseID), push("students", studentId));

Document studentDocument = studentCollection.find(eq("student_id", studentId)).first();
if (studentDocument != null) {
List<String> courseList = studentDocument.getList("courses", String.class);
for (String course : courseList) {
if (course.equals(courseID)) {
Response response = Response.status(Response.Status.CONFLICT).entity("This student is already in the course.").build();
throw new WebApplicationException(response);
}
if (course.equals(courseID)) throw new CPRException(Response.Status.CONFLICT, "This student is already in the course.");
}
studentCollection.updateOne(eq("student_id", studentId), push("courses", courseID));
} else {
Expand All @@ -160,9 +158,9 @@ public void addStudent(SecurityContext securityContext, StudentDAO student, Stri
public void removeCourse(SecurityContext securityContext, String courseID) {
String professorID = securityContext.getUserPrincipal().getName().split("@")[0];
Document courseDocument = courseCollection.find(and(eq("course_id", courseID), eq("professor_id", professorID))).first();
if (courseDocument == null) throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("This course does not exist.").build());
if (courseDocument == null) throw new CPRException(Response.Status.BAD_REQUEST, "This course does not exist.");
new CourseUtil().updateCoursesArrayInProfessorDb(securityContext, professorCollection, courseID, null, "DELETE");
new CourseUtil().updateCoursesArrayInStudenDb(studentCollection, courseID, null, "DELETE");
new CourseUtil().updateCoursesArrayInStudentDb(studentCollection, courseID, null, "DELETE");
new CourseUtil().updateCoursesKeyInDBs(assignmentCollection, courseID, null, "DELETE");
new CourseUtil().updateCoursesKeyInDBs(submissionCollection, courseID, null, "DELETE");
new CourseUtil().updateCoursesKeyInDBs(teamCollection, courseID, null, "DELETE");
Expand All @@ -171,10 +169,12 @@ public void removeCourse(SecurityContext securityContext, String courseID) {

public void removeStudent(SecurityContext securityContext, String studentID, String courseID) {
String professorID = securityContext.getUserPrincipal().getName().split("@")[0];

Document studentDocument = studentCollection.find(and(eq("student_id", studentID), eq("courses", courseID))).first();
if (studentDocument == null) throw new CPRException(Response.Status.NOT_FOUND, "This student does not exist.");

Document courseDocument = courseCollection.find(and(eq("course_id", courseID), eq("professor_id", professorID))).first();
if (courseDocument == null) throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("This course does not exist.").build());
if (studentDocument == null) throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("This student does not exist.").build());
if (courseDocument == null) throw new CPRException(Response.Status.NOT_FOUND, "This course does not exist.");

List<String> courses = studentDocument.getList("courses", String.class);
courses.remove(courseID);
Expand All @@ -191,8 +191,9 @@ public void addStudentsFromCSV(SecurityContext securityContext, FileDAO fileDAO)

String cid = fileDAO.getFilename();
cid = cid.substring(0, cid.length() - 4);

Document course = courseCollection.find(and(eq("course_id", cid), eq("professor_id", professorID))).first();
if (course == null) throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("This course does not exist.").build());
if (course == null) throw new CPRException(Response.Status.BAD_REQUEST, "This course does not exist.");

List<String> oldStudentList = course.getList("students", String.class);
String courseID = course.getString("course_id");
Expand All @@ -218,12 +219,4 @@ public void addStudentsFromCSV(SecurityContext securityContext, FileDAO fileDAO)
addStudent(securityContext, student, courseID);
}
}

public void collectionWipeOff() {
new CourseUtil().collectionWipeOff(studentCollection);
new CourseUtil().collectionWipeOff(courseCollection);
new CourseUtil().collectionWipeOff(assignmentCollection);
new CourseUtil().collectionWipeOff(submissionCollection);
new CourseUtil().collectionWipeOff(teamCollection);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import edu.oswego.cs.daos.FileDAO;
import edu.oswego.cs.daos.StudentDAO;
import edu.oswego.cs.database.CourseInterface;
import edu.oswego.cs.util.CPRException;

import javax.annotation.security.DenyAll;
import javax.annotation.security.RolesAllowed;
Expand Down Expand Up @@ -59,8 +60,7 @@ public Response addStudent(
@PathParam("courseID") String courseID,
@PathParam("studentInfo") String studentInfo) {
String[] parsedStudentInfo = studentInfo.split("-");
if (parsedStudentInfo.length < 3)
return Response.status(Response.Status.BAD_REQUEST).entity("Add student field was not filled out properly.").build();
if (parsedStudentInfo.length < 3) throw new CPRException(Response.Status.BAD_REQUEST, "Add student field was not filled out properly.");
StudentDAO studentDAO = new StudentDAO(parsedStudentInfo[0], parsedStudentInfo[1], parsedStudentInfo[2]);
new CourseInterface().addStudent(securityContext, studentDAO, courseID);
return Response.status(Response.Status.OK).entity("Student successfully added.").build();
Expand All @@ -75,7 +75,6 @@ public Response deleteStudent(
@Context SecurityContext securityContext,
@PathParam("courseID") String courseID,
@PathParam("studentID") String studentID) {

new CourseInterface().removeStudent(securityContext, studentID, courseID);
return Response.status(Response.Status.OK).entity("Student successfully removed.").build();
}
Expand All @@ -85,18 +84,10 @@ public Response deleteStudent(
@Produces(MediaType.APPLICATION_JSON)
@Path("courses/course/student/mass-add")
@RolesAllowed("professor")
public Response addStudentByCSVFile(@Context SecurityContext securityContext, IMultipartBody body) {
public Response addStudentByCSVFile(@Context SecurityContext securityContext, IMultipartBody body) throws Exception {
FileDAO fileDAO;
try {
fileDAO = FileDAO.FileFactory(body.getAllAttachments());
} catch (Exception e) {
return Response.status(Response.Status.BAD_REQUEST).entity("File corrupted. Try again.").build();
}
try {
new CourseInterface().addStudentsFromCSV(securityContext, fileDAO);
} catch (Exception e) {
return Response.status(Response.Status.BAD_REQUEST).entity("Failed to add students.").build();
}
fileDAO = FileDAO.FileFactory(body.getAllAttachments());
new CourseInterface().addStudentsFromCSV(securityContext, fileDAO);
return Response.status(Response.Status.OK).entity("Student(s) successfully added.").build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package edu.oswego.cs.util;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

public class CPRException extends WebApplicationException {
public CPRException(Response.Status responseStatus, String errorMessage) {
super(Response.status(responseStatus).entity(errorMessage).build());
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
package edu.oswego.cs.util;

import com.ibm.websphere.jaxrs20.multipart.IAttachment;
import edu.oswego.cs.daos.StudentDAO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -16,33 +12,11 @@ public static List<StudentDAO> parseStudentCSV(List<String> csvLines) {
List<StudentDAO> students = new ArrayList<>();
csvLines.forEach(line -> {
String[] delimitedLine = line.split(",");
if (delimitedLine.length < 10)
try {
throw new Exception("CSV file Is Not Formatted Correctly");
} catch (Exception ignored) {
}

String fullname = delimitedLine[1] + ", " + delimitedLine[2] + " " + delimitedLine[3];
if (delimitedLine.length < 10) throw new CPRException(Response.Status.CONFLICT, "CSV file is not formatted correctly.");
String fullName = delimitedLine[1] + ", " + delimitedLine[2] + " " + delimitedLine[3];
String email = delimitedLine[7];
students.add(new StudentDAO(fullname, email));
students.add(new StudentDAO(fullName, email));
});
return students;
}

public static String getModifiedFileName(IAttachment attachment) throws IOException {
String modifiedFileName = "";
InputStream inStream = attachment.getDataHandler().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
String line = "";
try {
while ((line = reader.readLine()) != null) {
modifiedFileName = line;
}
reader.close();
} catch (IOException ignored) {
}
return modifiedFileName;
}


}
Loading

0 comments on commit e9b0272

Please sign in to comment.