Example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl

List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl.

Prototype

@Deprecated
public String encodeRedirectUrl(String url);

Source Link

Usage

From source file:org.etudes.mneme.tool.GradeAssessmentView.java

/**
 * {@inheritDoc}//from   w  w  w.java 2 s  . c om
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2]sort for /grades, [3]aid |optional->| [4]our sort, [5]our page, [6]our highest/all-for-uid
    if ((params.length < 4) || params.length > 7)
        throw new IllegalArgumentException();

    // check for user permission to access the assessments for grading
    if (!this.submissionService.allowEvaluate(toolManager.getCurrentPlacement().getContext())) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // grades sort parameter
    String gradesSortCode = params[2];
    context.put("sort_grades", gradesSortCode);

    // get Assessment
    Assessment assessment = this.assessmentService.getAssessment(params[3]);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // check that the assessment is not a formal course evaluation
    if (assessment.getFormalCourseEval()) {
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // nor a survey
    if (assessment.getType() == AssessmentType.survey) {
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // validity check
    if (!assessment.getIsValid()) {
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    context.put("assessment", assessment);

    // sort parameter
    String sortCode = null;
    if (params.length > 4)
        sortCode = params[4];
    SubmissionService.FindAssessmentSubmissionsSort sort = getSort(assessment, context, sortCode);
    context.put("sort", sort.toString());

    // paging parameter
    String pagingParameter = null;
    if (params.length > 5)
        pagingParameter = params[5];
    if (pagingParameter == null) {
        pagingParameter = "1-" + Integer.toString(this.pageSizes.get(0));
    }

    // official or all
    // Boolean official = Boolean.TRUE;
    // String allUid = "official";
    // if ((params.length > 6) && (!params[6].equals("official")))
    // {
    // allUid = params[6];
    // }

    Boolean official = Boolean.FALSE;
    String allUid = null;
    if (params.length > 6) {
        if ("official".equals(params[6]))
            official = Boolean.TRUE;
    }

    // for anon, ignore official
    if (assessment.getAnonymous()) {
        official = Boolean.FALSE;
        allUid = null;
    }

    // view highest only decision (boolean string)
    Value highest = this.uiService.newValue();
    highest.setValue(Boolean.toString(official));
    context.put("highest", highest);

    // view option (official or all)
    if (official.booleanValue()) {
        context.put("view", "official");
    } else {
        context.put("view", "all");
    }

    // get the size
    Integer maxSubmissions = this.submissionService.countAssessmentSubmissions(assessment, official, allUid);

    // paging
    Paging paging = uiService.newPaging();
    paging.setMaxItems(maxSubmissions);
    paging.setCurrentAndSize(pagingParameter);
    context.put("paging", paging);

    // get all Assessment submissions
    List<Submission> submissions = this.submissionService.findAssessmentSubmissions(assessment, sort, official,
            allUid, paging.getSize() == 0 ? null : paging.getCurrent(),
            paging.getSize() == 0 ? null : paging.getSize(), null);
    context.put("submissions", submissions);

    // pages sizes
    if (this.pageSizes.size() > 1) {
        context.put("pageSizes", this.pageSizes);
    }
    new CKSetup().setCKCollectionAttrib(getDocsPath(), toolManager.getCurrentPlacement().getContext());

    uiService.render(ui, context);
}

From source file:org.etudes.mneme.tool.TocView.java

/**
 * {@inheritDoc}// ww  w.j a v a  2s . c  o m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need one parameter (sid) then return
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }

    String submissionId = params[2];
    String destination = null;
    if (params.length > 3) {
        destination = "/" + StringUtil.unsplit(params, 3, params.length - 3, "/");
    }

    // if not specified, go to the main list view
    else {
        destination = "/list";
    }
    context.put("return", destination);

    Submission submission = submissionService.getSubmission(submissionId);
    if (submission == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    if (!submissionService.allowCompleteSubmission(submission)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // validity check
    if (!submission.getAssessment().getIsValid()) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // linear is not allowed in here
    if (!submission.getAssessment().getRandomAccess()) {
        // redirect to error
        res.sendRedirect(
                res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.linear + "/" + submissionId)));
        return;
    }

    // collect information: the selected assessment (id the request)
    context.put("submission", submission);

    context.put("finalReview", Boolean.FALSE);

    // for the tool navigation
    if (this.assessmentService.allowManageAssessments(toolManager.getCurrentPlacement().getContext())) {
        context.put("maintainer", Boolean.TRUE);
    }

    // render
    uiService.render(ui, context);
}

From source file:org.etudes.mneme.tool.InstructionsEditView.java

/**
 * {@inheritDoc}// www .j  ava2  s  .  c  o  m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // aid, return
    if (params.length < 3) {
        throw new IllegalArgumentException();
    }

    String assessmentId = params[2];
    String destination = null;
    if (params.length > 3) {
        destination = "/" + StringUtil.unsplit(params, 3, params.length - 3, "/");
    }

    // if not specified, go to the main assessment_edit view
    else {
        destination = "/assessment_edit/" + assessmentId;
    }
    context.put("return", destination);

    final Assessment assessment = assessmentService.getAssessment(assessmentId);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // security check
    if (!assessmentService.allowEditAssessment(assessment)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // // clear the assessment of any empty parts (if not mint, which would end up causing it to become a stale mint and vanish!)
    // if (!assessment.getMint())
    // {
    // try
    // {
    // assessment.getParts().removeEmptyParts();
    // this.assessmentService.saveAssessment(assessment);
    // }
    // catch (AssessmentPermissionException e)
    // {
    // // redirect to error
    // res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
    // return;
    // }
    // catch (AssessmentPolicyException e)
    // {
    // // redirect to error
    // res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.policy)));
    // return;
    // }
    // }

    // collect information: the selected assessment
    context.put("assessment", assessment);

    context.put("parts", assessment.getParts().getParts());
    new CKSetup().setCKCollectionAttrib(getDocsPath(), toolManager.getCurrentPlacement().getContext());

    // render
    uiService.render(ui, context);
}

From source file:at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol.java

public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response,
        IRequest protocolRequest) throws Throwable {

    OAAuthParameter oa = AuthConfigurationProvider.getInstance()
            .getOnlineApplicationParameter(protocolRequest.getOAURL());
    if (!oa.getSAML1Parameter().isProvideAllErrors())
        return false;

    else {//from ww  w  . ja va 2  s. c o m
        SAML1AuthenticationServer saml1authentication = SAML1AuthenticationServer.getInstace();
        String samlArtifactBase64 = saml1authentication.BuildErrorAssertion(e, protocolRequest);

        String url = AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/RedirectServlet";
        url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL,
                URLEncoder.encode(protocolRequest.getOAURL(), "UTF-8"));
        url = addURLParameter(url, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
        url = response.encodeRedirectURL(url);

        response.setContentType("text/html");
        response.setStatus(302);
        response.addHeader("Location", url);
        Logger.debug("REDIRECT TO: " + url);

        return true;
    }
}

From source file:org.sakaiproject.login.tool.LoginTool.java

/**
 * Cleanup and redirect when we have a successful login / logout
 *
 * @param session//from w w  w  .  j av  a  2s  .  c  o m
 * @param tool
 * @param res
 * @throws IOException
 */
protected void complete(String returnUrl, Session session, Tool tool, HttpServletResponse res)
        throws IOException {
    // cleanup session
    if (session != null) {
        session.removeAttribute(Tool.HELPER_MESSAGE);
        session.removeAttribute(Tool.HELPER_DONE_URL);
        session.removeAttribute(ATTR_MSG);
        session.removeAttribute(ATTR_RETURN_URL);
        session.removeAttribute(ATTR_CONTAINER_CHECKED);
    }

    // if we end up with nowhere to go, go to the portal
    if (returnUrl == null) {
        returnUrl = ServerConfigurationService.getPortalUrl();
        M_log.info("complete: nowhere set to go, going to portal");
    }

    // redirect to the done URL
    res.sendRedirect(res.encodeRedirectURL(returnUrl));
}

From source file:org.etudes.mneme.tool.GradeAssessmentView.java

/**
 * {@inheritDoc}// ww w. jav a  2 s  . c  o m
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // [2]sort for /grades, [3]aid |optional->| [4]our sort, [5]our page, [6]our all/highest
    if ((params.length < 4) || params.length > 7)
        throw new IllegalArgumentException();

    // check for user permission to access the assessments for grading
    if (!this.submissionService.allowEvaluate(toolManager.getCurrentPlacement().getContext())) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // for Adjust every student's test submission by
    Value submissionAdjustValue = this.uiService.newValue();
    context.put("submissionAdjust", submissionAdjustValue);

    // for "Adjust every student's test submission by" comments
    Value submissionAdjustCommentsValue = this.uiService.newValue();
    context.put("submissionAdjustComments", submissionAdjustCommentsValue);

    // setup the model: the assessment
    // get Assessment - assessment id is in params at index 3
    Assessment assessment = this.assessmentService.getAssessment(params[3]);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // for the final scores
    PopulatingSet submissions = null;
    final SubmissionService submissionService = this.submissionService;
    submissions = uiService.newPopulatingSet(new Factory() {
        public Object get(String id) {
            Submission submission = submissionService.getSubmission(id);
            return submission;
        }
    }, new Id() {
        public String getId(Object o) {
            return ((Submission) o).getId();
        }
    });
    context.put("submissions", submissions);

    // view highest boolean holder
    Value highest = this.uiService.newValue();
    context.put("highest", highest);

    // read form
    String destination = this.uiService.decode(req, context);

    // save any final scores
    for (Iterator i = submissions.getSet().iterator(); i.hasNext();) {
        try {
            this.submissionService.evaluateSubmission((Submission) i.next());
        } catch (AssessmentPermissionException e) {
            M_log.warn("post: " + e);
        }
    }

    // apply the global adjustments
    String adjustScore = StringUtil.trimToNull(submissionAdjustValue.getValue());
    String adjustComments = StringUtil.trimToNull(submissionAdjustCommentsValue.getValue());
    if (adjustScore != null || adjustComments != null) {
        try {
            // parse the score
            Float score = null;
            if (adjustScore != null) {
                score = Float.parseFloat(adjustScore);
            }

            // apply (no release)
            this.submissionService.evaluateSubmissions(assessment, adjustComments, score);
        } catch (AssessmentPermissionException e) {
            M_log.warn("post: " + e);
        } catch (NumberFormatException e) {
        }
    }

    // release all evaluated
    if (destination.equals("RELEASEEVALUATED")) {
        try {
            this.submissionService.releaseSubmissions(assessment, Boolean.TRUE);
        } catch (AssessmentPermissionException e) {
            M_log.warn("post: " + e);
        }

        destination = context.getDestination();
    }

    else if (destination.equals("RELEASEALL")) {
        try {
            this.submissionService.releaseSubmissions(assessment, Boolean.FALSE);
        } catch (AssessmentPermissionException e) {
            M_log.warn("post: " + e);
        }

        destination = context.getDestination();
    }

    else if (destination.equals("SAVE")) {
        destination = context.getDestination();
    }

    else if (destination.equals("VIEW")) {
        // anon always gets view all
        if (assessment.getAnonymous()) {
            // just ignore this
            destination = context.getDestination();
        } else {
            // build the new dest parameters
            String[] dest = new String[7];
            for (int i = 0; i < params.length; i++) {
                dest[i] = params[i];
            }

            // fill in missing sort
            if (dest[4] == null) {
                dest[4] = "0A";
            }

            // fill in missing paging
            if (dest[5] == null) {
                dest[5] = "1-" + Integer.toString(this.pageSizes.get(0));
            }

            // set the official / all
            if ("true".equals(highest.getValue())) {
                dest[6] = "official";
            } else {
                dest[6] = "all";
            }

            destination = StringUtil.unsplit(dest, "/");
        }
    }

    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
}

From source file:com.wso2telco.gsma.authenticators.PinAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    log.info("Initiating authentication request");

    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());

    String pinNo = generatePassword();
    if (log.isDebugEnabled()) {
        log.debug("Pin no : " + pinNo);
        log.debug("Query parameters : " + queryParams);
    }/*from  ww  w  .  j av  a2  s.  c o m*/

    context.setProperty("pin", pinNo);
    try {

        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        }

        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&authenticators="
                + getName() + ":" + "LOCAL" + retryParam);

    } catch (IOException e) {
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:org.jamwiki.servlets.LoginServlet.java

/**
 * Redirect to the default Spring Security logout URL after adding a "successful logout"
 * URL to the request.  See the Spring Security LogoutFilter.determineTargetUrl() for
 * further details.//from   www . j a va2 s  . co m
 */
private void viewLogout(HttpServletRequest request, HttpServletResponse response, WikiPageInfo pageInfo)
        throws IOException {
    String virtualWikiName = pageInfo.getVirtualWikiName();
    String logoutSuccessUrl = WikiUtil.findDefaultVirtualWikiUrl(virtualWikiName);
    try {
        logoutSuccessUrl = URLEncoder.encode(logoutSuccessUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // this should never happen
        throw new IllegalStateException("Unsupporting encoding UTF-8");
    }
    StringBuilder springSecurityLogoutUrl = new StringBuilder();
    if (!StringUtils.equals(request.getContextPath(), "/")) {
        springSecurityLogoutUrl.append(request.getContextPath());
    }
    springSecurityLogoutUrl.append(JAMWikiAuthenticationConstants.SPRING_SECURITY_LOGOUT_URL);
    springSecurityLogoutUrl.append('?')
            .append(JAMWikiAuthenticationConstants.SPRING_SECURITY_LOGOUT_REDIRECT_QUERY_PARAM);
    springSecurityLogoutUrl.append('=').append(logoutSuccessUrl);
    response.sendRedirect(response.encodeRedirectURL(springSecurityLogoutUrl.toString()));
}

From source file:org.josso.gateway.signon.LoginAction.java

/**
 * Ask the user for login information./*from  w  w w.  j  av a2  s.  c o  m*/
 */
protected ActionForward askForLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    try {

        // Ask user for login information.
        SSOWebConfiguration cfg = Lookup.getInstance().lookupSSOWebConfiguration();

        String loginUrl = cfg.getCustomLoginURL();
        String backTo = getBackTo(request);

        if (loginUrl != null) {

            if (backTo != null) {
                loginUrl += (loginUrl.indexOf("?") >= 0 ? "&" : "?") + "josso_back_to=" + backTo;
            }

            // The authentication interface is not the default ...
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to custom login : " + loginUrl);

            response.sendRedirect(response.encodeRedirectURL(loginUrl));
            return null; // No action forward needed, we

        }

        return mapping.findForward("login-page");

    } catch (Exception e) {
        if (this.onFatalError(e, request, response))
            return null;

        return mapping.findForward("error");
    }
}

From source file:fll.web.admin.CreateUser.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    PreparedStatement addUser = null;
    PreparedStatement checkUser = null;
    ResultSet rs = null;//from w  ww  . jav  a 2  s.c o m
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {
        connection = datasource.getConnection();

        final String user = request.getParameter("user");
        final String pass = request.getParameter("pass");
        final String passCheck = request.getParameter("pass_check");
        if (null == pass || null == passCheck || null == user || user.isEmpty() || pass.isEmpty()
                || passCheck.isEmpty()) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>You must enter all information in the form.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        if (!pass.equals(passCheck)) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>Password and password check do not match.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        checkUser = connection.prepareStatement("SELECT fll_user FROM fll_authentication WHERE fll_user = ?");
        checkUser.setString(1, user);
        rs = checkUser.executeQuery();
        if (rs.next()) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>Username '" + user + "' already exists.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        final String hashedPass = DigestUtils.md5Hex(pass);
        addUser = connection
                .prepareStatement("INSERT INTO fll_authentication (fll_user, fll_pass) VALUES(?, ?)");
        addUser.setString(1, user);
        addUser.setString(2, hashedPass);
        addUser.executeUpdate();

        session.setAttribute(SessionAttributes.MESSAGE,
                "<p class='success' id='success-create-user'>Successfully created user '" + user + "'</p>");

        // do a login if not already logged in
        final Collection<String> loginKeys = CookieUtils.findLoginKey(request);
        final String authenticatedUser = Queries.checkValidLogin(connection, loginKeys);
        if (null == authenticatedUser) {
            DoLogin.doLogin(request, response, application, session);
        } else {
            response.sendRedirect(response.encodeRedirectURL("index.jsp"));
        }

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(checkUser);
        SQLFunctions.close(addUser);
        SQLFunctions.close(connection);
    }

}