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.openvpms.web.echo.servlet.SpringWebContainerServlet.java

/**
 * Processes a HTTP request and generates a response.
 *
 * @param request  the incoming {@code HttpServletRequest}
 * @param response the outgoing {@code HttpServletResponse}
 *///w ww . ja  v  a 2  s .  c o  m
@Override
protected void process(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    HttpSession session = request.getSession();

    String serviceId = request.getParameter(SERVICE_ID_PARAMETER);
    if (!AsyncMonitorService.SERVICE_ID.equals(serviceId)) {
        // flag the session as active, if the request isn't associated with echo2 asynchronous tasks
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        getSessionMonitor().active(request, authentication);
    }

    if (supportsMultipleInstances(request)) {
        // get next instance-counter
        Integer nextInstance = (Integer) session.getAttribute(NEXT_INSTANCE);
        if (nextInstance == null) {
            nextInstance = 1;
        }

        ServletInstance instance = new ServletInstance(request);

        if (instance.getId() != -1 && instance.getId() < nextInstance) {
            servletName.set(instance.getServletName());
            locale.set(request.getLocale());
            super.process(request, response);
        } else {
            // increase instance-counter
            synchronized (session) {
                nextInstance = (Integer) session.getAttribute(NEXT_INSTANCE);
                if (nextInstance == null) {
                    nextInstance = 1;
                }
                instance.setId(nextInstance);
                nextInstance += 1;
                session.setAttribute(NEXT_INSTANCE, nextInstance);
            }

            servletName.set(instance.getServletName());

            // redirect to new servlet-path including request parameters
            String url = instance.getURI();
            String queryString = request.getQueryString();
            if (queryString != null) {
                url += "?" + queryString;
            }
            response.sendRedirect(response.encodeRedirectURL(url));
        }
    } else {
        servletName.set(request.getServletPath());
        super.process(request, response);
    }
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void login(HttpServletRequest req, HttpServletResponse resp) {

    String repositoryName;/*ww  w.ja va2 s .c om*/
    String username;
    String password;
    try {
        repositoryName = getField(req, resp, "repository");
        username = getField(req, resp, "username");
        password = getField(req, resp, "password");
    } catch (FieldNotFoundException e) {
        return;
    }

    Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
    //TODO: Refactor init/end methods to interface and remove this explicit cast
    JCRSecurityService securityService = (JCRSecurityService) JLibraryServiceFactory.getInstance(profile)
            .getSecurityService();

    Credentials credentials = new Credentials();
    if (username.equals(User.ADMIN_KEYNAME)) {
        username = User.ADMIN_NAME;
    }
    credentials.setUser(username);
    credentials.setPassword(password);
    try {
        Ticket userTicket = securityService.login(credentials, repositoryName);
        TicketService.getTicketService().putTicket(req, repositoryName, userTicket);
        req.getSession(true).setAttribute((StatsService.SESSION_LOGGED_USER + repositoryName).toLowerCase(),
                new LoggedUser());

        // Always forward to root
        resp.sendRedirect(resp.encodeRedirectURL(getRepositoryURL(req, repositoryName)));
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to log in.");
    }
}

From source file:pt.iflow.authentication.AuthWinUserServlet.java

static AuthenticationResult authenticate(final HttpServletRequest request, final HttpServletResponse response,
        final String username, final String password, final String nextUrl)
        throws ServletException, IOException {
    AuthenticationResult result = new AuthenticationResult();
    result.nextUrl = nextUrl;/*from   ww w .  ja v a 2 s  .c o m*/

    HttpSession session = request.getSession();

    Boolean bIsSystem = (Boolean) session.getAttribute(ADMIN_SESSION_NAME);
    boolean isSystem = false;

    if (bIsSystem != null)
        isSystem = bIsSystem.booleanValue();

    String login = Utils.decrypt(username);
    String pass = Utils.decrypt(password);

    if (login != null) {
        login = login.trim();
    }

    boolean licenseOk = LicenseServiceFactory.getLicenseService().isLicenseOK();

    AuthProfile ap = BeanFactory.getAuthProfileBean();

    UserInfoInterface ui = null;

    if (isSystem)
        ui = BeanFactory.getUserInfoFactory().newSystemUserInfo();
    else
        ui = BeanFactory.getUserInfoFactory().newUserInfo();

    Hashtable<String, String> cookies = ServletUtils.getCookies(request);
    if (cookies != null) {
        ui.setCookieLang(cookies.get(Const.LANG_COOKIE));
    }

    ui.login(login, pass);

    // check license status
    if (!licenseOk && !isSystem) {
        result.nextUrl = "Admin/login.jsp";
        session.invalidate();
        return result;
    }

    boolean isAuth = result.isAuth = ui.isLogged();

    if (isAuth) {

        /////////////////////////////
        //
        // Now set some session vars
        //
        /////////////////////////////

        //Application Data
        session.setAttribute("login", login);

        session.setAttribute(Const.USER_INFO, ui);
        UserSettings settings = ui.getUserSettings();
        OrganizationData orgData = ap.getOrganizationInfo(ui.getOrganization());
        session.setAttribute(Const.ORG_INFO, orgData);

        OrganizationTheme orgTheme = BeanFactory.getOrganizationThemeBean();
        if (orgTheme != null) {
            OrganizationThemeData themeData = orgTheme.getOrganizationTheme(ui);
            session.setAttribute("themedata", themeData);
        }

        if (ui.isPasswordExpired()) {
            result.nextUrl = "changePassword";
        }

        if (!isSystem && settings.isDefault() && Const.USE_INDIVIDUAL_LOCALE && Const.ASK_LOCALE_AT_LOGIN) {
            result.nextUrl = "setupUser";
        }

        // check license status
        if (!licenseOk && isSystem) {
            result.nextUrl = "Admin/licenseValidation.jsp";
        }

        session.setAttribute("SessionHelperToken", new SimpleSessionHelper());

    } else {
        result.nextUrl = "main.jsp";
        result.errorMsg = ui.getError();
        session.setAttribute("login_error", result.errorMsg);
    }
    PersistSession ps = new PersistSession();
    ps.getSession(ui, session);

    response.sendRedirect(response.encodeRedirectURL("main.jsp"));

    return result;
}

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

/**
 * {@inheritDoc}/*from ww  w  .  j  a v a2  s. c o m*/
 */
public void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need two parameters (sid/question selector) and optional anchor
    // question selector may end in "!" for "last chance" - linear repeat question when it was not answered
    if (params.length < 5) {
        throw new IllegalArgumentException();
    }

    String submissionId = params[2];
    String questionSelector = params[3];
    boolean lastChance = false;
    if (questionSelector.endsWith("!")) {
        questionSelector = questionSelector.substring(0, questionSelector.length() - 1);
        lastChance = true;
    }

    String returnDestination = null;
    if (params.length > 5) {
        returnDestination = "/" + StringUtil.unsplit(params, 5, params.length - 5, "/");
    }
    // if not specified, go to the main list view
    else {
        returnDestination = "/list";
    }

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

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

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

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

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

    String redirectUrl = null;
    if (destination.startsWith("REDIRECT:")) {
        String[] parts = StringUtil.splitFirst(destination, ":");
        redirectUrl = "/!PORTAL!/" + parts[1];
        destination = "LIST";
    }

    // check for file upload error
    boolean uploadError = ((req.getAttribute("upload.status") != null)
            && (!req.getAttribute("upload.status").equals("ok")));

    // if we are going to submitted, we must complete the submission (unless there was an upload error)
    Boolean complete = Boolean.valueOf((!uploadError) && destination.startsWith("/submitted"));

    // unless we are going to list, instructions, or this very same question, or we have a file upload error, mark the
    // answers as complete
    Boolean answersComplete = Boolean.valueOf(!(uploadError || destination.startsWith("LIST")
            || destination.startsWith("STAY") || destination.startsWith("/instructions")
            || destination.equals(context.getPreviousDestination())));

    // and if we are working in a random access test, answers are always complete
    if (submission.getAssessment().getRandomAccess())
        answersComplete = Boolean.TRUE;

    // post-process the answers
    for (Answer answer : answers) {
        answer.getTypeSpecificAnswer().consolidate(destination);
    }

    // linear order check - unless this was a last chance display
    boolean repeat = false;
    if (!lastChance) {
        if (!submission.getAssessment().getRandomAccess().booleanValue()) {
            // linear order is always presented by-question
            if (answers.size() == 1) {
                Answer answer = answers.get(0);
                boolean answered = answer.getIsAnswered().booleanValue();
                if (!answered) {
                    repeat = true;

                    // don't mark the answer as complete, so we can re-enter
                    answersComplete = false;
                }
            }
        }
    }

    // where are we going?
    destination = questionChooseDestination(context, destination, questionSelector, submissionId, params,
            repeat, returnDestination);

    Boolean auto = Boolean.FALSE;

    // submit all answers
    try {
        // if we are doing AUTO, and the submission is really timed out, set complete
        if (destination.equals("AUTO")) {
            // check if this submission is really done (time over, past deadline)
            if (submission.getIsOver(new Date(), 0)) {
                auto = Boolean.TRUE;
                complete = Boolean.TRUE;
                destination = "/submitted/" + submissionId + returnDestination;
            } else {
                // if for some reason we are here (AUTO) but the submission is not yet really over, just return to list
                destination = "/list";
                complete = Boolean.FALSE;
            }
        }

        submissionService.submitAnswers(answers, answersComplete, complete, auto);

        // if there was an upload error, send to the upload error
        if ((req.getAttribute("upload.status") != null) && (!req.getAttribute("upload.status").equals("ok"))) {
            res.sendRedirect(res.encodeRedirectURL(
                    Web.returnUrl(req, "/error/" + Errors.upload + "/" + req.getAttribute("upload.limit"))));
            return;
        }

        if (destination.equals("SUBMIT")) {
            // get the submission again, to make sure that the answers we just posted are reflected
            submission = submissionService.getSubmission(submissionId);

            // if linear, or the submission is all answered, or this is a single question assessment, we can complete the submission and go to submitted
            if ((!submission.getAssessment().getRandomAccess()) || (submission.getIsAnswered())
                    || (submission.getAssessment().getIsSingleQuestion())) {
                submissionService.completeSubmission(submission, Boolean.FALSE);

                destination = "/submitted/" + submissionId + returnDestination;
            }

            // if not linear, and there are unanswered parts, send to final review
            else {
                destination = "/final_review/" + submissionId + returnDestination;
            }
        }

        if (redirectUrl != null) {
            // redirect to the full URL
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, redirectUrl)));
            return;
        }

        // redirect to the next destination
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, destination)));
        return;
    } catch (AssessmentClosedException e) {
    } catch (SubmissionCompletedException e) {
    } catch (AssessmentPermissionException e) {
    }

    // redirect to error
    res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.FormAuthenticator.java

/** Perform form authentication.
 * Called from SecurityHandler.//  w  w w .ja  v  a  2 s  .  c  om
 * @return UserPrincipal if authenticated else null.
 */
public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest httpRequest,
        HttpResponse httpResponse) throws IOException {
    HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper();
    HttpServletResponse response = httpResponse == null ? null
            : (HttpServletResponse) httpResponse.getWrapper();

    // Handle paths
    String uri = pathInContext;

    // Setup session 
    HttpSession session = request.getSession(response != null);
    if (session == null)
        return null;

    // Handle a request for authentication.
    if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) {
        // Check the session object for login info.
        FormCredential form_cred = new FormCredential();
        form_cred.authenticate(realm, request.getParameter(__J_USERNAME), request.getParameter(__J_PASSWORD),
                httpRequest);

        String nuri = (String) session.getAttribute(__J_URI);
        if (nuri == null || nuri.length() == 0) {
            nuri = request.getContextPath();
            if (nuri.length() == 0)
                nuri = "/";
        }

        if (form_cred._userPrincipal != null) {
            // Authenticated OK
            if (log.isDebugEnabled())
                log.debug("Form authentication OK for " + form_cred._jUserName);
            session.removeAttribute(__J_URI); // Remove popped return URI.
            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            httpRequest.setAuthUser(form_cred._jUserName);
            httpRequest.setUserPrincipal(form_cred._userPrincipal);
            session.setAttribute(__J_AUTHENTICATED, form_cred);

            // Sign-on to SSO mechanism
            if (realm instanceof SSORealm) {
                ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal,
                        new Password(form_cred._jPassword));
            }

            // Redirect to original request
            if (response != null) {
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(nuri));
            }
        } else if (response != null) {
            if (log.isDebugEnabled())
                log.debug("Form authentication FAILED for " + form_cred._jUserName);
            if (_formErrorPage != null) {
                response.setContentLength(0);
                response.sendRedirect(
                        response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage)));
            } else {
                response.sendError(HttpResponse.__403_Forbidden);
            }
        }

        // Security check is always false, only true after final redirection.
        return null;
    }

    // Check if the session is already authenticated.
    FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);

    if (form_cred != null) {
        // We have a form credential. Has it been distributed?
        if (form_cred._userPrincipal == null) {
            // This form_cred appears to have been distributed.  Need to reauth
            form_cred.authenticate(realm, httpRequest);

            // Sign-on to SSO mechanism
            if (form_cred._userPrincipal != null && realm instanceof SSORealm) {
                ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal,
                        new Password(form_cred._jPassword));
            }
        } else if (!realm.reauthenticate(form_cred._userPrincipal))
            // Else check that it is still authenticated.
            form_cred._userPrincipal = null;

        // If this credential is still authenticated
        if (form_cred._userPrincipal != null) {
            if (log.isDebugEnabled())
                log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName());
            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            httpRequest.setAuthUser(form_cred._userPrincipal.getName());
            httpRequest.setUserPrincipal(form_cred._userPrincipal);
            return form_cred._userPrincipal;
        } else
            session.setAttribute(__J_AUTHENTICATED, null);
    } else if (realm instanceof SSORealm) {
        // Try a single sign on.
        Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse);

        if (httpRequest.hasUserPrincipal()) {
            form_cred = new FormCredential();
            form_cred._userPrincipal = request.getUserPrincipal();
            form_cred._jUserName = form_cred._userPrincipal.getName();
            if (cred != null)
                form_cred._jPassword = cred.toString();
            if (log.isDebugEnabled())
                log.debug("SSO for " + form_cred._userPrincipal);

            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            session.setAttribute(__J_AUTHENTICATED, form_cred);
            return form_cred._userPrincipal;
        }
    }

    // Don't authenticate authform or errorpage
    if (isLoginOrErrorPage(pathInContext))
        return SecurityConstraint.__NOBODY;

    // redirect to login page
    if (response != null) {
        if (httpRequest.getQuery() != null)
            uri += "?" + httpRequest.getQuery();
        session.setAttribute(__J_URI, request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + URI.addPaths(request.getContextPath(), uri));
        response.setContentLength(0);
        response.sendRedirect(
                response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage)));
    }

    return null;
}

From source file:org.apache.struts.action.RequestProcessor.java

/**
 * <p>Forward or redirect to the specified destination, by the specified
 * mechanism.  This method uses a <code>ForwardConfig</code> object
 * instead an <code>ActionForward</code>.</p>
 *
 * @param request  The servlet request we are processing
 * @param response The servlet response we are creating
 * @param forward  The ForwardConfig controlling where we go next
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet exception occurs
 *//*from w w w. ja  v  a2  s  . co m*/
protected void processForwardConfig(HttpServletRequest request, HttpServletResponse response,
        ForwardConfig forward) throws IOException, ServletException {
    if (forward == null) {
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("processForwardConfig(" + forward + ")");
    }

    String forwardPath = forward.getPath();
    String uri;

    // If the forward can be unaliased into an action, then use the path of the action
    String actionIdPath = RequestUtils.actionIdURL(forward, request, servlet);
    if (actionIdPath != null) {
        forwardPath = actionIdPath;
        ForwardConfig actionIdForward = new ForwardConfig(forward);
        actionIdForward.setPath(actionIdPath);
        forward = actionIdForward;
    }

    // paths not starting with / should be passed through without any
    // processing (ie. they're absolute)
    if (forwardPath.startsWith("/")) {
        // get module relative uri
        uri = RequestUtils.forwardURL(request, forward, null);
    } else {
        uri = forwardPath;
    }

    if (forward.getRedirect()) {
        // only prepend context path for relative uri
        if (uri.startsWith("/")) {
            uri = request.getContextPath() + uri;
        }

        response.sendRedirect(response.encodeRedirectURL(uri));
    } else {
        doForward(uri, request, response);
    }
}

From source file:org.jahia.bin.Render.java

/**
 * This method allows you to define where you want to redirect the user after request.
 *
 * @param url//from  w w w .jav a 2s.  co m
 * @param path
 * @param req
 * @param resp
 * @param parameters
 * @param bypassCache If true we will append a parameter to the URL that should match the id of the resource to refresh
 * @throws IOException
 */
public static void performRedirect(String url, String path, HttpServletRequest req, HttpServletResponse resp,
        Map<String, List<String>> parameters, boolean bypassCache) throws IOException {
    String renderedURL = null;

    List<String> stringList = parameters.get(NEW_NODE_OUTPUT_FORMAT);
    String outputFormat = !CollectionUtils.isEmpty(stringList) && stringList.get(0) != null ? stringList.get(0)
            : "html";

    stringList = parameters.get(REDIRECT_HTTP_RESPONSE_CODE);
    int responseCode = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? Integer.parseInt(stringList.get(0))
            : HttpServletResponse.SC_SEE_OTHER;

    stringList = parameters.get(REDIRECT_TO);
    String stayOnPage = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? StringUtils.substringBeforeLast(stringList.get(0), ";")
            : null;

    if (!Login.isAuthorizedRedirect(req, stayOnPage, true)) {
        logger.warn("Unauthorized attempt redirect to {}", stayOnPage);
        stayOnPage = null;
    }

    if (!StringUtils.isEmpty(stayOnPage)) {
        renderedURL = stayOnPage + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    } else if (!StringUtils.isEmpty(url)) {
        String requestedURL = req.getRequestURI();
        //            String encodedPath = URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
        String decodedURL = URLDecoder.decode(requestedURL, "UTF-8");

        int index = decodedURL.indexOf(path);

        renderedURL = decodedURL.substring(0, index) + url
                + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    }
    if (bypassCache) {
        stringList = parameters.get(RESOURCE_ID);
        String formuuid = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
                ? stringList.get(0)
                : null;
        if (formuuid != null) {
            renderedURL = renderedURL + "?ec=" + formuuid;
        }
    }
    if (!StringUtils.isEmpty(renderedURL)) {
        String redirect = resp.encodeRedirectURL(renderedURL);
        if (SettingsBean.getInstance().isDisableJsessionIdParameter()) {
            String s = ";" + SettingsBean.getInstance().getJsessionIdParameterName();
            if (redirect.contains(s)) {
                redirect = SessionidRemovalResponseWrapper.removeJsessionId(redirect);
            }
        }
        if (StringUtils.isEmpty(stayOnPage)) {
            resp.setHeader("Location", redirect);
        } else if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
            resp.setHeader("Location", redirect);
        }
        if (responseCode == HttpServletResponse.SC_FOUND) {
            resp.sendRedirect(redirect);
        } else {
            resp.setStatus(responseCode);
        }
    }
}

From source file:fll.web.UploadSpreadsheet.java

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

    final StringBuilder message = new StringBuilder();
    String nextPage;//from   www .  j  a  va2s.  c  o m
    try {
        UploadProcessor.processUpload(request);
        final String uploadRedirect = (String) request.getAttribute("uploadRedirect");
        if (null == uploadRedirect) {
            throw new RuntimeException(
                    "Missing parameter 'uploadRedirect' params: " + request.getParameterMap());
        }
        session.setAttribute("uploadRedirect", uploadRedirect);

        final FileItem fileItem = (FileItem) request.getAttribute("file");
        final String extension = Utilities.determineExtension(fileItem.getName());
        final File file = File.createTempFile("fll", extension);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Wrote data to: " + file.getAbsolutePath());
        }
        fileItem.write(file);
        session.setAttribute(SPREADSHEET_FILE_KEY, file.getAbsolutePath());

        if (ExcelCellReader.isExcelFile(file)) {
            final List<String> sheetNames = ExcelCellReader.getAllSheetNames(file);
            if (sheetNames.size() > 1) {
                session.setAttribute("sheetNames", sheetNames);
                nextPage = "promptForSheetName.jsp";
            } else {
                session.setAttribute(SHEET_NAME_KEY, sheetNames.get(0));
                nextPage = uploadRedirect;
            }
        } else {
            nextPage = uploadRedirect;
        }

    } catch (final FileUploadException e) {
        message.append("<p class='error'>Error processing team data upload: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error processing team data upload", e);
    } catch (final Exception e) {
        message.append("<p class='error'>Error saving team data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving team data into the database", e);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL(nextPage));
}

From source file:grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Spring Security won't save the original request
        requestCache.saveRequest(request, response);
    }//from   w  ww.j  a  va 2 s.  co m

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (useForward && (errorPage != null || ajaxError)) {
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.getRequestDispatcher(ajaxError ? ajaxErrorPage : errorPage).forward(request, response);
        return;
    }

    String redirectUrl;
    String serverURL = ReflectionUtils.getGrailsServerURL();
    if (serverURL == null) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }
        redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    } else {
        redirectUrl = serverURL;
    }

    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

From source file:org.jasig.portal.url.UrlCanonicalizingFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    if ("GET".equals(request.getMethod())) {
        final String canonicalUrl = this.urlSyntaxProvider.getCanonicalUrl(request);

        final String canonicalUri;
        final int queryStringIndex = canonicalUrl.indexOf("?");
        if (queryStringIndex < 0) {
            canonicalUri = canonicalUrl;
        } else {//from   w w w  . j  a va 2s .  c o  m
            canonicalUri = canonicalUrl.substring(0, queryStringIndex);
        }

        final String requestURI = request.getRequestURI();

        final int redirectCount = this.getRedirectCount(request);
        if (!canonicalUri.equals(requestURI)) {
            if (redirectCount < this.maximumRedirects) {
                this.setRedirectCount(request, response, redirectCount + 1);

                /*
                 * This is the place where we should decide if...
                 *   - (1) the user is a guest
                 *   - (2) the canonicalUrl is not the requested content
                 *   - (3) there is a strategy for external login
                 *
                 * If all of these are true, we should attempt to send the 
                 * user to external login with a properly-encoded deep-linking 
                 * service URL attached.
                 */

                String encodedTargetUrl = null;

                IPerson person = personManager.getPerson(request);
                if (/* #1 */ person.isGuest() && /* #2 */ urlSyntaxProvider
                        .doesRequestPathReferToSpecificAndDifferentContentVsCanonicalPath(requestURI,
                                canonicalUri)
                        && /* #3 */ loginRefUrlEncoder != null) {
                    encodedTargetUrl = loginRefUrlEncoder.encodeLoginAndRefUrl(request);
                }

                if (encodedTargetUrl == null) {
                    // For whatever reason, we haven't chosen to send the 
                    // user through external login, so we use the canonicalUrl
                    encodedTargetUrl = response.encodeRedirectURL(canonicalUrl);
                }

                response.sendRedirect(encodedTargetUrl);
                logger.debug("Redirecting from {} to canonicalized URL {}, redirect {}",
                        new Object[] { requestURI, canonicalUri, redirectCount });
                return;
            }

            this.clearRedirectCount(request, response);
            logger.debug("Not redirecting from {} to canonicalized URL {} due to limit of {} redirects",
                    new Object[] { requestURI, canonicalUri, redirectCount });
        } else if (redirectCount > 0) {
            this.clearRedirectCount(request, response);
        }
    }

    final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(request);
    final UrlType urlType = portalRequestInfo.getUrlType();
    final UrlState urlState = portalRequestInfo.getUrlState();

    final PortalHttpServletResponseWrapper httpServletResponseWrapper = new PortalHttpServletResponseWrapper(
            response);
    final PortalHttpServletRequestWrapper httpServletRequestWrapper = new PortalHttpServletRequestWrapper(
            request, httpServletResponseWrapper, this.userInstanceManager);

    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_TYPE_HEADER, urlType.toString());
    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_STATE_HEADER, urlState.toString());

    //Hack to make PortalController work in light of https://jira.springsource.org/secure/attachment/18283/SPR7346.patch
    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_TYPE_HEADER + "." + urlType,
            Boolean.TRUE.toString());
    httpServletRequestWrapper.setHeader(IPortalRequestInfo.URL_STATE_HEADER + "." + urlState,
            Boolean.TRUE.toString());

    filterChain.doFilter(httpServletRequestWrapper, httpServletResponseWrapper);
}