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:mitm.djigzo.web.services.security.InvalidateUserSpringSecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("HttpServletRequest expected.");
    }/*from   w  w w  . j a  v a  2s  .co  m*/

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("HttpServletResponse expected.");
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    String loggedInUserName = null;

    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();

    if (loggedInUser != null) {
        loggedInUserName = loggedInUser.getName();
    }

    if (loggedInUserName != null) {
        String email = StringUtils.trimToNull(request.getParameter(usernameRequestParameter));

        if (email != null) {
            email = EmailAddressUtils.canonicalize(email);

            if (!email.equals(loggedInUserName)) {
                /*
                 * The user has changed, so invalidate session
                 */
                HttpSession session = httpServletRequest.getSession(false);

                if (session != null) {
                    session.invalidate();
                }

                SecurityContextHolder.clearContext();

                /*
                 * We need to 'reload' the complete request to make sure the user need to login
                 */
                StringBuffer redirectURL = httpServletRequest.getRequestURL();

                if (httpServletRequest.getQueryString() != null) {
                    redirectURL.append("?").append(httpServletRequest.getQueryString());
                }

                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(redirectURL.toString()));

                return;
            }
        }
    }

    chain.doFilter(request, response);
}

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

/**
 * {@inheritDoc}//from w w  w  .  ja  va2 s.com
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need two parameters (sid/question selector) and optional anchor
    if ((params.length != 4) && (params.length != 5)) {
        throw new IllegalArgumentException();
    }

    String submissionId = params[2];
    String questionSelector = params[3];
    String anchor = (params.length == 5) ? params[4] : null;

    // adjust the current destination to remove the anchor
    String curDestination = context.getDestination();
    if (anchor != null) {
        int pos = curDestination.lastIndexOf("/");
        curDestination = curDestination.substring(0, pos);
    }
    context.put("curDestination", curDestination);

    Submission submission = submissionService.getSubmission(submissionId);

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

    // handle our 'z' selector - redirect to the appropriate question to re-enter this submission
    if ("z".equals(questionSelector)) {
        try {
            this.submissionService.enterSubmission(submission);
        } catch (AssessmentPermissionException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        } catch (AssessmentClosedException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
            return;
        } catch (AssessmentCompletedException e) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
            return;
        }

        redirectToQuestion(req, res, submission, true, false);
        return;
    }

    // if the submission has past a hard deadline or ran out of time, close it and tell the user
    if (submission.completeIfOver()) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.over)));
        return;
    }

    context.put("actionTitle", messages.getString("question-header-work"));

    // collect the questions (actually their answers) to put on the page
    List<Answer> answers = new ArrayList<Answer>();

    Errors err = questionSetup(submission, questionSelector, context, answers, true);
    if (err != null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + err + "/" + submissionId)));
        return;
    }

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

    if (anchor != null)
        context.put("anchor", anchor);

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

From source file:org.mycore.frontend.editor.MCREditorServlet.java

/**
 * Writes the output of editor to a local file in the web application
 * directory. Usage: &lt;target type="webapp" name="{relative_path_to_file}"
 * url="{redirect url after file is written}" /&gt; If cancel url is given,
 * user is redirected to that page, otherwise target url is used.
 * // w  w  w . j  a  v  a 2  s. c  o  m
 * @throws IOException
 */
private void sendToWebAppFile(HttpServletRequest req, HttpServletResponse res, MCREditorSubmission sub,
        Element editor) throws IOException {
    String path = sub.getParameters().getParameter("_target-name");

    LOGGER.debug("Writing editor output to webapp file " + path);

    File f = getWebAppFile(path);
    if (!f.getParentFile().exists()) {
        f.getParentFile().mkdirs();
    }
    FileOutputStream fout = new FileOutputStream(f);
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding("UTF-8"));
    outputter.output(sub.getXML(), fout);
    fout.close();

    String url = sub.getParameters().getParameter("_target-url");
    Element cancel = editor.getChild("cancel");
    if ((url == null || url.length() == 0) && cancel != null && cancel.getAttributeValue("url") != null) {
        url = cancel.getAttributeValue("url");
    }

    LOGGER.debug("EditorServlet redirecting to " + url);
    res.sendRedirect(res.encodeRedirectURL(url));
}

From source file:com.mindquarry.webapp.servlet.AuthenticationFilter.java

/**
 * Filter method that implements the actual logic and decides whether to
 * process by calling the next filter in the chain (another filter or the
 * servlet) or stopping here and sending a special response (authentication
 * request or redirect).//from w w  w  . j av a 2s  .  co  m
 *  
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    // cast to http request and response due to read and set http headers
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    // always send an authentication request in order to avoid one round trip 
    response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm_ + "\"");

    // only do authentication for protected URIs, eg. excluded login page
    if (isProtected(request)) {
        String authenticatedUser = authenticateUser(request);

        // the special login request is done to actually perform the
        // authentication, this is typically the second step initiated by
        // the login page
        if (isLoginRequest(request)) {
            if (authenticatedUser == null) {
                // not authenticated. trigger auth. with username / password
                // either by the HTTP auth dialog in the browser or
                // automatically by Javascript XMLHttpRequest
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                // authenticated. redirect to original target
                String originalUrl = request.getParameter(TARGET_URI_PARAM);
                String redirectUrl = response.encodeRedirectURL((originalUrl != null ? originalUrl : "."));
                response.sendRedirect(redirectUrl);
            }

            // no further servlet processing.
            return;

        } else {
            // 99 percent of all pages, not the special login request.

            // here we either have the first request to the server, ie.
            // not yet authenticated, or some client that does not send the
            // authorization data preemptively (although he already did
            // authenticate) -> see isGuiBrowserRequest()
            if (authenticatedUser == null) {
                // not authenticated.

                // standard browser with preemptive sending auth data, thus
                // it must be the first request -> go to login page
                if (isGuiBrowserRequest(request)) {
                    String loginUrl = buildLoginUrlForRequest(request);
                    String redirectUrl = response.encodeRedirectURL(loginUrl);
                    response.sendRedirect(redirectUrl);
                } else {
                    // trigger simple client auth. or re-authentication
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }

                // no further servlet processing.
                return;

            } else {
                // authenticated. make username available as request attribute
                request.setAttribute(USERNAME_ATTR, authenticatedUser);
            }
        }
    }

    // access granted, proceed with the servlet
    chain.doFilter(servletRequest, servletResponse);
}

From source file:org.acegisecurity.ui.AbstractProcessingFilter.java

protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
    String finalUrl;//  w  w w  .  j av a  2  s  .c o m
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        if (useRelativeContext) {
            finalUrl = url;
        } else {
            finalUrl = request.getContextPath() + url;
        }
    } else if (useRelativeContext) {
        // Calculate the relative URL from the fully qualifed URL, minus the
        // protocol and base context.
        int len = request.getContextPath().length();
        int index = url.indexOf(request.getContextPath()) + len;
        finalUrl = url.substring(index);
        if (finalUrl.length() > 1 && finalUrl.charAt(0) == '/') {
            finalUrl = finalUrl.substring(1);
        }
    } else {
        finalUrl = url;
    }

    Assert.isTrue(!response.isCommitted(),
            "Response already committed; the authentication mechanism must be able to modify buffer size");
    response.setBufferSize(bufferSize);
    response.sendRedirect(response.encodeRedirectURL(finalUrl));
}

From source file:org.xwoot.iwoot.web.filter.InitFilter.java

/**
 * {@inheritDoc}/* w ww. j  a v  a  2s.co m*/
 * 
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) srequest;
    HttpServletResponse response = (HttpServletResponse) sresponse;

    // System.out.println("#######################");
    // System.out.println("# BaseFilter ");
    // System.out.println("# ---------- ");
    // System.out.println("# Request URI  : " + request.getRequestURI());
    // System.out.println("# Context Path : " + request.getContextPath());
    // System.out.println("# Method       : " + request.getMethod());
    // System.out.println("# Remote Host  : " + request.getRemoteHost());
    // System.out.println("# Remote Addr  : " + request.getRemoteAddr());
    // System.out.println("# Remote Port  : " + request.getRemotePort());
    // System.out.println("# Remote User  : " + request.getRemoteUser());
    // System.out.println("# Session ID   : "
    // + request.getRequestedSessionId());
    // System.out.println("#######################");

    System.out.println("Filter");
    // Changing the skin.
    if (request.getParameter("skin") != null) {
        request.getSession().setAttribute("skin", request.getParameter("skin"));
    }

    // Always display the wizard when mockiphone is not initialized
    if (!IWootWebApp.getInstance().isStarted()) {
        System.out.println("Site is not started yet, starting the wizard." + request.getServletPath());
        if (!StringUtils.equals(request.getServletPath(), "/bootstrap.do")) {
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/bootstrap.do"));
            return;
        }
    }
    this.config.getServletContext().log("Base Filter applied");

    // Restlet gestion
    RestApplication appli = (RestApplication) this.config.getServletContext()
            .getAttribute("com.noelios.restlet.ext.servlet.ServerServlet.application");

    /*     if(appli==null){
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/bootstrap.do"));
    return;
    //            srequest.getRequestDispatcher("/rest").forward(srequest, sresponse);
    //            return;
         }
    */

    if (IWootWebApp.getInstance().isStarted() && appli != null && appli.getIwoot() == null) {
        appli.setIwoot(IWootWebApp.getInstance().getIWootEngine());
    }

    if (appli != null) {
        System.out.println((IWootWebApp.getInstance().isStarted()) + " " + " " + (appli.getIwoot()) == null);
    }

    // Let the request be further processed.
    chain.doFilter(request, response);
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

private void sendToSubSelect(HttpServletResponse res, MCRRequestParameters parms, List variables, String root)
        throws IOException {
    String webpage = parms.getParameter("subselect.webpage");
    String sessionID = parms.getParameter("subselect.session");

    Element editor = MCREditorSessionCache.instance().getEditorSession(sessionID).getXML();
    MCREditorSubmission subnew = new MCREditorSubmission(editor, variables, root, parms);

    editor.removeChild("input");
    editor.removeChild("repeats");
    editor.removeChild("failed");
    editor.addContent(subnew.buildInputElements());
    editor.addContent(subnew.buildRepeatElements());

    // Redirect to webpage to reload editor form
    StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());
    sb.append(webpage);//from w w w. j a  v a2 s  . c o  m
    if (!webpage.contains("XSL.editor.session.id=")) {
        sb.append("XSL.editor.session.id=");
        sb.append(sessionID);
    }

    LOGGER.debug("Editor redirect to " + sb.toString());
    res.sendRedirect(res.encodeRedirectURL(sb.toString()));
}

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

/**
 * {@inheritDoc}/*  w ww.  j  a v  a 2 s.  com*/
 */
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];
    String returnDestination = null;
    if (params.length > 3) {
        returnDestination = "/" + StringUtil.unsplit(params, 3, params.length - 3, "/");
    }

    // if not specified, go to the main list view
    else {
        returnDestination = "/list";
    }

    // // 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, returnDestination);
}

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

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //SSOSession session = null;
    //SSOUser user = null;

    if (logger.isDebugEnabled())
        logger.debug("JOSSO Command : [cmd=" + getSSOCmd(request) + "]");

    try {/*from   w ww.j av a2 s.  c om*/

        // Logout user
        SSOGateway g = getSSOGateway();
        prepareContext(request);

        //user = g.findUserInSession(session.getProcessId());

        // Clear josso cookie
        // Cookie ssoCookie = newJossoCookie(request.getContextPath(), "-");
        // response.addCookie(ssoCookie);
        g.logout();

        removeJossoSessionId(request, response);

    } catch (SSOException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        ActionErrors errors = new ActionErrors();
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("sso.login.failed"));
        saveErrors(request, errors);
    }

    // Redirect the user to the proper page, if any
    String back_to = request.getParameter(PARAM_JOSSO_BACK_TO);

    if (back_to == null) {
        // Try with the configured URL if any.
        SSOWebConfiguration c = Lookup.getInstance().lookupSSOWebConfiguration();
        back_to = c.getLogoutBackToURL();
    }

    if (back_to != null) {
        if (logger.isDebugEnabled())
            logger.debug("[logout()], ok->redirecting to : " + back_to);
        response.sendRedirect(response.encodeRedirectURL(back_to));
        return null; // No forward is needed.
    }

    if (logger.isDebugEnabled())
        logger.debug("[logout()], ok");

    return mapping.findForward("success");
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * A post request deals with form interactions.
 *
 * @param request  The servlet request//from   w  w  w  . java 2s  .com
 * @param response The servlet response
 * @throws ServletException Error in request handling
 * @throws IOException Error doing other IO
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    Adapter adapter = null;

    try {
        adapter = (Adapter) session.getAttribute("chiba.adapter");
        if (adapter == null) {
            throw new ServletException(Config.getInstance().getErrorMessage("session-invalid"));
        }
        adapter.beanCtx.put("chiba.useragent", request.getHeader("User-Agent"));
        adapter.beanCtx.put("chiba.web.request", request);
        adapter.beanCtx.put("chiba.web.session", session);
        //adapter.executeHandler();
        adapter.execute();

        // Check for redirects
        String redirectURI = (String) adapter.beanCtx.get(ChibaAdapter.LOAD_URI);
        if (redirectURI != null) {
            String redirectTo = redirectURI;
            adapter.shutdown();
            response.sendRedirect(response.encodeRedirectURL(redirectTo));
            adapter.beanCtx.put(ChibaAdapter.LOAD_URI, null);
            return;
        }

        // Check for forwards
        Map forwardMap = (Map) adapter.beanCtx.get(ChibaAdapter.SUBMISSION_RESPONSE);
        InputStream forwardStream = (InputStream) forwardMap.get(ChibaAdapter.SUBMISSION_RESPONSE_STREAM);
        if (forwardStream != null) {
            adapter.shutdown();

            // fetch response stream
            InputStream responseStream = (InputStream) forwardMap
                    .remove(ChibaAdapter.SUBMISSION_RESPONSE_STREAM);

            // copy header info
            Iterator iterator = forwardMap.keySet().iterator();
            while (iterator.hasNext()) {
                String name = iterator.next().toString();
                String value = forwardMap.get(name).toString();
                response.setHeader(name, value);
            }

            // copy stream content
            byte[] copyBuffer = new byte[8092];
            OutputStream out = response.getOutputStream();
            int readLength = responseStream.read(copyBuffer);
            do {
                out.write(copyBuffer, 0, readLength);
                readLength = responseStream.read(copyBuffer);
            } while (readLength >= 0);

            responseStream.close();
            out.close();

            // remove forward response and terminate
            adapter.beanCtx.put(ChibaAdapter.SUBMISSION_RESPONSE, null);
            return;
        }

        // Neither redirects nor forwards, handle it the normal way.
        response.setContentType("text/html");
        Writer writer = response.getWriter();
        adapter.generator.setOutput(writer);
        adapter.buildUI();
        writer.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception processing XForms", e);
        shutdown(adapter, session, e, request, response);
    }
}