Search in sources :

Example 1 with SegueDatabaseException

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();
    }
}
Also used : SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) DuplicateAssignmentException(uk.ac.cam.cl.dtg.isaac.api.managers.DuplicateAssignmentException) AssignmentDTO(uk.ac.cam.cl.dtg.isaac.dto.AssignmentDTO) LinkedHashMap(java.util.LinkedHashMap) NoUserLoggedInException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException) SegueErrorResponse(uk.ac.cam.cl.dtg.segue.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.segue.dto.users.RegisteredUserDTO) UserGroupDTO(uk.ac.cam.cl.dtg.segue.dto.UserGroupDTO) GameboardDTO(uk.ac.cam.cl.dtg.isaac.dto.GameboardDTO) GameboardItem(uk.ac.cam.cl.dtg.isaac.dto.GameboardItem) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) GZIP(org.jboss.resteasy.annotations.GZIP)

Example 2 with SegueDatabaseException

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();
    }
}
Also used : SegueErrorResponse(uk.ac.cam.cl.dtg.segue.dto.SegueErrorResponse) MissingRequiredFieldException(uk.ac.cam.cl.dtg.segue.auth.exceptions.MissingRequiredFieldException) InvalidNameException(uk.ac.cam.cl.dtg.segue.auth.exceptions.InvalidNameException) RegisteredUserDTO(uk.ac.cam.cl.dtg.segue.dto.users.RegisteredUserDTO) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) InvalidPasswordException(uk.ac.cam.cl.dtg.segue.auth.exceptions.InvalidPasswordException) UserPreference(uk.ac.cam.cl.dtg.segue.dos.UserPreference) EmailMustBeVerifiedException(uk.ac.cam.cl.dtg.segue.comm.EmailMustBeVerifiedException) DuplicateAccountException(uk.ac.cam.cl.dtg.segue.auth.exceptions.DuplicateAccountException) FailedToHashPasswordException(uk.ac.cam.cl.dtg.segue.auth.exceptions.FailedToHashPasswordException)

Example 3 with SegueDatabaseException

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);
    }
}
Also used : SQLException(java.sql.SQLException) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResourceNotFoundException(uk.ac.cam.cl.dtg.segue.dao.ResourceNotFoundException)

Example 4 with SegueDatabaseException

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);
    }
}
Also used : SQLException(java.sql.SQLException) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResourceNotFoundException(uk.ac.cam.cl.dtg.segue.dao.ResourceNotFoundException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Date(java.util.Date)

Example 5 with SegueDatabaseException

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);
    }
}
Also used : SQLException(java.sql.SQLException) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Date(java.util.Date)

Aggregations

SegueDatabaseException (uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException)292 PreparedStatement (java.sql.PreparedStatement)136 Connection (java.sql.Connection)135 SQLException (java.sql.SQLException)135 SegueErrorResponse (uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse)116 RegisteredUserDTO (uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO)115 Path (javax.ws.rs.Path)114 ApiOperation (io.swagger.annotations.ApiOperation)106 Produces (javax.ws.rs.Produces)104 NoUserLoggedInException (uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException)95 ResultSet (java.sql.ResultSet)76 GZIP (org.jboss.resteasy.annotations.GZIP)76 ContentManagerException (uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException)62 POST (javax.ws.rs.POST)58 Date (java.util.Date)54 GET (javax.ws.rs.GET)50 NoUserException (uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException)48 List (java.util.List)38 Map (java.util.Map)37 Consumes (javax.ws.rs.Consumes)37