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:com.xpn.xwiki.user.impl.xwiki.MyFormAuthenticator.java

/**
 * {@inheritDoc}/*ww w.  j ava2  s .co  m*/
 * 
 * @see org.securityfilter.authenticator.Authenticator#showLogin(HttpServletRequest, HttpServletResponse)
 */
@Override
public void showLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String savedRequestId = request.getParameter(SavedRequestManager.getSavedRequestIdentifier());
    if (StringUtils.isEmpty(savedRequestId)) {
        // Save this request
        savedRequestId = SavedRequestManager.saveRequest(request);
    }
    String sridParameter = SavedRequestManager.getSavedRequestIdentifier() + "=" + savedRequestId;

    // Redirect to login page
    StringBuilder redirectBack = new StringBuilder(request.getRequestURI());
    redirectBack.append('?');
    String delimiter = "";
    if (StringUtils.isNotEmpty(request.getQueryString())) {
        redirectBack.append(request.getQueryString());
        delimiter = "&";
    }
    if (!request.getParameterMap().containsKey(SavedRequestManager.getSavedRequestIdentifier())) {
        redirectBack.append(delimiter);
        redirectBack.append(sridParameter);
    }
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + this.loginPage + "?"
            + sridParameter + "&xredirect=" + URLEncoder.encode(redirectBack.toString(), "UTF-8")));

    return;
}

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

/**
 * Respond to requests.//from   ww  w. j  a v  a2s  .c  o m
 * 
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException.
 * @throws IOException.
 */
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // get the session
    Session session = SessionManager.getCurrentSession();

    // check the remote user for authentication
    String remoteUser = req.getRemoteUser();
    try {
        Evidence e = new ExternalTrustedEvidence(remoteUser);
        Authentication a = AuthenticationManager.authenticate(e);

        // login the user
        if (UsageSessionService.login(a.getUid(), a.getEid(), req.getRemoteAddr(), req.getHeader("user-agent"),
                UsageSessionService.EVENT_LOGIN_CONTAINER)) {
            // get the return URL
            String url = getUrl(session, Tool.HELPER_DONE_URL);

            // cleanup session
            session.removeAttribute(Tool.HELPER_MESSAGE);
            session.removeAttribute(Tool.HELPER_DONE_URL);

            // Mark as successfully authenticated
            session.setAttribute(SkinnableLogin.ATTR_CONTAINER_SUCCESS, SkinnableLogin.ATTR_CONTAINER_SUCCESS);

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

            return;
        }
    } catch (AuthenticationException ex) {
        M_log.warn("Authentication Failed for: " + remoteUser + ". " + ex.getMessage());
    }

    // mark the session and redirect (for login failure or authentication exception)
    session.setAttribute(SkinnableLogin.ATTR_CONTAINER_CHECKED, SkinnableLogin.ATTR_CONTAINER_CHECKED);
    res.sendRedirect(res.encodeRedirectURL(getUrl(session, SkinnableLogin.ATTR_RETURN_URL)));
}

From source file:org.hdiv.webflow.mvc.servlet.FlowHandlerAdapterHDIV.java

protected void sendRedirect(String url, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    if (this.getAjaxHandler().isAjaxRequest(request, response)) {
        this.getAjaxHandler().sendAjaxRedirect(url, request, response, false);
    } else {/*from   ww  w.j a  v  a  2  s . com*/

        if (request.getSession(false) != null) {
            LinkUrlProcessor linkUrlProcessor = HDIVUtil
                    .getLinkUrlProcessor(request.getSession().getServletContext());
            url = linkUrlProcessor.processUrl(request, url);
        }
        /*
        if (request.getSession(false) != null) {         
           HDIVConfig hdivConfig = (HDIVConfig) HDIVUtil.getApplication().getBean("config");   
           if (HDIVRequestUtils.hasActionOrServletExtension(url, hdivConfig.getProtectedURLPatterns())) {
              url = HDIVRequestUtils.addHDIVParameterIfNecessary(request, url, hdivConfig.isValidationInUrlsWithoutParamsActivated());
           }
        }
        */
        logger.debug("[sendRedirect] Redirecting to url: " + url);

        if (this.getRedirectHttp10Compatible()) {
            // Always send status code 302.
            response.sendRedirect(response.encodeRedirectURL(url));
        } else {
            // Correct HTTP status code is 303, in particular for POST requests.
            response.setStatus(303);
            response.setHeader("Location", response.encodeRedirectURL(url));
        }
    }
}

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

/**
 * Cleanup and redirect when we have a successful login / logout
 *
 * @param session/*from  ww w  . j  a v 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();
        log.info("complete: nowhere set to go, going to portal");
    }

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

From source file:org.apache.struts2.dispatcher.ServletRedirectResult.java

/**
 * Redirects to the location specified by calling {@link HttpServletResponse#sendRedirect(String)}.
 *
 * @param finalLocation the location to redirect to.
 * @param invocation    an encapsulation of the action execution state.
 * @throws Exception if an error occurs when redirecting.
 *///  w  ww . j a v  a2  s . c  om
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    ActionContext ctx = invocation.getInvocationContext();
    HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);

    if (isPathUrl(finalLocation)) {
        if (!finalLocation.startsWith("/")) {
            ActionMapping mapping = actionMapper.getMapping(request,
                    Dispatcher.getInstance().getConfigurationManager());
            String namespace = null;
            if (mapping != null) {
                namespace = mapping.getNamespace();
            }

            if ((namespace != null) && (namespace.length() > 0) && (!"/".equals(namespace))) {
                finalLocation = namespace + "/" + finalLocation;
            } else {
                finalLocation = "/" + finalLocation;
            }
        }

        // if the URL's are relative to the servlet context, append the servlet context path
        if (prependServletContext && (request.getContextPath() != null)
                && (request.getContextPath().length() > 0)) {
            finalLocation = request.getContextPath() + finalLocation;
        }

        finalLocation = response.encodeRedirectURL(finalLocation);
    }

    if (log.isDebugEnabled()) {
        log.debug("Redirecting to finalLocation " + finalLocation);
    }

    response.sendRedirect(finalLocation);
}

From source file:com.jaspersoft.jasperserver.war.util.RequestParameterAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (requiresAuthentication(httpRequest)) {
        String username = EncryptionRequestUtils.getValue(httpRequest,
                AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
        String password = EncryptionRequestUtils.getValue(httpRequest,
                AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY);
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                password);/*www.j  ava  2  s .  c  o  m*/
        authRequest.setDetails(new WebAuthenticationDetails(httpRequest));

        Authentication authResult;
        try {
            authResult = authenticationManager.authenticate(authRequest);
        } catch (AuthenticationException e) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " failed to authenticate: " + e.toString());
            }

            SecurityContextHolder.getContext().setAuthentication(null);
            httpResponse.sendRedirect(httpResponse.encodeRedirectURL(getFullFailureUrl(httpRequest)));
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("User " + username + " authenticated: " + authResult);
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);
        onSuccessfulAuthentication(httpRequest, httpResponse, authResult);
    }

    chain.doFilter(request, response);
}

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

/**
 * {@inheritDoc}// ww w.j  a  va2  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 view
    else {
        destination = "/assessments";
    }
    context.put("return", destination);

    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;
    }

    // check for formal course evaluation permission
    if (assessmentService.allowSetFormalCourseEvaluation(assessment.getContext())) {
        context.put("allowEval", Boolean.TRUE);
    }

    // // 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;
    // }
    // }

    try {
        Site site = this.siteService.getSite(toolManager.getCurrentPlacement().getContext());
        ToolConfiguration config = site.getToolForCommonId("sakai.mneme");
        if (config != null)
            toolId = config.getId();
        context.put("toolId", toolId);
    } catch (IdUnusedException e) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

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

    context.put("details", assessment.getParts().getPhantomDetails());

    // value holders for the selection check boxes
    Values values = this.uiService.newValues();
    context.put("ids", values);

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

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

/**
 * {@inheritDoc}/*from w  w w.j  a v  a 2 s  . co  m*/
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    if (!context.getPostExpected()) {
        throw new IllegalArgumentException();
    }

    // no parameters expected
    if (params.length != 2) {
        throw new IllegalArgumentException();
    }

    // read form
    Value installValue = this.uiService.newValue();
    context.put("installValue", installValue);
    Value installBulkValue = this.uiService.newValue();
    context.put("installBulkValue", installBulkValue);
    Value poolRmDupsContext = this.uiService.newValue();
    context.put("poolRmDupsContext", poolRmDupsContext);
    Value poolRmContext = this.uiService.newValue();
    context.put("poolRmContext", poolRmContext);

    String destination = uiService.decode(req, context);

    if ("INSTALL".equals(destination)) {
        if (installValue.getValue() != null) {
            // add the specs
            destination = "/install/" + installValue.getValue();
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
            return;
        }
    }

    else if ("INSTALL_BULK".equals(destination)) {
        if (installBulkValue.getValue() != null) {
            // add the specs
            destination = "/install_bulk/" + installBulkValue.getValue();
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
            return;
        }
    }

    else if ("QUESTION_CLEANUP".equals(destination)) {
        destination = "/question_cleanup";
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
        return;
    }

    else if ("INSTALL_TEMPLATES".equals(destination)) {
        destination = "/install_templates";
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
        return;
    }

    else if ("POOL_RM_DUPS".equals(destination)) {
        if (poolRmDupsContext.getValue() != null) {
            destination = "/pool_rm_dups/" + poolRmDupsContext.getValue();
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
            return;
        }
    }

    else if ("POOL_RM".equals(destination)) {
        if (poolRmContext.getValue() != null) {
            destination = "/pool_rm/" + poolRmContext.getValue();
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
            return;
        }
    }

    destination = "/home";
    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
}

From source file:org.muse.mneme.tool.EnterView.java

/**
 * {@inheritDoc}//from  w ww.  j  a  va  2  s  . co  m
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need a single parameter (aid)
    if (params.length != 3) {
        throw new IllegalArgumentException();
    }

    String assessmentId = params[2];

    // // check expected
    // if (!context.getPostExpected())
    // {
    // // redirect to error
    // res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unexpected)));
    // return;
    // }

    // for the password
    Value value = this.uiService.newValue();
    context.put("password", value);

    // for the honor pledge
    Value pledge = this.uiService.newValue();
    context.put("pledge", pledge);

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

    // if other than the ENTER destination, just go there
    if (!destination.equals("ENTER")) {
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
        return;
    }

    // process: enter the assessment for this user, find the submission id and starting question
    Assessment assessment = assessmentService.getAssessment(assessmentId);
    if (assessment == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // get the submissions from the user to this assessment
    Submission submission = submissionService.getNewUserAssessmentSubmission(assessment, null);
    if (submission == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }

    // check password
    if ((submission.getAssessment().getPassword().getPassword() != null)
            && (!submission.getAssessment().getPassword().checkPassword(value.getValue()))) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.password)));
        return;
    }

    // check pledge
    if (submission.getAssessment().getRequireHonorPledge() && (!"true".equals(pledge.getValue()))) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.pledge)));
        return;
    }

    enterSubmission(req, res, submission);
}