Search in sources :

Example 1 with InvalidPostParametersException

use of teammates.common.exception.InvalidPostParametersException in project teammates by TEAMMATES.

the class ControllerServlet method doPost.

@Override
// used as fallback
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public final void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserType userType = new GateKeeper().getCurrentUser();
    String url = HttpRequestHelper.getRequestedUrl(req);
    Map<String, String[]> params = HttpRequestHelper.getParameterMap(req);
    try {
        /* We are using the Template Method Design Pattern here.
             * This method contains the high level logic of the request processing.
             * Concrete details of the processing steps are to be implemented by child
             * classes, based on request-specific needs.
             */
        long startTime = System.currentTimeMillis();
        log.info("Request received : [" + req.getMethod() + "] " + req.getRequestURL().toString() + ":" + HttpRequestHelper.printRequestParameters(req));
        log.info("User agent : " + req.getHeader("User-Agent"));
        Action c = new ActionFactory().getAction(req);
        if (c.isValidUser()) {
            ActionResult actionResult = c.executeAndPostProcess();
            actionResult.writeSessionTokenToCookieIfRequired(req, resp);
            actionResult.send(req, resp);
        } else {
            resp.sendRedirect(c.getAuthenticationRedirectUrl());
        }
        long timeTaken = System.currentTimeMillis() - startTime;
        // This is the log message that is used to generate the 'activity log' for the admin.
        log.info(c.getLogMessage() + "|||" + timeTaken);
    } catch (PageNotFoundException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ACTION_NOT_FOUND_PAGE, params, url));
    } catch (EntityNotFoundException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ENTITY_NOT_FOUND_PAGE, params, url));
    } catch (FeedbackSessionNotVisibleException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        req.getSession().setAttribute(Const.ParamsNames.FEEDBACK_SESSION_NOT_VISIBLE, e.getStartTimeString());
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.FEEDBACK_SESSION_NOT_VISIBLE, params, url));
    } catch (InvalidOriginException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.INVALID_ORIGIN, params, url));
    } catch (UnauthorizedAccessException e) {
        log.warning(new LogMessageGenerator().generateActionFailureLogMessage(url, params, e, userType));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.UNAUTHORIZED, params, url));
    } catch (DeadlineExceededException | DatastoreTimeoutException e) {
        /*This exception may not be caught because GAE kills
              the request soon after throwing it. In that case, the error
              message in the log will be emailed to the admin by a separate
              cron job.*/
        cleanUpStatusMessageInSession(req);
        log.severe("Deadline exceeded exception caught by ControllerServlet : " + TeammatesException.toStringWithStackTrace(e));
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.DEADLINE_EXCEEDED_ERROR_PAGE, params, url));
    } catch (InvalidPostParametersException e) {
        String requestUrl = req.getRequestURL().toString();
        log.info(e.getMessage());
        cleanUpStatusMessageInSession(req);
        List<StatusMessage> statusMessagesToUser = new ArrayList<>();
        statusMessagesToUser.add(new StatusMessage(Const.StatusMessages.NULL_POST_PARAMETER_MESSAGE, StatusMessageColor.WARNING));
        req.getSession().setAttribute(Const.ParamsNames.STATUS_MESSAGES_LIST, statusMessagesToUser);
        if (requestUrl.contains("/instructor")) {
            resp.sendRedirect(Const.ActionURIs.INSTRUCTOR_HOME_PAGE);
        } else if (requestUrl.contains("/student")) {
            resp.sendRedirect(Const.ActionURIs.STUDENT_HOME_PAGE);
        } else if (requestUrl.contains("/admin")) {
            resp.sendRedirect(Const.ActionURIs.ADMIN_HOME_PAGE);
        } else {
            cleanUpStatusMessageInSession(req);
            resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ERROR_PAGE, params, url));
        }
    } catch (Throwable t) {
        /* Log only stack trace to prevent delay in termination of request
             * which can result in GAE shutting down the instance.
             * Note that severe logs are sent by email automatically in the cron job auto/compileLogs.
             */
        log.severe("Unexpected exception caught by ControllerServlet : " + TeammatesException.toStringWithStackTrace(t));
        cleanUpStatusMessageInSession(req);
        resp.sendRedirect(appendParamsToErrorPageUrl(Const.ViewURIs.ERROR_PAGE, params, url));
    }
}
Also used : InvalidPostParametersException(teammates.common.exception.InvalidPostParametersException) LogMessageGenerator(teammates.common.util.LogMessageGenerator) DeadlineExceededException(com.google.apphosting.api.DeadlineExceededException) EntityNotFoundException(teammates.common.exception.EntityNotFoundException) DatastoreTimeoutException(com.google.appengine.api.datastore.DatastoreTimeoutException) StatusMessage(teammates.common.util.StatusMessage) PageNotFoundException(teammates.common.exception.PageNotFoundException) FeedbackSessionNotVisibleException(teammates.common.exception.FeedbackSessionNotVisibleException) InvalidOriginException(teammates.common.exception.InvalidOriginException) UnauthorizedAccessException(teammates.common.exception.UnauthorizedAccessException) GateKeeper(teammates.logic.api.GateKeeper) ArrayList(java.util.ArrayList) List(java.util.List) UserType(teammates.common.datatransfer.UserType)

Example 2 with InvalidPostParametersException

use of teammates.common.exception.InvalidPostParametersException in project teammates by TEAMMATES.

the class BaseActionTest method verifyAssumptionFailure.

/**
 * Verifies that the {@code parameters} violates an assumption of the
 * matching {@link Action}. e.g., missing a compulsory parameter.
 */
protected void verifyAssumptionFailure(String... parameters) {
    try {
        Action c = gaeSimulation.getActionObject(getActionUri(), parameters);
        c.executeAndPostProcess();
        signalFailureToDetectException();
    } catch (AssertionError | InvalidPostParametersException e) {
        ignoreExpectedException();
    }
}
Also used : Action(teammates.ui.controller.Action) InvalidPostParametersException(teammates.common.exception.InvalidPostParametersException)

Example 3 with InvalidPostParametersException

use of teammates.common.exception.InvalidPostParametersException in project teammates by TEAMMATES.

the class InstructorFeedbackAbstractAction method extractFeedbackSessionData.

/**
 * Creates a feedback session attributes object from the request parameters.
 * The created time is always set to now, and the opening email enabled flag is always set to true.
 * @param fsName the name of the feedback session (should be sanitized when creating a new session).
 * @param courseId the ID of the course the feedback session is in.
 * @param creatorEmail the email address of the feedback session's creator.
 * @return feedback session attributes object.
 * @throws InvalidPostParametersException if any of the request parameters are not in the expected format.
 */
protected FeedbackSessionAttributes extractFeedbackSessionData(String fsName, String courseId, String creatorEmail) {
    Assumption.assertNotNull(fsName);
    Assumption.assertNotNull(courseId);
    Assumption.assertNotNull(creatorEmail);
    FeedbackSessionAttributes attributes = FeedbackSessionAttributes.builder(fsName, courseId, creatorEmail).withCreatedTime(Instant.now()).build();
    String paramTimeZone = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_TIMEZONE);
    try {
        attributes.setTimeZone(ZoneId.of(paramTimeZone));
    } catch (DateTimeException e) {
        throw new InvalidPostParametersException("Failed to parse time zone parameter: " + paramTimeZone, e);
    }
    inputStartTimeLocal = TimeHelper.combineDateTime(getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_STARTDATE), getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_STARTTIME));
    inputEndTimeLocal = TimeHelper.combineDateTime(getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_ENDDATE), getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_ENDTIME));
    attributes.setStartTime(TimeHelper.convertLocalDateTimeToInstant(inputStartTimeLocal, attributes.getTimeZone()));
    attributes.setEndTime(TimeHelper.convertLocalDateTimeToInstant(inputEndTimeLocal, attributes.getTimeZone()));
    String paramGracePeriod = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_GRACEPERIOD);
    try {
        attributes.setGracePeriodMinutes(Integer.parseInt(paramGracePeriod));
    } catch (NumberFormatException nfe) {
        throw new InvalidPostParametersException("Failed to parse grace period parameter: " + paramGracePeriod, nfe);
    }
    attributes.setFeedbackSessionType(FeedbackSessionType.STANDARD);
    attributes.setInstructions(new Text(getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_INSTRUCTIONS)));
    String type = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_RESULTSVISIBLEBUTTON);
    switch(type) {
        case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_CUSTOM:
            inputPublishTimeLocal = TimeHelper.combineDateTime(getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_PUBLISHDATE), getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_PUBLISHTIME));
            attributes.setResultsVisibleFromTime(TimeHelper.convertLocalDateTimeToInstant(inputPublishTimeLocal, attributes.getTimeZone()));
            break;
        case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_ATVISIBLE:
            attributes.setResultsVisibleFromTime(Const.TIME_REPRESENTS_FOLLOW_VISIBLE);
            break;
        case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_LATER:
            attributes.setResultsVisibleFromTime(Const.TIME_REPRESENTS_LATER);
            break;
        default:
            throw new InvalidPostParametersException("Invalid resultsVisibleFrom setting: " + type);
    }
    // Handle session visible after results visible to avoid having a
    // results visible date when session is private (session not visible)
    type = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_SESSIONVISIBLEBUTTON);
    switch(type) {
        case Const.INSTRUCTOR_FEEDBACK_SESSION_VISIBLE_TIME_CUSTOM:
            inputVisibleTimeLocal = TimeHelper.combineDateTime(getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_VISIBLEDATE), getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_VISIBLETIME));
            attributes.setSessionVisibleFromTime(TimeHelper.convertLocalDateTimeToInstant(inputVisibleTimeLocal, attributes.getTimeZone()));
            break;
        case Const.INSTRUCTOR_FEEDBACK_SESSION_VISIBLE_TIME_ATOPEN:
            attributes.setSessionVisibleFromTime(Const.TIME_REPRESENTS_FOLLOW_OPENING);
            break;
        case Const.INSTRUCTOR_FEEDBACK_SESSION_VISIBLE_TIME_NEVER:
            attributes.setSessionVisibleFromTime(Const.TIME_REPRESENTS_NEVER);
            // Overwrite if private
            attributes.setResultsVisibleFromTime(Const.TIME_REPRESENTS_LATER);
            attributes.setFeedbackSessionType(FeedbackSessionType.PRIVATE);
            break;
        default:
            throw new InvalidPostParametersException("Invalid sessionVisibleFrom setting: " + type);
    }
    String[] sendReminderEmailsArray = getRequestParamValues(Const.ParamsNames.FEEDBACK_SESSION_SENDREMINDEREMAIL);
    List<String> sendReminderEmailsList = sendReminderEmailsArray == null ? new ArrayList<>() : Arrays.asList(sendReminderEmailsArray);
    attributes.setClosingEmailEnabled(sendReminderEmailsList.contains(EmailType.FEEDBACK_CLOSING.toString()));
    attributes.setPublishedEmailEnabled(sendReminderEmailsList.contains(EmailType.FEEDBACK_PUBLISHED.toString()));
    // A session opening reminder email is always sent as students
    // without accounts need to receive the email to be able to respond
    attributes.setOpeningEmailEnabled(true);
    return attributes;
}
Also used : FeedbackSessionAttributes(teammates.common.datatransfer.attributes.FeedbackSessionAttributes) InvalidPostParametersException(teammates.common.exception.InvalidPostParametersException) DateTimeException(java.time.DateTimeException) Text(com.google.appengine.api.datastore.Text)

Aggregations

InvalidPostParametersException (teammates.common.exception.InvalidPostParametersException)3 DatastoreTimeoutException (com.google.appengine.api.datastore.DatastoreTimeoutException)1 Text (com.google.appengine.api.datastore.Text)1 DeadlineExceededException (com.google.apphosting.api.DeadlineExceededException)1 DateTimeException (java.time.DateTimeException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 UserType (teammates.common.datatransfer.UserType)1 FeedbackSessionAttributes (teammates.common.datatransfer.attributes.FeedbackSessionAttributes)1 EntityNotFoundException (teammates.common.exception.EntityNotFoundException)1 FeedbackSessionNotVisibleException (teammates.common.exception.FeedbackSessionNotVisibleException)1 InvalidOriginException (teammates.common.exception.InvalidOriginException)1 PageNotFoundException (teammates.common.exception.PageNotFoundException)1 UnauthorizedAccessException (teammates.common.exception.UnauthorizedAccessException)1 LogMessageGenerator (teammates.common.util.LogMessageGenerator)1 StatusMessage (teammates.common.util.StatusMessage)1 GateKeeper (teammates.logic.api.GateKeeper)1 Action (teammates.ui.controller.Action)1