Example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdFromUrl

List of usage examples for javax.servlet.http HttpServletRequest isRequestedSessionIdFromUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdFromUrl.

Prototype

@Deprecated
public boolean isRequestedSessionIdFromUrl();

Source Link

Usage

From source file:eu.eidas.node.service.ColleagueRequestServlet.java

/**
 * Post method//from www . ja va2 s  .  c  om
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PropertiesUtil.checkProxyServiceActive();
    // Obtaining the assertion consumer url from SPRING context
    ServiceControllerService controllerService = (ServiceControllerService) getApplicationContext()
            .getBean(NodeBeanNames.EIDAS_SERVICE_CONTROLLER.toString());

    CorrelationMap<StoredAuthenticationRequest> requestCorrelationMap = controllerService
            .getProxyServiceRequestCorrelationMap();

    // Prevent cookies from being accessed through client-side script WITHOUT renew of session.
    setHTTPOnlyHeaderToSession(false, request, response);
    SessionHolder.setId(request.getSession());
    request.getSession().setAttribute(EidasParameterKeys.SAML_PHASE.toString(),
            EIDASValues.EIDAS_SERVICE_REQUEST);

    // Obtains the parameters from httpRequest
    WebRequest webRequest = new IncomingRequest(request);

    // Validating the only HTTP parameter: SAMLRequest.
    String samlRequest = webRequest.getEncodedLastParameterValue(EidasParameterKeys.SAML_REQUEST);
    NodeParameterValidator.paramName(EidasParameterKeys.SAML_REQUEST).paramValue(samlRequest)
            .eidasError(EidasErrorKey.COLLEAGUE_REQ_INVALID_SAML).validate();

    // Storing the Remote Address and Host for auditing proposes.
    String remoteIpAddress = webRequest.getRemoteIpAddress();

    // Validating the optional HTTP Parameter relayState.
    String relayState = webRequest.getEncodedLastParameterValue(NodeParameterNames.RELAY_STATE.toString());
    LOG.debug("Saving ProxyService relay state. " + relayState);

    // Obtaining the authData
    IAuthenticationRequest authData = controllerService.getProxyService()
            .processAuthenticationRequest(webRequest, relayState, requestCorrelationMap, remoteIpAddress);
    if (StringUtils.isNotBlank(relayState)) { // RelayState's HTTP Parameter is optional!
        NodeParameterValidator.paramName(NodeParameterNames.RELAY_STATE).paramValue(relayState)
                .eidasError(EidasErrorKey.SPROVIDER_SELECTOR_INVALID_RELAY_STATE).validate();
    }
    // Validating the personal attribute list
    IPersonalAttributeList persAttrList = PersonalAttributeList.copyOf(authData.getRequestedAttributes());
    List<PersonalAttribute> attrList = new ArrayList<PersonalAttribute>();

    boolean hasEidasAttributes = !Sets.intersection(EidasSpec.REGISTRY.getAttributes(),
            authData.getRequestedAttributes().getDefinitions()).isEmpty();
    //ImmutablePersonalAttributeSet
    for (PersonalAttribute pa : persAttrList) {
        attrList.add(pa);
    }
    String redirectUrl = authData.getAssertionConsumerServiceURL();
    LOG.debug("RedirectUrl: " + redirectUrl);
    // Validating the citizenConsentUrl
    NodeParameterValidator.paramName(EidasParameterKeys.EIDAS_SERVICE_REDIRECT_URL)
            .paramValue(controllerService.getCitizenConsentUrl())
            .eidasError(EidasErrorKey.COLLEAGUE_REQ_INVALID_DEST_URL).validate();
    LOG.debug("sessionId is on cookies () or fromURL ", request.isRequestedSessionIdFromCookie(),
            request.isRequestedSessionIdFromURL());

    request.setAttribute(NodeParameterNames.SAML_TOKEN_FAIL.toString(),
            controllerService.getProxyService().generateSamlTokenFail(authData,
                    EIDASStatusCode.REQUESTER_URI.toString(), EidasErrorKey.CITIZEN_RESPONSE_MANDATORY,
                    remoteIpAddress));

    request.setAttribute(EidasParameterKeys.SP_ID.toString(), authData.getProviderName());
    if (authData instanceof IStorkAuthenticationRequest) {
        request.setAttribute(NodeParameterNames.QAA_LEVEL.toString(),
                ((IStorkAuthenticationRequest) authData).getQaa());
    }

    request.setAttribute(NodeParameterNames.LOA_VALUE.toString(),
            EidasAttributesUtil.getUserFriendlyLoa(authData.getLevelOfAssurance()));
    request.setAttribute(NodeParameterNames.CITIZEN_CONSENT_URL.toString(),
            encodeURL(controllerService.getCitizenConsentUrl(), response)); // Correct URl redirect cookie implementation
    request.setAttribute(NodeParameterNames.ATTR_LIST.toString(), attrList);
    request.setAttribute(NodeParameterNames.REDIRECT_URL.toString(), encodeURL(redirectUrl, response));// Correct URl redirect cookie implementation
    request.setAttribute(NodeParameterNames.EIDAS_ATTRIBUTES_PARAM.toString(),
            Boolean.valueOf(hasEidasAttributes));

    request.setAttribute(NodeParameterNames.REQUEST_ID.toString(), authData.getId());
    request.setAttribute(NodeParameterNames.COLLEAGUE_REQUEST.toString(), authData);

    NodeViewNames forwardUrl;
    if (controllerService.isAskConsentType()) {
        forwardUrl = NodeViewNames.EIDAS_SERVICE_PRESENT_CONSENT;
    } else {
        forwardUrl = NodeViewNames.EIDAS_SERVICE_NO_CONSENT;
    }
    RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl.toString());
    dispatcher.forward(request, response);
}

From source file:com.cws.esolutions.security.filters.SessionAuthenticationFilter.java

public void doFilter(final ServletRequest sRequest, final ServletResponse sResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    final String methodName = SessionAuthenticationFilter.CNAME
            + "#doFilter(final ServletRequest sRequest, final ServletResponse sResponse, final FilterChain filterChain) throws IOException, ServletException";

    if (DEBUG) {// w  w w . ja  v  a2  s .com
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletRequest: {}", sRequest);
        DEBUGGER.debug("ServletResponse: {}", sResponse);
    }

    final HttpServletRequest hRequest = (HttpServletRequest) sRequest;
    final HttpServletResponse hResponse = (HttpServletResponse) sResponse;
    final HttpSession hSession = hRequest.getSession(false);
    final String requestURI = hRequest.getRequestURI();
    final String passwdPage = hRequest.getContextPath() + this.passwordURI;
    final StringBuilder redirectPath = new StringBuilder().append(hRequest.getContextPath() + this.loginURI)
            .append("?vpath=" + requestURI);

    if (DEBUG) {
        DEBUGGER.debug("HttpServletRequest: {}", hRequest);
        DEBUGGER.debug("HttpServletResponse: {}", hResponse);
        DEBUGGER.debug("HttpSession: {}", hSession);
        DEBUGGER.debug("RequestURI: {}", requestURI);
        DEBUGGER.debug("passwdPage: {}", passwdPage);
        DEBUGGER.debug("redirectPath: {}", redirectPath);

        DEBUGGER.debug("Dumping session content:");
        Enumeration<?> sessionEnumeration = hSession.getAttributeNames();

        while (sessionEnumeration.hasMoreElements()) {
            String element = (String) sessionEnumeration.nextElement();
            Object value = hSession.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request content:");
        Enumeration<?> requestEnumeration = hRequest.getAttributeNames();

        while (requestEnumeration.hasMoreElements()) {
            String element = (String) requestEnumeration.nextElement();
            Object value = hRequest.getAttribute(element);

            DEBUGGER.debug("Attribute: {}; Value: {}", element, value);
        }

        DEBUGGER.debug("Dumping request parameters:");
        Enumeration<?> paramsEnumeration = hRequest.getParameterNames();

        while (paramsEnumeration.hasMoreElements()) {
            String element = (String) paramsEnumeration.nextElement();
            Object value = hRequest.getParameter(element);

            DEBUGGER.debug("Parameter: {}; Value: {}", element, value);
        }
    }

    if (StringUtils.equals(this.loginURI, requestURI)) {
        if (DEBUG) {
            DEBUGGER.debug("Request authenticated. No action taken !");
        }

        filterChain.doFilter(sRequest, sResponse);

        return;
    }

    if ((this.ignoreURIs != null) && (this.ignoreURIs.length != 0)) {
        if (Arrays.asList(this.ignoreURIs).contains("ALL")) {
            if (DEBUG) {
                DEBUGGER.debug("ALL URIs are ignored. Breaking ...");
            }

            filterChain.doFilter(sRequest, sResponse);

            return;
        }

        // hostname isnt in ignore list
        for (String uri : this.ignoreURIs) {
            uri = hRequest.getContextPath().trim() + uri.trim();

            if (DEBUG) {
                DEBUGGER.debug(uri);
                DEBUGGER.debug(requestURI);
            }

            if (StringUtils.contains(requestURI, uri)) {
                // ignore
                if (DEBUG) {
                    DEBUGGER.debug("URI matched to ignore list - breaking out");
                }

                filterChain.doFilter(sRequest, sResponse);

                return;
            }
        }
    }

    if (hRequest.isRequestedSessionIdFromURL()) {
        ERROR_RECORDER.error("Session found is from URL. Redirecting request to " + hRequest.getContextPath()
                + this.loginURI);

        // invalidate the session
        hRequest.getSession(false).invalidate();
        hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT);
        hSession.invalidate();

        hResponse.sendRedirect(hRequest.getContextPath() + this.loginURI);

        return;
    }

    Enumeration<?> sessionAttributes = hSession.getAttributeNames();

    if (DEBUG) {
        DEBUGGER.debug("Enumeration<String>: {}", sessionAttributes);
    }

    while (sessionAttributes.hasMoreElements()) {
        String element = (String) sessionAttributes.nextElement();

        if (DEBUG) {
            DEBUGGER.debug("element: {}", element);
        }

        Object value = hSession.getAttribute(element);

        if (DEBUG) {
            DEBUGGER.debug("sessionValue: {}", value);
        }

        if (value instanceof UserAccount) {
            UserAccount userAccount = (UserAccount) value;

            if (DEBUG) {
                DEBUGGER.debug("UserAccount: {}", userAccount);
            }

            if (userAccount.getStatus() != null) {
                switch (userAccount.getStatus()) {
                case EXPIRED:
                    if ((!(StringUtils.equals(requestURI, passwdPage)))) {
                        ERROR_RECORDER.error(
                                "Account is expired and this request is not for the password page. Redirecting !");

                        hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI);

                        return;
                    }

                    filterChain.doFilter(sRequest, sResponse);

                    return;
                case RESET:
                    if ((!(StringUtils.equals(requestURI, passwdPage)))) {
                        ERROR_RECORDER.error(
                                "Account has status RESET and this request is not for the password page. Redirecting !");

                        hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI);

                        return;
                    }

                    filterChain.doFilter(sRequest, sResponse);

                    return;
                case SUCCESS:
                    filterChain.doFilter(sRequest, sResponse);

                    return;
                default:
                    break;
                }
            }
        }
    }

    // no user account in the session
    ERROR_RECORDER.error("Session contains no existing user account. Redirecting request to "
            + hRequest.getContextPath() + this.loginURI);

    // invalidate the session
    hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT);
    hSession.invalidate();

    if (StringUtils.isNotEmpty(hRequest.getQueryString())) {
        redirectPath.append("?" + hRequest.getQueryString());
    }

    if (DEBUG) {
        DEBUGGER.debug("redirectPath: {}", redirectPath.toString());
    }

    hResponse.sendRedirect(URLEncoder.encode(redirectPath.toString(), systemConfig.getEncoding()));

    return;
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//from ww w.  j  av  a  2s.co m
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:org.apache.catalina.realm.RealmBase.java

/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraint Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 *///  ww  w .j  a  v a 2 s .com
public boolean hasUserDataPermission(HttpRequest request, HttpResponse response,
        SecurityConstraint[] constraints) throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return (true);
    }
    for (int i = 0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return (true);
        }
        if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return (true);
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return (true);
    }
    // Initialize variables we need to determine the appropriate action
    HttpServletRequest hrequest = (HttpServletRequest) request.getRequest();
    HttpServletResponse hresponse = (HttpServletResponse) response.getResponse();
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        hresponse.sendError(HttpServletResponse.SC_FORBIDDEN, hrequest.getRequestURI());
        return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuffer file = new StringBuffer();
    String protocol = "https";
    String host = hrequest.getServerName();
    // Protocol
    file.append(protocol).append("://");
    // Host with port
    file.append(host).append(":").append(redirectPort);
    // URI
    file.append(hrequest.getRequestURI());
    String requestedSessionId = hrequest.getRequestedSessionId();
    if ((requestedSessionId != null) && hrequest.isRequestedSessionIdFromURL()) {
        file.append(";jsessionid=");
        file.append(requestedSessionId);
    }
    String queryString = hrequest.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    hresponse.sendRedirect(file.toString());
    return (false);

}

From source file:org.wings.session.PortletWingServlet.java

public final PortletSessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response,
        boolean createSessionServlet) throws ServletException {

    // WingS-Portlet-Bridge: for the bridge we are using the portletSession to
    // seperate between the instances of one portlet through the portlet scope
    RenderRequest renderRequest = (RenderRequest) request.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST);
    if (renderRequest == null) {
        log.error("WingS-Portlet-Bridge: cant get RenderRequest because " + "the request attribute "
                + Const.REQUEST_ATTR_RENDER_REQUEST + " is null!");
    }/*from  w ww.  ja  va 2s.c om*/
    final PortletSession portletSession = renderRequest.getPortletSession();

    // WingS-Portlet-Bridge: get the wings mainclass for current mode
    String lookupName = "SessionServlet";
    lookupName = "SessionServlet:" + (String) renderRequest.getAttribute(Const.REQUEST_ATTR_WINGS_CLASS);

    log.info("WingS-Portlet-Bridge: loaded mainclass " + lookupName
            + " for PortletSessionServlet identificaction");

    // it should be enough to synchronize on the http session object...
    synchronized (portletSession) {
        PortletSessionServlet sessionServlet = null;

        if (portletSession != null) {
            // WingS-Portlet-Bridge: changed for portlet scope
            sessionServlet = (PortletSessionServlet) portletSession.getAttribute(lookupName,
                    PortletSession.PORTLET_SCOPE);
        }

        // Sanity check - maybe this is a stored/deserialized session servlet?
        if (sessionServlet != null && !sessionServlet.isValid()) {
            sessionServlet.destroy();
            sessionServlet = null;
            log.debug("session servlet exists but is not valid");
        }

        /*
         * we are only interested in a new session, if the response is
         * not null. If it is null, then we just called getSessionServlet()
         * for lookup purposes and are satisfied, if we don't get anything.
         */
        if (sessionServlet == null) {
            if (createSessionServlet) {
                log.info("no session servlet, create new one");
                sessionServlet = newSession(request, response);
                portletSession.setAttribute(lookupName, sessionServlet, PortletSession.PORTLET_SCOPE);
            } else {
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder().append("session id: ")
                    .append(request.getRequestedSessionId()).append(", created at: ")
                    .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                            .format(new java.util.Date(portletSession.getCreationTime())))
                    .append(", identified via:")
                    .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "")
                    .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ")
                    .append(portletSession.getMaxInactiveInterval()).append("s ");
            log.debug(message.toString());
            //log.debug("session valid " + request.isRequestedSessionIdValid());
            //log.debug("session httpsession id " + httpSession.getId());
            //log.debug("session httpsession new " + httpSession.isNew());
            //log.debug("session last accessed at " +
            //        new java.util.Date(httpSession.getLastAccessedTime()));
            //log.debug("session expiration timeout (s) " +
            //        httpSession.getMaxInactiveInterval());
            //log.debug("session contains wings session " +
            //        (httpSession.getAttribute(lookupName) != null));
        }

        sessionServlet.getSession().getExternalizeManager().setResponse(response);

        /* Handling of the requests character encoding.
         * --------------------------------------------
         * The following block is needed for a correct handling of
         * non-ISO-8859-1 data:
         *
         * Using LocaleCharacterSet and/or charset.properties we can
         * advise the client to use i.e. UTF-8 as character encoding.
         * Once told the browser consequently also encodes his requests
         * in the choosen characterset of the sings session. This is
         * achieved by adding the HTML code
         * <meta http-equiv="Content-Type" content="text/html;charset="<charset>">
         * to the generated pages.
         *
         * If the user hasn't overridden the encoding in their browser,
         * then all form data (e.g. mueller) is submitted with data encoded
         * like m%C3%BCller because byte pair C3 BC is how the german
         * u-umlaut is represented in UTF-8. If the form is
         * iso-8859-1 encoded then you get m%FCller, because byte FC is
         * how it is presented in iso-8859-1.
         *
         * So the browser behaves correctly by sending his form input
         * correctly encoded in the advised character encoding. The issue
         * is that the servlet container is typically unable to determine
         * the correct encoding of this form data. By proposal the browser
         * should als declare the used character encoding for his data.
         * But actual browsers omit this information and hence the servlet
         * container is unable to guess the right encoding (Tomcat actually
         * thenalways guesses ISO 8859-1). This results in totally
         * scrumbled up data for all non ISO-8859-1 character encodings.
         * With the block below we tell the servlet container about the
         * character encoding we expect in the browsers request and hence
         * the servlet container can do the correct decoding.
         * This has to be done at very first, otherwise the servlet
         * container will ignore this setting.
         */
        if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding?
            try {
                String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding();
                // We know better about the used character encoding than tomcat
                log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding);
                request.setCharacterEncoding(sessionCharacterEncoding);
            } catch (UnsupportedEncodingException e) {
                log.warn("Problem on applying current session character encoding", e);
            }
        }

        return sessionServlet;
    }
}

From source file:org.wings.session.WingServlet.java

public final SessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response,
        boolean createSessionServlet) throws ServletException {
    final HttpSession httpSession = request.getSession(true);

    // it should be enough to synchronize on the http session object...
    synchronized (httpSession) {
        SessionServlet sessionServlet = null;

        if (httpSession != null) {
            sessionServlet = (SessionServlet) httpSession.getAttribute(lookupName);
        }//from w w  w. ja va 2 s  . c o m

        // Sanity check - maybe this is a stored/deserialized session servlet?
        if (sessionServlet != null && !sessionServlet.isValid()) {
            sessionServlet.destroy();
            sessionServlet = null;
        }

        /*
         * we are only interested in a new session, if the response is
         * not null. If it is null, then we just called getSessionServlet()
         * for lookup purposes and are satisfied, if we don't get anything.
         */
        if (sessionServlet == null) {
            if (createSessionServlet) {
                log.info("no session servlet, create new one");
                sessionServlet = newSession(request, response);
                httpSession.setAttribute(lookupName, sessionServlet);
            } else {
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder().append("session id: ")
                    .append(request.getRequestedSessionId()).append(", created at: ")
                    .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                            .format(new java.util.Date(httpSession.getCreationTime())))
                    .append(", identified via:")
                    .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "")
                    .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ")
                    .append(httpSession.getMaxInactiveInterval()).append("s ");
            log.debug(message.toString());
            //log.debug("session valid " + request.isRequestedSessionIdValid());
            //log.debug("session httpsession id " + httpSession.getId());
            //log.debug("session httpsession new " + httpSession.isNew());
            //log.debug("session last accessed at " +
            //        new java.util.Date(httpSession.getLastAccessedTime()));
            //log.debug("session expiration timeout (s) " +
            //        httpSession.getMaxInactiveInterval());
            //log.debug("session contains wings session " +
            //        (httpSession.getAttribute(lookupName) != null));
        }

        sessionServlet.getSession().getExternalizeManager().setResponse(response);

        /* Handling of the requests character encoding.
         * --------------------------------------------
         * The following block is needed for a correct handling of
         * non-ISO-8859-1 data:
         *
         * Using LocaleCharacterSet and/or charset.properties we can
         * advise the client to use i.e. UTF-8 as character encoding.
         * Once told the browser consequently also encodes his requests
         * in the choosen characterset of the sings session. This is
         * achieved by adding the HTML code
         * <meta http-equiv="Content-Type" content="text/html;charset="<charset>">
         * to the generated pages.
         *
         * If the user hasn't overridden the encoding in their browser,
         * then all form data (e.g. mueller) is submitted with data encoded
         * like m%C3%BCller because byte pair C3 BC is how the german
         * u-umlaut is represented in UTF-8. If the form is
         * iso-8859-1 encoded then you get m%FCller, because byte FC is
         * how it is presented in iso-8859-1.
         *
         * So the browser behaves correctly by sending his form input
         * correctly encoded in the advised character encoding. The issue
         * is that the servlet container is typically unable to determine
         * the correct encoding of this form data. By proposal the browser
         * should als declare the used character encoding for his data.
         * But actual browsers omit this information and hence the servlet
         * container is unable to guess the right encoding (Tomcat actually
         * thenalways guesses ISO 8859-1). This results in totally
         * scrumbled up data for all non ISO-8859-1 character encodings.
         * With the block below we tell the servlet container about the
         * character encoding we expect in the browsers request and hence
         * the servlet container can do the correct decoding.
         * This has to be done at very first, otherwise the servlet
         * container will ignore this setting.
         */
        if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding?
            try {
                String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding();
                // We know better about the used character encoding than tomcat
                log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding);
                request.setCharacterEncoding(sessionCharacterEncoding);
            } catch (UnsupportedEncodingException e) {
                log.warn("Problem on applying current session character encoding", e);
            }
        }

        return sessionServlet;
    }
}