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:uk.gov.devonline.www.xforms.XFormsFilter.java

protected void handleExit(XMLEvent exitEvent, XFormsSession xFormsSession, HttpSession session,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (ChibaEventNames.REPLACE_ALL.equals(exitEvent.getType())) {
        submissionResponse(xFormsSession, request, response);
        //response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/SubmissionResponse?sessionKey=" + xFormsSession.getKey()));
    } else if (ChibaEventNames.LOAD_URI.equals(exitEvent.getType())) {
        if (exitEvent.getContextInfo("show") != null) {
            String loadURI = (String) exitEvent.getContextInfo("uri");

            //kill XFormsSession
            xFormsSession.getManager().deleteXFormsSession(xFormsSession.getKey());

            response.sendRedirect(response.encodeRedirectURL(loadURI));
        }//from  w ww  . j a v a 2 s .c  o  m
    }
    LOG.debug("EXITED DURING XFORMS MODEL INIT!");
}

From source file:org.sakaiproject.nakamura.auth.opensso.OpenSsoAuthenticationHandler.java

/**
 * If a redirect is configured, this method will take care of the redirect.
 * <p>//from w ww . j  a  va2  s.c o  m
 * If user auto-creation is configured, this method will check for an existing
 * Authorizable that matches the principal. If not found, it creates a new Jackrabbit
 * user with all properties blank except for the ID and a randomly generated password.
 * WARNING: Currently this will not perform the extra work done by the Nakamura
 * CreateUserServlet, and the resulting user will not be associated with a valid
 * profile.
 * <p>
 * Note: do not try to inject the token here.  The request has not had the authenticated
 * user added to it so request.getUserPrincipal() and request.getRemoteUser() both
 * return null.
 * <p>
 * TODO This really needs to be dropped to allow for user pull, person directory
 * integrations, etc. See SLING-1563 for the related issue of user population via
 * OpenID.
 *
 * @see org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler#authenticationSucceeded(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      org.apache.sorg.apache.sling.auth.coretionInfo)
 */
public boolean authenticationSucceeded(HttpServletRequest request, HttpServletResponse response,
        AuthenticationInfo authInfo) {
    LOGGER.debug("authenticationSucceeded called");

    // If the plug-in is intended to verify the existence of a matching Authorizable,
    // check that now.
    boolean isUserValid = isUserValid(authInfo);
    if (!isUserValid) {
        LOGGER.warn("SSO authentication succeeded but corresponding user not found or created");
        try {
            dropCredentials(request, response);
        } catch (IOException e) {
            LOGGER.error("Failed to drop credentials after SSO authentication by invalid user", e);
        }
        try {
            // redirect over to SSO to logout to invalidate the session, then return to our
            // server to tell the user about the missing local user.
            String localUrl = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + missingLocalUserUrl;
            String redirectUrl = response.encodeRedirectURL(logoutUrl + "?goto=" + localUrl);
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return true;
    }

    // Check for the default post-authentication redirect.
    return DefaultAuthenticationFeedbackHandler.handleRedirect(request, response);
}

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

/**
 * {@inheritDoc}//from   w ww  .  j  a  v  a  2 s . c  o m
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // Note: parameter and sort logic changes need to be coordinated with QuestionPreviewView.figurePrevNextForPoolEdit()

    // pool id, sort, paging, assessment id, all the rest is return parameters
    if (params.length < 6) {
        throw new IllegalArgumentException();
    }

    boolean fixMode = params[1].equals("pool_fix");
    if (fixMode)
        context.put("fix", Boolean.TRUE);

    String destination = null;
    if (params.length > 6) {
        destination = "/" + StringUtil.unsplit(params, 6, params.length - 6, "/");
    }

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

    // this view
    context.put("view", params[1]);

    if (!this.poolService.allowManagePools(toolManager.getCurrentPlacement().getContext())) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // pool
    String pid = params[2];
    Pool pool = this.poolService.getPool(pid);
    if (pool == null) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
        return;
    }
    context.put("pool", pool);

    // sort
    String sortCode = DEFAULT_SORT;
    if (!params[3].equals("-"))
        sortCode = params[3];
    if ((sortCode == null) || (sortCode.length() != 2)) {
        throw new IllegalArgumentException();
    }
    context.put("sort_column", sortCode.charAt(0));
    context.put("sort_direction", sortCode.charAt(1));
    QuestionService.FindQuestionsSort sort = findSort(sortCode);

    // paging
    String pagingParameter = "1-" + Integer.toString(this.pageSizes.get(0));
    if (!params[4].equals("-"))
        pagingParameter = params[4];
    Integer maxQuestions = this.questionService.countQuestions(pool, null, null, null, null);
    Paging paging = uiService.newPaging();
    paging.setMaxItems(maxQuestions);
    paging.setCurrentAndSize(pagingParameter);
    context.put("paging", paging);

    // assessment id (only if we are editing a historical pool in fix mode)
    String aid = params[5];
    context.put("aid", aid);

    // get questions
    List<Question> questions = questionService.findQuestions(pool, sort, null, null,
            paging.getSize() == 0 ? null : paging.getCurrent(), paging.getSize() == 0 ? null : paging.getSize(),
            null, null);
    context.put("questions", questions);

    // 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:com.ctc.storefront.filters.cms.CMSSiteFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final FilterChain filterChain) throws ServletException, IOException {
    final String requestURL = httpRequest.getRequestURL().toString();

    final CmsPageRequestContextData cmsPageRequestContextData = getCmsPageContextService()
            .initialiseCmsPageContextForRequest(httpRequest);

    // check whether exits valid preview data
    if (cmsPageRequestContextData.getPreviewData() == null) {
        // process normal request (i.e. normal browser non-cmscockpit request)
        if (processNormalRequest(httpRequest, httpResponse)) {
            // proceed filters
            filterChain.doFilter(httpRequest, httpResponse);
        }//w ww. ja va 2 s.c  o m
    } else if (StringUtils.contains(requestURL, PREVIEW_TOKEN)) {
        final String redirectURL = processPreviewRequest(httpRequest, cmsPageRequestContextData);

        // redirect to computed URL
        if (redirectURL.charAt(0) == '/') {
            final String contextPath = httpRequest.getContextPath();
            final String encodedRedirectUrl = httpResponse.encodeRedirectURL(contextPath + redirectURL);
            httpResponse.sendRedirect(encodedRedirectUrl);
        } else {
            final String encodedRedirectUrl = httpResponse.encodeRedirectURL(redirectURL);
            httpResponse.sendRedirect(encodedRedirectUrl);
        }

        // next filter in chain won't be invoked!!!
    } else {
        if (httpRequest.getSession().isNew()) {
            processPreviewData(httpRequest, cmsPageRequestContextData.getPreviewData());
        }
        // proceed filters
        filterChain.doFilter(httpRequest, httpResponse);
    }
}

From source file:org.openbravo.base.secureApp.LoginHandler.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    log4j.debug("start doPost");

    final VariablesSecureApp vars = new VariablesSecureApp(req);

    // Empty session
    req.getSession().removeAttribute("#Authenticated_user");
    vars.removeSessionValue("#AD_Role_ID");
    vars.setSessionObject("#loggingIn", "Y");

    final String strUser = vars.getStringParameter("user");

    // When redirect parameter is true, instead of returning a json object with the login result and
    // target, a redirect to the application or error page is done.
    String strRedirect = vars.getStringParameter("redirect");
    boolean doRedirect = strRedirect != null && !strRedirect.isEmpty() && strRedirect.equalsIgnoreCase("true");

    OBContext.setAdminMode();/*from  w  w  w  .j  av a2 s . c o m*/
    try {
        Client systemClient = OBDal.getInstance().get(Client.class, "0");

        String language = systemClient.getLanguage().getLanguage();

        if (strUser.equals("") && !OBVersion.getInstance().is30()) {
            res.sendRedirect(res.encodeRedirectURL(strDireccion + "/security/Login_F1.html"));
        } else {
            try {
                AuthenticationManager authManager = AuthenticationManager.getAuthenticationManager(this);

                final String strUserAuth = authManager.authenticate(req, res);
                final String sessionId = vars.getSessionValue("#AD_Session_ID");

                if (StringUtils.isEmpty(strUserAuth)) {
                    throw new AuthenticationException("Message");// FIXME
                }
                checkLicenseAndGo(res, vars, strUserAuth, strUser, sessionId, doRedirect);

            } catch (AuthenticationException e) {

                final OBError errorMsg = e.getOBError();

                if (errorMsg != null) {
                    vars.removeSessionValue("#LoginErrorMsg");

                    final String failureTitle = Utility.messageBD(this, errorMsg.getTitle(), language);
                    final String failureMessage = Utility.messageBD(this, errorMsg.getMessage(), language);

                    goToRetry(res, vars, failureMessage, failureTitle, "Error", "../security/Login_FS.html",
                            doRedirect);

                } else {
                    throw new ServletException("Error"); // FIXME
                }
            }
        }
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:de.mpg.escidoc.services.pidcache.web.MainServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info("POST request");

    if (req.getParameter("url") == null) {
        logger.warn("URL parameter failed.");
        resp.sendError(HttpServletResponse.SC_NO_CONTENT, "URL parameter failed.");
    }/*ww  w  .j  a  va  2 s . co m*/
    try {

        if (!authenticate(req, resp)) {
            logger.warn("Unauthorized request from " + req.getRemoteHost());
            return;
        }

        PidCacheService cacheService = new PidCacheService();
        String xmlOutput = null;

        if (logger.isDebugEnabled()) {
            logger.info("request pathInfo <" + req.getPathInfo() + ">");
        }
        if (GwdgPidService.GWDG_PIDSERVICE_CREATE.equals(req.getPathInfo())) {
            xmlOutput = cacheService.create(req.getParameter("url"));
        } else if (GwdgPidService.GWDG_PIDSERVICE_EDIT.equals(req.getPathInfo())) {
            if (req.getParameter("pid") == null) {
                resp.sendError(HttpServletResponse.SC_NO_CONTENT, "PID parameter failed.");
            }
            xmlOutput = cacheService.update(req.getParameter("pid"), req.getParameter("url"));
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getPathInfo());
        }

        resp.encodeRedirectURL(cacheService.getLocation());
        resp.addHeader("Location", cacheService.getLocation());
        resp.getWriter().append(xmlOutput);
    } catch (Exception e) {
        throw new ServletException("Error processing request", e);
    }
}

From source file:org.gatein.sso.agent.opensso.OpenSSOAgentImpl.java

/**
 * This method is useful only for Cross-Domain (CD) authentication scenario when GateIn and OpenSSO are in different DNS domains and they can't share cookie.
 *
 * It performs://from   w w  w.jav  a  2  s .c o m
 * <li>Parse and validate message from OpenSSO CDCServlet.</li>
 * <li>Use ssoToken from parsed message and establish OpenSSO cookie iPlanetDirectoryPro</li>
 * <li>Redirects to InitiateLoginFilter but with cookie established. So in next request, we can perform agent validation against OpenSSO server</li>
 *
 * @param httpRequest
 * @param httpResponse
 * @return true if parameter LARES with message from CDC is present in HttpServletRequest
 * @throws IOException
 */
protected boolean tryMessageFromCDC(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws IOException {
    String encodedCDCMessage = httpRequest.getParameter("LARES");

    if (encodedCDCMessage == null) {
        if (log.isTraceEnabled()) {
            log.trace("Message from CDC not found in this HttpServletRequest");
        }
        return false;
    }

    CDMessageContext messageContext = cdcMessageParser.parseMessage(encodedCDCMessage);
    if (log.isTraceEnabled()) {
        log.trace("Successfully parsed messageContext " + messageContext);
    }

    // Validate received messageContext
    validateCDMessageContext(httpRequest, messageContext);

    // Establish cookie with ssoToken
    String ssoToken = messageContext.getSsoToken();
    Cookie cookie = new Cookie(cookieName, "\"" + ssoToken + "\"");
    cookie.setPath(httpRequest.getContextPath());
    httpResponse.addCookie(cookie);
    if (log.isTraceEnabled()) {
        log.trace("Cookie " + cookieName + " with value " + ssoToken + " added to HttpResponse");
    }

    // Redirect again this request to be processed by OpenSSOAgent. Now we have cookie established
    String urlToRedirect = httpResponse.encodeRedirectURL(httpRequest.getRequestURI());
    httpResponse.sendRedirect(urlToRedirect);

    return true;
}

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

private void logout(HttpServletRequest req, HttpServletResponse resp) {

    String repositoryName;//from  w w w  . j ava 2 s . c om
    try {
        repositoryName = getField(req, resp, "repository");
    } catch (FieldNotFoundException e1) {
        return;
    }

    // Remove ticket from user's session
    TicketService.getTicketService().removeTicket(req, repositoryName);
    req.getSession(true).setAttribute((StatsService.SESSION_LOGGED_USER + repositoryName).toLowerCase(), null);
    String rootURL = getRepositoryURL(req, repositoryName);
    try {
        resp.sendRedirect(resp.encodeRedirectURL(rootURL));
    } catch (IOException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to log out.");
    }
}

From source file:org.wso2.carbon.identity.authenticator.mepin.MepinAuthenticator.java

/**
 * initiate the authentication request//from   ww  w  . jav a  2s . c o  m
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    authenticatorProperties = context.getAuthenticatorProperties();
    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL()
            .replace(MepinConstants.LOGIN_PAGE, MepinConstants.MEPIN_PAGE);
    boolean isSecondStep = false;
    try {
        String authenticatedLocalUsername = getLocalAuthenticatedUser(context).getUserName();
        if (StringUtils.isNotEmpty(authenticatedLocalUsername)) {
            isSecondStep = true;
        }
    } catch (NullPointerException e) {
        log.warn("Username cannot be fetched from previous authentication steps.");
    }

    try {
        String retryParam = "";
        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=authentication.fail.message";
        }
        response.sendRedirect(response.encodeRedirectURL(loginPage + "?authenticators=" + getName()
                + "&applicationId=" + authenticatorProperties.get(MepinConstants.MEPIN_APPICATION_ID)
                + "&callbackUrl=" + authenticatorProperties.get(MepinConstants.MEPIN_CALLBACK_URL) + "&"
                + FrameworkConstants.SESSION_DATA_KEY + "=" + context.getContextIdentifier() + "&isSecondStep="
                + isSecondStep + retryParam));
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while redirecting");
        }
        throw new AuthenticationFailedException("Error while redirecting the MePIN");
    }
}

From source file:org.xwoot.mockiphone.web.filters.BaseFilter.java

/**
 * {@inheritDoc}/*from  w  ww .  jav 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("#######################");

    // 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 (!MockIphoneSite.getInstance().isStarted()) {
        System.out.println("Site is not started yet, starting the wizard.");
        if (!StringUtils.equals(request.getServletPath(), "/bootstrap.do")) {
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/bootstrap.do"));
            return;
        }
    }
    this.config.getServletContext().log("Base Filter applied");

    try {
        request.setAttribute("iwootUrl",
                MockIphoneSite.getInstance().getMockIphoneSiteEngine().getIwootRestClient().getUri());
    } catch (IWootClientException e) {
        throw new ServletException(e);
    }

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