use of uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException in project isaac-api by isaacphysics.
the class AssignmentFacade method assignGameBoard.
/**
* Allows a user to assign a gameboard to group of users.
*
* @param request
* - so that we can identify the current user.
* @param assignmentDTOFromClient a partially completed DTO for the assignment.
* @return the assignment object.
*/
@POST
@Path("/assign/")
@Produces(MediaType.APPLICATION_JSON)
@GZIP
@ApiOperation(value = "Create a new assignment.")
public Response assignGameBoard(@Context final HttpServletRequest request, final AssignmentDTO assignmentDTOFromClient) {
if (assignmentDTOFromClient.getGameboardId() == null || assignmentDTOFromClient.getGroupId() == null) {
return new SegueErrorResponse(Status.BAD_REQUEST, "A required field was missing. Must provide group and gameboard ids").toResponse();
}
try {
RegisteredUserDTO currentlyLoggedInUser = userManager.getCurrentRegisteredUser(request);
UserGroupDTO assigneeGroup = groupManager.getGroupById(assignmentDTOFromClient.getGroupId());
boolean userIsTeacherOrAbove = isUserTeacherOrAbove(userManager, currentlyLoggedInUser);
boolean userIsStaff = isUserStaff(userManager, currentlyLoggedInUser);
boolean notesIsNullOrEmpty = assignmentDTOFromClient.getNotes() == null || (assignmentDTOFromClient.getNotes() != null && assignmentDTOFromClient.getNotes().isEmpty());
boolean notesIsTooLong = assignmentDTOFromClient.getNotes() != null && assignmentDTOFromClient.getNotes().length() > MAX_NOTE_CHAR_LENGTH;
if (!userIsTeacherOrAbove) {
return new SegueErrorResponse(Status.FORBIDDEN, "You need a teacher account to create groups and set assignments!").toResponse();
}
if (null == assigneeGroup) {
return new SegueErrorResponse(Status.BAD_REQUEST, "The group id specified does not exist.").toResponse();
}
if (!GroupManager.isOwnerOrAdditionalManager(assigneeGroup, currentlyLoggedInUser.getId()) && !isUserAnAdmin(userManager, currentlyLoggedInUser)) {
return new SegueErrorResponse(Status.FORBIDDEN, "You can only set assignments to groups you own or manage.").toResponse();
}
if (userIsStaff) {
if (notesIsTooLong) {
return new SegueErrorResponse(Status.BAD_REQUEST, "Your assignment notes exceed the maximum allowed length of " + MAX_NOTE_CHAR_LENGTH.toString() + " characters.").toResponse();
}
} else if (!notesIsNullOrEmpty) {
// user is not staff but it is a teacher, if we got here unscathed
return new SegueErrorResponse(Status.BAD_REQUEST, "You are not allowed to add assignment notes.").toResponse();
}
GameboardDTO gameboard = this.gameManager.getGameboard(assignmentDTOFromClient.getGameboardId());
if (null == gameboard) {
return new SegueErrorResponse(Status.BAD_REQUEST, "The gameboard id specified does not exist.").toResponse();
}
assignmentDTOFromClient.setOwnerUserId(currentlyLoggedInUser.getId());
assignmentDTOFromClient.setCreationDate(null);
assignmentDTOFromClient.setId(null);
// modifies assignment passed in to include an id.
AssignmentDTO assignmentWithID = this.assignmentManager.createAssignment(assignmentDTOFromClient);
LinkedHashMap<String, Object> eventDetails = new LinkedHashMap<>();
eventDetails.put(Constants.GAMEBOARD_ID_FKEY, assignmentWithID.getGameboardId());
eventDetails.put(GROUP_FK, assignmentWithID.getGroupId());
eventDetails.put(ASSIGNMENT_FK, assignmentWithID.getId());
eventDetails.put(ASSIGNMENT_DUEDATE_FK, assignmentWithID.getDueDate());
this.getLogManager().logEvent(currentlyLoggedInUser, request, IsaacServerLogType.SET_NEW_ASSIGNMENT, eventDetails);
this.userBadgeManager.updateBadge(currentlyLoggedInUser, UserBadgeManager.Badge.TEACHER_ASSIGNMENTS_SET, assignmentWithID.getId().toString());
tagsLoop: for (String tag : bookTags) {
for (GameboardItem item : gameboard.getContents()) {
if (item.getTags().contains(tag)) {
this.userBadgeManager.updateBadge(currentlyLoggedInUser, UserBadgeManager.Badge.TEACHER_BOOK_PAGES_SET, assignmentWithID.getId().toString());
break tagsLoop;
}
}
}
return Response.ok(assignmentDTOFromClient).build();
} catch (NoUserLoggedInException e) {
return SegueErrorResponse.getNotLoggedInResponse();
} catch (DuplicateAssignmentException e) {
return new SegueErrorResponse(Status.BAD_REQUEST, e.getMessage()).toResponse();
} catch (SegueDatabaseException e) {
log.error("Database error while trying to assign work", e);
return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Unknown database error.").toResponse();
}
}
use of uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException in project isaac-api by isaacphysics.
the class UsersFacade method createUserObjectAndLogIn.
/**
* Create a user object. This method allows new user objects to be created.
*
* @param request
* - so that we can identify the user
* @param response
* to tell the browser to store the session in our own segue cookie.
* @param userObjectFromClient
* - the new user object from the clients perspective.
* @param newPassword
* - the new password for the user.
* @param userPreferenceObject
* - the new preferences for this user
* @param rememberMe
* - Boolean to indicate whether or not this cookie expiry duration should be long or short
* @return the updated user object.
*/
private Response createUserObjectAndLogIn(final HttpServletRequest request, final HttpServletResponse response, final RegisteredUser userObjectFromClient, final String newPassword, final Map<String, Map<String, Boolean>> userPreferenceObject, final boolean rememberMe) throws InvalidKeySpecException, NoSuchAlgorithmException {
try {
RegisteredUserDTO savedUser = userManager.createUserObjectAndSession(request, response, userObjectFromClient, newPassword, rememberMe);
if (userPreferenceObject != null) {
List<UserPreference> userPreferences = userPreferenceObjectToList(userPreferenceObject, savedUser.getId());
userPreferenceManager.saveUserPreferences(userPreferences);
}
return Response.ok(savedUser).build();
} catch (InvalidPasswordException e) {
log.warn("Invalid password exception occurred during registration!");
return new SegueErrorResponse(Status.BAD_REQUEST, e.getMessage()).toResponse();
} catch (FailedToHashPasswordException e) {
log.error("Failed to hash password during user registration!");
return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Unable to set a password.").toResponse();
} catch (MissingRequiredFieldException e) {
log.warn("Missing field during update operation. ", e);
return new SegueErrorResponse(Status.BAD_REQUEST, "You are missing a required field. " + "Please make sure you have specified all mandatory fields in your response.").toResponse();
} catch (DuplicateAccountException e) {
log.warn(String.format("Duplicate account registration attempt for (%s)", userObjectFromClient.getEmail()));
return new SegueErrorResponse(Status.BAD_REQUEST, e.getMessage()).toResponse();
} catch (SegueDatabaseException e) {
String errorMsg = "Unable to set a password, due to an internal database error.";
log.error(errorMsg, e);
return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, errorMsg).toResponse();
} catch (EmailMustBeVerifiedException e) {
log.warn("Someone attempted to register with an Isaac email address: " + userObjectFromClient.getEmail());
return new SegueErrorResponse(Status.BAD_REQUEST, "You cannot register with an Isaac email address.").toResponse();
} catch (InvalidNameException e) {
log.warn("Invalid name provided during registration.");
return new SegueErrorResponse(Status.BAD_REQUEST, e.getMessage()).toResponse();
}
}
use of uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException in project isaac-api by isaacphysics.
the class PgEventBookings method delete.
@Override
public void delete(final String eventId, final Long userId) throws SegueDatabaseException {
String query = "DELETE FROM event_bookings WHERE event_id = ? AND user_id = ?";
try (Connection conn = ds.getDatabaseConnection();
PreparedStatement pst = conn.prepareStatement(query)) {
pst.setString(1, eventId);
pst.setLong(2, userId);
int executeUpdate = pst.executeUpdate();
if (executeUpdate == 0) {
throw new ResourceNotFoundException("Could not delete the requested booking.");
}
} catch (SQLException e) {
throw new SegueDatabaseException("Postgres exception while trying to delete event booking", e);
}
}
use of uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException in project isaac-api by isaacphysics.
the class PgEventBookings method updateStatus.
@Override
public void updateStatus(final String eventId, final Long userId, final Long reservingUserId, final BookingStatus status, final Map<String, String> additionalEventInformation) throws SegueDatabaseException {
PreparedStatement pst;
// FIXME: try-with-resources!
try (Connection conn = ds.getDatabaseConnection()) {
String reservingUserIdClause = "";
if (reservingUserId != null) {
reservingUserIdClause = ", reserved_by = ? ";
}
if (additionalEventInformation != null) {
pst = conn.prepareStatement("UPDATE event_bookings " + "SET status = ?, updated = ?, additional_booking_information = ?::text::jsonb " + reservingUserIdClause + "WHERE event_id = ? AND user_id = ?;");
pst.setString(1, status.name());
pst.setTimestamp(2, new java.sql.Timestamp(new Date().getTime()));
pst.setString(3, objectMapper.writeValueAsString(additionalEventInformation));
if (reservingUserId != null) {
pst.setLong(4, reservingUserId);
pst.setString(5, eventId);
pst.setLong(6, userId);
} else {
pst.setString(4, eventId);
pst.setLong(5, userId);
}
} else {
pst = conn.prepareStatement("UPDATE event_bookings " + "SET status = ?, updated = ? " + reservingUserIdClause + "WHERE event_id = ? AND user_id = ?;");
pst.setString(1, status.name());
pst.setTimestamp(2, new java.sql.Timestamp(new Date().getTime()));
if (reservingUserId != null) {
pst.setLong(3, reservingUserId);
pst.setString(4, eventId);
pst.setLong(5, userId);
} else {
pst.setString(3, eventId);
pst.setLong(4, userId);
}
}
int executeUpdate = pst.executeUpdate();
if (executeUpdate == 0) {
throw new ResourceNotFoundException("Could not delete the requested booking.");
}
} catch (SQLException e) {
throw new SegueDatabaseException("Postgres exception while trying to update event booking", e);
} catch (JsonProcessingException e) {
throw new SegueDatabaseException("Unable to convert json to string for persistence.", e);
}
}
use of uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException in project isaac-api by isaacphysics.
the class PgEventBookings method add.
/*
* (non-Javadoc)
*
* @see uk.ac.cam.cl.dtg.isaac.dos.eventbookings.EventBookings#add(uk.ac.cam.
* cl.dtg.isaac.dos.eventbookings.EventBooking)
*/
@Override
public EventBooking add(final String eventId, final Long userId, final Long reserveById, final BookingStatus status, Map<String, String> additionalEventInformation) throws SegueDatabaseException {
if (null == additionalEventInformation) {
additionalEventInformation = Maps.newHashMap();
}
String query = "INSERT INTO event_bookings (id, user_id, reserved_by, event_id, status, created, updated, additional_booking_information)" + " VALUES (DEFAULT, ?, ?, ?, ?, ?, ?, ?::text::jsonb)";
try (Connection conn = ds.getDatabaseConnection();
PreparedStatement pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
Date creationDate = new Date();
pst.setLong(1, userId);
if (reserveById == null) {
pst.setNull(2, Types.INTEGER);
} else {
pst.setLong(2, reserveById);
}
pst.setString(3, eventId);
pst.setString(4, status.name());
pst.setTimestamp(5, new java.sql.Timestamp(creationDate.getTime()));
pst.setTimestamp(6, new java.sql.Timestamp(creationDate.getTime()));
pst.setString(7, objectMapper.writeValueAsString(additionalEventInformation));
if (pst.executeUpdate() == 0) {
throw new SegueDatabaseException("Unable to save event booking.");
}
try (ResultSet generatedKeys = pst.getGeneratedKeys()) {
if (generatedKeys.next()) {
Long id = generatedKeys.getLong(1);
return new PgEventBooking(ds, id, userId, reserveById, eventId, status, creationDate, creationDate, additionalEventInformation);
} else {
throw new SQLException("Creating event booking failed, no ID obtained.");
}
}
} catch (SQLException e) {
throw new SegueDatabaseException("Postgres exception", e);
} catch (JsonProcessingException e) {
throw new SegueDatabaseException("Unable to convert json to string for persistence.", e);
}
}
Aggregations