Example usage for javax.servlet RequestDispatcher forward

List of usage examples for javax.servlet RequestDispatcher forward

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher forward.

Prototype

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Source Link

Document

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Usage

From source file:com.alfaariss.oa.profile.saml2.profile.sso.SingleLogout.java

private void processLogoutRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context, String sBinding,
        String sReason) throws OAException, SAML2SecurityException, StatusException {
    //Validate requestor and signature
    validateRequest(context, SPSSODescriptor.DEFAULT_ELEMENT_NAME);

    //Process request
    ITGT tgt = _protocol.processRequest(context);

    String sInReponseTo = context.getInboundSAMLMessageId();
    String sIssuer = context.getInboundMessageIssuer();

    //DD remove the requestor id, if not: the issuer will recieve a logout request
    tgt.removeRequestorID(sIssuer);/*from  w w  w .  ja v  a  2 s. c  om*/

    boolean bIsPartiallyLogout = false;
    if (sReason != null && sReason.equals(LogoutResponse.SP_TIMEOUT_URI)) {
        bIsPartiallyLogout = tgt.getRequestorIDs().size() > 0;
    }

    if (bIsPartiallyLogout || sBinding.equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {//process synchronous logout

        //Process response        
        _protocol.processResponse(tgt, sInReponseTo, context, bIsPartiallyLogout);

        //Send response      
        sendResponse(context, servletRequest, servletResponse, sBinding);

        _eventLogger.info(new UserEventLogItem(null, tgt.getId(), null, UserEvent.USER_LOGGED_OUT,
                tgt.getUser().getID(), servletRequest.getRemoteAddr(), context.getInboundMessageIssuer(), this,
                context.getOutboundSAMLMessageId()));
    } else {//process a-synchronous logout
        ISession session = _sessionFactory.createSession(sIssuer);

        ISessionAttributes sessionAttributes = session.getAttributes();
        sessionAttributes.put(this.getClass(), SESSION_REQUEST_ID, sInReponseTo);
        sessionAttributes.put(this.getClass(), SESSION_REQUEST_PROTOCOLBINDING, sBinding);

        String sRelayState = context.getRelayState();
        if (sRelayState != null)
            sessionAttributes.put(this.getClass(), SESSION_REQUEST_RELAYSTATE, sRelayState);

        session.persist();//this generates the session ID

        StringBuffer sbProfileURL = new StringBuffer();
        sbProfileURL.append(_sProfileURL);
        sbProfileURL.append("?");
        sbProfileURL.append(ISession.ID_NAME);
        sbProfileURL.append("=");
        sbProfileURL.append(session.getId());
        session.setProfileURL(sbProfileURL.toString());

        servletRequest.setAttribute(ISession.ID_NAME, session);

        StringBuffer sbForward = new StringBuffer(_sWebSSOPath);
        if (!_sWebSSOPath.endsWith("/"))
            sbForward.append("/");
        sbForward.append(SSO_LOGOUT_URI);

        _logger.debug("Forwarding user to: " + sbForward.toString());

        RequestDispatcher oDispatcher = servletRequest.getRequestDispatcher(sbForward.toString());
        if (oDispatcher == null) {
            _logger.warn("There is no requestor dispatcher supported with name: " + sbForward.toString());
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        _eventLogger.info(new UserEventLogItem(session, servletRequest.getRemoteAddr(),
                UserEvent.USER_LOGOUT_IN_PROGRESS, this, null));
        try {
            oDispatcher.forward(servletRequest, servletResponse);
        } catch (Exception e) {
            _logger.fatal("Could not forward user", e);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    }
}

From source file:com.squid.kraken.v4.auth.OAuth2LoginServlet.java

/**
 * Display the login screen.//w w  w  .  j a v  a 2 s  . c o m
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void showLogin(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher rd;

    String redirectUri = request.getParameter(REDIRECT_URI);
    String clientId = request.getParameter(CLIENT_ID);
    if (redirectUri == null) {
        request.setAttribute(ERROR, "Invalid request : redirect_uri must be provided");
        rd = getServletContext().getRequestDispatcher(ERROR_JSP);
    } else if (clientId == null) {
        request.setAttribute(ERROR, "Invalid request : client_id must be provided");
        rd = getServletContext().getRequestDispatcher(ERROR_JSP);
    } else {
        request.setAttribute(CUSTOMER_ID, request.getParameter(CUSTOMER_ID));
        request.setAttribute(REDIRECT_URI, redirectUri);
        request.setAttribute(RESPONSE_TYPE, request.getParameter(RESPONSE_TYPE));
        request.setAttribute(CLIENT_ID, clientId);

        rd = getServletContext().getRequestDispatcher(LOGIN_JSP);
    }
    rd.forward(request, response);
}

From source file:com.alfaariss.oa.sso.web.profile.web.WebProfile.java

private void handleStartPage(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws SSOException, IOException, ServletException {
    try {//from  w w w  .j av a  2s. c  om
        String sServletPath = oRequest.getServletPath();
        StringBuffer sbServletPath = new StringBuffer(sServletPath);
        if (!sServletPath.endsWith("/"))
            sbServletPath.append("/");
        sbServletPath.append(UserProfile.PROFILE_ID);

        RequestDispatcher oDispatcher = oRequest.getRequestDispatcher(sbServletPath.toString());
        if (oDispatcher != null)
            oDispatcher.forward(oRequest, oResponse);
        else {
            _systemLogger.fatal("Forward request not supported: " + sbServletPath.toString());
            throw new SSOException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (SSOException e) {
        throw e;
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaIngestController.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTION)) {
        return;/*ww w.  j  a  va 2  s .c  o  m*/
    }

    VitroRequest vreq = new VitroRequest(request);
    ModelMaker maker = getModelMaker(vreq);
    WhichService modelType = getModelType(vreq);

    String actionStr = vreq.getParameter("action");
    actionStr = (actionStr != null) ? actionStr : "";

    if ("listModels".equals(actionStr)) {
        processListModelsRequest(vreq, maker, modelType);
    } else if ("configModels".equals(actionStr)) {
        processConfigModelsRequest(vreq);
    } else if ("contentModels".equals(actionStr)) {
        processContentModelsRequest(vreq);
    } else if ("createModel".equals(actionStr)) {
        processCreateModelRequest(vreq, maker, modelType);
    } else if ("removeModel".equals(actionStr)) {
        processRemoveModelRequest(vreq, maker, modelType);
    } else if ("loadRDFData".equals(actionStr)) {
        processLoadRDFDataRequest(vreq, maker);
    } else if ("cleanLiterals".equals(actionStr)) {
        processCleanLiteralsRequest(vreq);
    } else if ("outputModel".equals(actionStr)) {
        processOutputModelRequest(vreq, response);
        return; // don't attempt to display a JSP
    } else if ("clearModel".equals(actionStr)) {
        processClearModelRequest(vreq, maker, modelType);
    } else if ("attachModel".equals(actionStr)) {
        processAttachModelRequest(vreq, maker, modelType);
    } else if ("detachModel".equals(actionStr)) {
        processDetachModelRequest(vreq, maker, modelType);
    } else if ("renameBNodes".equals(actionStr)) {
        processRenameBNodesRequest(vreq, maker);
    } else if ("renameBNodesURISelect".equals(actionStr)) {
        processRenameBNodesURISelectRequest(vreq, maker);
    } else if ("smushSingleModel".equals(actionStr)) {
        processSmushSingleModelRequest(vreq);
    } else if ("csv2rdf".equals(actionStr)) {
        processCsv2rdfRequest(vreq);
    } else if ("processStrings".equals(actionStr)) {
        processProcessStringsRequest(vreq);
    } else if ("splitPropertyValues".equals(actionStr)) {
        processSplitPropertyValuesRequest(vreq);
    } else if ("subtractModels".equals(actionStr)) {
        processSubtractModelRequest(vreq);
    } else if ("executeWorkflow".equals(actionStr)) {
        processExecuteWorkflowRequest(vreq);
    } else if ("executeSparql".equals(actionStr)) {
        processExecuteSparqlRequest(vreq);
    } else if ("generateTBox".equals(actionStr)) {
        processGenerateTBoxRequest(vreq);
    } else if ("permanentURI".equals(actionStr)) {
        processPermanentURIRequest(vreq, maker);
    } else if ("mergeResources".equals(actionStr)) {
        processMergeResourceRequest(vreq);
    } else if ("renameResource".equals(actionStr)) {
        processRenameResourceRequest(vreq);
    } else if ("mergeResult".equals(actionStr)) {
        processMergeResultRequest(vreq, response);
        return;
    } else if ("dumpRestore".equals(actionStr)) {
        processDumpRestore(vreq, response);
        return;
    }

    else {
        request.setAttribute("title", "Ingest Menu");
        request.setAttribute("bodyJsp", INGEST_MENU_JSP);
    }

    maker = getModelMaker(vreq);
    request.setAttribute("modelNames", maker.listModels().toList());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error(e, e);
        throw new ServletException(e);
    }

}

From source file:com.alfaariss.oa.profile.aselect.processor.handler.BrowserHandler.java

/**
 * Processes the <code>request=login1</code> request.
 *
 * The request parameters that are supported:
 * <table border='1'>/*from   w w w  .  j a v  a2 s  .  co  m*/
 * <tr><th><i>parameter</i></th><th><i>value</i></th><th><i>optional?</i></th></tr>
 * <tr><td>request</td><td>login1</td><td>false</td></tr>
 * <tr><td>rid</td><td>[rid]</td><td>false</td></tr>
 * <tr><td>a-select-server</td><td>[a-select-server]</td><td>false</td></tr>
 * </table>
 * <br>
 * @param oServletRequest HTTP servlet request object
 * @param oServletResponse HTTP servlet response object
 * @param oBinding The binding object
 * @throws ASelectException if request handling failed
 */
public void login1(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse, IBinding oBinding)
        throws ASelectException {
    ISession oSession = null;
    try {
        IRequest oRequest = oBinding.getRequest();

        String sASelectServer = (String) oRequest.getParameter(ASelectProcessor.PARAM_ASELECTSERVER);
        if (sASelectServer == null) {
            StringBuffer sbError = new StringBuffer("No '");
            sbError.append(ASelectProcessor.PARAM_ASELECTSERVER);
            sbError.append("' found in request");
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        String sRID = (String) oRequest.getParameter(ASelectProcessor.PARAM_RID);
        if (sRID == null) {
            StringBuffer sbError = new StringBuffer("No '");
            sbError.append(ASelectProcessor.PARAM_RID);
            sbError.append("' found in request");
            _logger.debug(sbError.toString());

            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        if (!SessionValidator.validateDefaultSessionId(sRID)) {
            StringBuffer sbError = new StringBuffer("Invalid '");
            sbError.append(ASelectProcessor.PARAM_RID);
            sbError.append("' in request: ");
            sbError.append(sRID);
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        if (!_server.getID().equals(sASelectServer)) {
            StringBuffer sbError = new StringBuffer("The Server ID doesn't correspond to the supplied '");
            sbError.append(ASelectProcessor.PARAM_ASELECTSERVER);
            sbError.append("' parameter: ");
            sbError.append(sASelectServer);
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_ID_MISMATCH);
        }

        oSession = _sessionFactory.retrieve(sRID);
        if (oSession == null) {
            _logger.debug("No session found with id: " + sRID);
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        if (oSession.isExpired()) {
            StringBuffer sbError = new StringBuffer("Expired session with id '");
            sbError.append(sRID);
            sbError.append("' found in request sent from IP: ");
            sbError.append(oServletRequest.getRemoteAddr());
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_SESSION_EXPIRED);
        }

        StringBuffer sbProfileURL = new StringBuffer();
        if (_sRedirectURL == null)
            sbProfileURL.append(oRequest.getRequestedURL());
        else
            sbProfileURL.append(_sRedirectURL);
        sbProfileURL.append("?");
        sbProfileURL.append(ASelectProcessor.PARAM_ASELECTSERVER);
        sbProfileURL.append("=");
        sbProfileURL.append(URLEncoder.encode(_server.getID(), ASelectProcessor.CHARSET));
        sbProfileURL.append("&");
        sbProfileURL.append(ASelectProcessor.PARAM_RID);
        sbProfileURL.append("=");
        sbProfileURL.append(URLEncoder.encode(sRID, ASelectProcessor.CHARSET));
        oSession.setProfileURL(sbProfileURL.toString());

        oServletRequest.setAttribute(ISession.ID_NAME, oSession);

        RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(_sWebSSOPath);
        if (oDispatcher == null) {
            _logger.warn("There is no requestor dispatcher supported with name: " + _sWebSSOPath);
            throw new ASelectUserException(UserEvent.INTERNAL_ERROR,
                    ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
        }

        oDispatcher.forward(oServletRequest, oServletResponse);
    } catch (ASelectUserException e) {
        UserEvent event = e.getEvent();
        String sCode = e.getMessage();
        if (oSession != null)
            _eventLogger
                    .info(new UserEventLogItem(oSession, oServletRequest.getRemoteAddr(), event, this, sCode));
        else
            _eventLogger.info(new UserEventLogItem(null, null, null, event, null,
                    oServletRequest.getRemoteAddr(), null, this, sCode));

        showErrorPage(oServletRequest, oServletResponse, event, sCode, oSession);
    } catch (OAException e) {
        _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                oServletRequest.getRemoteAddr(), null, this, e.getMessage()));

        _logger.error("Exception occurred during 'login1' process", e);
        throw new ASelectException(e.getMessage());
    } catch (Exception e) {
        if (oSession != null)
            _eventLogger.info(new RequestorEventLogItem(oSession, oServletRequest.getRemoteAddr(),
                    RequestorEvent.INTERNAL_ERROR, this, null));
        else
            _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null,
                    oServletRequest.getRemoteAddr(), null, this, null));

        _logger.fatal("Internal error during 'login1' process", e);
        throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
    }
}

From source file:org.deegree.test.gui.StressTestController.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///  w  ww  .java 2  s. c  o  m
@Override
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String action = request.getParameter("action");
    String step1 = request.getParameter("step1");
    String step2 = request.getParameter("step2");
    String step3 = request.getParameter("step3");

    String imageSource = request.getParameter("imgsrc");
    String bigimg = request.getParameter("bigimg");
    String shot = request.getParameter("shot");
    String bigshot = request.getParameter("bigshot");

    if (action != null && action.equalsIgnoreCase("status")) {
        String state = (String) request.getSession().getAttribute("applicationState");

        if (state != null && state.equalsIgnoreCase("wait")) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/status.jsp");

            HttpSession session = request.getSession();
            String appState = (String) session.getAttribute("applicationState");
            request.setAttribute("applicationState", appState);
            if (appState.equals("wait")) {
                String operation = (String) session.getAttribute("operationInProgress");
                request.setAttribute("opeartionInProgress", operation);
            }

            List<TestResultData> partialRes = test.getResultData();
            request.setAttribute("partialResults", partialRes);

            request.setAttribute("threads", threads);
            request.setAttribute("requests", requests);

            dispatcher.forward(request, response);

        } else if (state != null && state.equalsIgnoreCase("ready")) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/status.jsp");

            HttpSession session = request.getSession();

            request.setAttribute("applicationState", "ready");

            resultData = (List<TestResultData>) session.getAttribute("resultData");
            request.setAttribute("resultData", resultData);

            imgLinks = (List<String>) session.getAttribute("imgLinks");
            request.setAttribute("imgLinks", imgLinks);

            showImg = (Boolean) session.getAttribute("showImage");
            request.setAttribute("showImage", showImg);

            request.setAttribute("threads", threads);
            request.setAttribute("requests", requests);

            dispatcher.forward(request, response);

        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/status.jsp");
            request.setAttribute("applicationState", "welcome");
            dispatcher.forward(request, response);
        }

    } else if (action != null && action.equalsIgnoreCase("wpvs")) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/wpvs.jsp");
        dispatcher.forward(request, response);

    } else if (action != null && action.equalsIgnoreCase("wms")) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/wms.jsp");
        dispatcher.forward(request, response);

    } else if (step1 != null) {

        doStep1(request, response);

    } else if (step2 != null) {

        doStep2(request, response);

    } else if (step3 != null) {

        doStep3(request, response);

    } else if (imageSource != null) {

        drawDiagram(response, 400, 300);

    } else if (bigimg != null) {

        drawDiagram(response, 1000, 750);

    } else if (shot != null) {

        renderResizedImage(response, shot, 200, 150);

    } else if (bigshot != null) {

        renderImage(response, bigshot);
    }

}

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

/**
 * <p>Do a forward to specified URI using a <code>RequestDispatcher</code>.
 * This method is used by all internal method needing to do a
 * forward.</p>/* ww w  .j a  v  a  2 s . c  o  m*/
 *
 * @param uri      Context-relative URI to forward to
 * @param request  Current page request
 * @param response Current page response
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet exception occurs
 * @since Struts 1.1
 */
protected void doForward(String uri, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);

    if (rd == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                getInternal().getMessage("requestDispatcher", uri));

        return;
    }

    rd.forward(request, response);
}

From source file:com.fluidops.iwb.server.SparqlServlet.java

/**
 * Handles the forward to the {@link HybridSearchServlet} by performing a redirect or a forward.
 * A redirect is performed if the content length of the request is smaller than Jetty's buffer
 * limit, otherwise the request is directly forwarded.
 * // ww  w .ja v a2s  .  co  m
 * All parameters are passed to the {@link HybridSearchServlet} as part of the request. Note
 * that the "repository" parameter is in addition mapped to "queryTarget".
 * 
 * Note that certain request parameters as defined in {@link #requestParamIgnoreKeys} are
 * not forwarded.
 * 
 * @param req
 * @param resp
 * @throws IOException
 */
protected void handleForward(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // determine the query target (used for repository manager)
    String repositoryID = req.getParameter("repository");
    String queryTarget;
    if (StringUtil.isNotNullNorEmpty(repositoryID))
        queryTarget = StringUtil.urlEncode(repositoryID);
    else
        queryTarget = "RDF";

    // Apparently, the jetty limit on request header buffer size is 6144, which is filled by (contentLength*2 + something else).
    // Content length 2965 was sufficient for the query to pass.
    // Moved the threshold down in case if additional properties are to be passed (e.g., multiple query targets).
    if (req.getContentLength() < 2800) {

        StringBuilder forwardedParams = new StringBuilder();
        /*
         * Sanitize the request parameters before redirect to
         * prevent HTTP response splitting vulnerabilities
         * 
         * @see http://de.wikipedia.org/wiki/HTTP_Response_Splitting
         */
        for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
            if (requestParamIgnoreKeys.contains(entry.getKey()))
                continue;
            for (String value : entry.getValue()) {
                forwardedParams.append(String.format("&%s=%s", entry.getKey(), StringUtil.urlEncode(value)));
            }
        }
        String location = req.getContextPath() + "/search/?queryLanguage=SPARQL&queryTarget=" + queryTarget
                + forwardedParams.toString();

        resp.sendRedirect(location);
    } else {

        RequestDispatcher dispatcher = req
                .getRequestDispatcher("/search/?queryLanguage=SPARQL&queryTarget=" + queryTarget);
        try {
            dispatcher.forward(req, resp);
        } catch (ServletException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not forward request to search servlet.");
        }
    }
}

From source file:com.alfaariss.oa.profile.aselect.processor.handler.BrowserHandler.java

/**
 * Process asynchronous logout results.// www  .j  a  v a2s.c om
 *
 * @param oServletRequest HTTP servlet request object
 * @param oServletResponse HTTP servlet response object
 * @param oBinding The binding object
 * @throws ASelectException if request handling failed
 * @since 1.4
 */
public void logout(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse, IBinding oBinding)
        throws ASelectException {
    ISession session = null;
    try {
        IRequest oRequest = oBinding.getRequest();

        String sASelectServer = (String) oRequest.getParameter(ASelectProcessor.PARAM_ASELECTSERVER);
        if (sASelectServer == null) {
            StringBuffer sbError = new StringBuffer("No '");
            sbError.append(ASelectProcessor.PARAM_ASELECTSERVER);
            sbError.append("' found in request");
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        String sRID = (String) oRequest.getParameter(ASelectProcessor.PARAM_RID);
        if (sRID == null) {
            StringBuffer sbError = new StringBuffer("No '");
            sbError.append(ASelectProcessor.PARAM_RID);
            sbError.append("' found in request");
            _logger.debug(sbError.toString());

            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        if (!SessionValidator.validateDefaultSessionId(sRID)) {
            StringBuffer sbError = new StringBuffer("Invalid '");
            sbError.append(ASelectProcessor.PARAM_RID);
            sbError.append("' in request: ");
            sbError.append(sRID);
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        if (!_server.getID().equals(sASelectServer)) {
            StringBuffer sbError = new StringBuffer("The Server ID doesn't correspond to the supplied '");
            sbError.append(ASelectProcessor.PARAM_ASELECTSERVER);
            sbError.append("' parameter: ");
            sbError.append(sASelectServer);
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_ID_MISMATCH);
        }

        session = _sessionFactory.retrieve(sRID);
        if (session == null) {
            _logger.debug("No session found with id: " + sRID);
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        if (session.isExpired()) {
            StringBuffer sbError = new StringBuffer("Expired session with id '");
            sbError.append(sRID);
            sbError.append("' found in request sent from IP: ");
            sbError.append(oServletRequest.getRemoteAddr());
            _logger.debug(sbError.toString());
            throw new ASelectUserException(UserEvent.REQUEST_INVALID,
                    ASelectErrors.ERROR_ASELECT_SERVER_SESSION_EXPIRED);
        }

        switch (session.getState()) {
        case USER_LOGOUT_SUCCESS: {
            String sRequestorURL = (String) session.getAttributes().get(ASelectProcessor.class,
                    ASelectProcessor.SESSION_REQUESTOR_URL);

            _eventLogger.info(new UserEventLogItem(session, oServletRequest.getRemoteAddr(),
                    UserEvent.USER_LOGGED_OUT, this, null));

            _logger.debug("Logout succeeded, redirect user back to requestor: " + sRequestorURL);

            oServletResponse.sendRedirect(sRequestorURL);
            break;
        }
        case USER_LOGOUT_PARTIAL:
        case USER_LOGOUT_FAILED: {
            throw new ASelectUserException(UserEvent.USER_LOGOUT_FAILED, ASelectErrors.ERROR_LOGOUT_FAILED);
        }
        case USER_LOGOUT_IN_PROGRESS: {
            oServletRequest.setAttribute(ISession.ID_NAME, session);

            StringBuffer sbForward = new StringBuffer(_sWebSSOPath);
            if (!_sWebSSOPath.endsWith("/"))
                sbForward.append("/");
            sbForward.append(SSO_LOGOUT_URI);

            _logger.debug("Forwarding user to: " + sbForward.toString());

            RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(sbForward.toString());
            if (oDispatcher == null) {
                _logger.warn("There is no requestor dispatcher supported with name: " + sbForward.toString());
                throw new ASelectUserException(UserEvent.INTERNAL_ERROR,
                        ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
            }

            oDispatcher.forward(oServletRequest, oServletResponse);
            break;
        }
        default: {//forward user to start logout process

            StringBuffer sbProfileURL = new StringBuffer();
            if (_sRedirectURL == null)
                sbProfileURL.append(oRequest.getRequestedURL());
            else
                sbProfileURL.append(_sRedirectURL);

            sbProfileURL.append("?request=logout&");
            sbProfileURL.append(ASelectProcessor.PARAM_ASELECTSERVER);
            sbProfileURL.append("=");
            sbProfileURL.append(URLEncoder.encode(_server.getID(), ASelectProcessor.CHARSET));
            sbProfileURL.append("&");
            sbProfileURL.append(ASelectProcessor.PARAM_RID);
            sbProfileURL.append("=");
            sbProfileURL.append(URLEncoder.encode(sRID, ASelectProcessor.CHARSET));
            session.setProfileURL(sbProfileURL.toString());

            oServletRequest.setAttribute(ISession.ID_NAME, session);

            StringBuffer sbForward = new StringBuffer(_sWebSSOPath);
            if (!_sWebSSOPath.endsWith("/"))
                sbForward.append("/");
            sbForward.append(SSO_LOGOUT_URI);

            _logger.debug("Forwarding user to: " + sbForward.toString());

            RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(sbForward.toString());
            if (oDispatcher == null) {
                _logger.warn("There is no requestor dispatcher supported with name: " + sbForward.toString());
                throw new ASelectUserException(UserEvent.INTERNAL_ERROR,
                        ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
            }

            _eventLogger.info(new UserEventLogItem(session, oServletRequest.getRemoteAddr(),
                    UserEvent.USER_LOGOUT_IN_PROGRESS, this, null));

            oDispatcher.forward(oServletRequest, oServletResponse);
        }
        }
    } catch (ASelectUserException e) {
        UserEvent event = e.getEvent();
        String sCode = e.getMessage();
        if (session != null)
            _eventLogger
                    .info(new UserEventLogItem(session, oServletRequest.getRemoteAddr(), event, this, sCode));
        else
            _eventLogger.info(new UserEventLogItem(null, null, null, event, null,
                    oServletRequest.getRemoteAddr(), null, this, sCode));

        showErrorPage(oServletRequest, oServletResponse, event, sCode, session);
    } catch (OAException e) {
        _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                oServletRequest.getRemoteAddr(), null, this, e.getMessage()));

        _logger.error("Exception occurred during 'logout' process", e);
        throw new ASelectException(e.getMessage());
    } catch (Exception e) {
        _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                oServletRequest.getRemoteAddr(), null, this, "logout"));

        _logger.fatal("Internal error during logout request process", e);
        throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
    }
}

From source file:com.alfaariss.oa.profile.aselect.processor.handler.BrowserHandler.java

/**
 * Handle the redirect sent by the application to show the user information page.
 * <br>//  ww w . j a  v  a 2s  . co  m
 * Redirects the user to the WebSSO.
 * @param oServletRequest HTTP servlet request object
 * @param oServletResponse HTTP servlet response object
 * @throws ASelectException if request handling failed
 */
public void userinformation(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse)
        throws ASelectException {
    try {
        if (_sWebSSOUrl != null) {
            _logger.debug("Redirect to web sso: " + _sWebSSOUrl);
            try {
                oServletResponse.sendRedirect(_sWebSSOUrl);
            } catch (Exception e) {
                _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                        oServletRequest.getRemoteAddr(), null, this, "user information"));

                _logger.fatal("Internal error during user information request process", e);
                throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
            }
        } else {
            _logger.debug("Forward to web sso: " + _sWebSSOPath);
            RequestDispatcher oDispatcher = oServletRequest.getRequestDispatcher(_sWebSSOPath);
            if (oDispatcher == null) {
                _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                        oServletRequest.getRemoteAddr(), null, this, "user information"));

                _logger.warn("There is no requestor dispatcher supported with name: " + _sWebSSOPath);
                throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
            }

            oDispatcher.forward(oServletRequest, oServletResponse);
        }
    } catch (ASelectException e) {
        throw e;
    } catch (Exception e) {
        _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                oServletRequest.getRemoteAddr(), null, this, "user information"));

        _logger.fatal("Internal error during user information request process", e);
        throw new ASelectException(ASelectErrors.ERROR_ASELECT_INTERNAL_ERROR);
    }
}