FileDocCategorySizeDatePackage
ApplicationHttpRequest.javaAPI DocGlassfish v2 API31329Fri May 04 22:31:54 BST 2007org.apache.catalina.core

ApplicationHttpRequest

public class ApplicationHttpRequest extends HttpServletRequestWrapper
Wrapper around a javax.servlet.http.HttpServletRequest that transforms an application request object (which might be the original one passed to a servlet, or might be based on the 2.3 javax.servlet.http.HttpServletRequestWrapper class) back into an internal org.apache.catalina.HttpRequest.

WARNING: Due to Java's lack of support for multiple inheritance, all of the logic in ApplicationRequest is duplicated in ApplicationHttpRequest. Make sure that you keep these two classes in synchronization when making changes!

author
Craig R. McClanahan
author
Remy Maucherat
version
$Revision: 1.16 $ $Date: 2007/05/05 05:31:54 $

Fields Summary
protected static final org.apache.catalina.util.StringManager
sm
The string manager for this package.
private String
requestedSessionVersion
private boolean
isSessionVersioningSupported
protected org.apache.catalina.Context
context
The context for this request.
protected String
contextPath
The context path for this request.
protected boolean
crossContext
If this request is cross context, since this changes session accesss behavior.
protected Object
dispatcherType
The current dispatcher type.
protected static final String
info
Descriptive information about this implementation.
protected Map
parameters
The request parameters for this request. This is initialized from the wrapped request, but updates are allowed.
private boolean
parsedParams
Have the parameters for this request already been parsed?
protected String
pathInfo
The path information for this request.
private String
queryParamString
The query parameters for the current request.
protected String
queryString
The query string for this request.
protected Object
requestDispatcherPath
The current request dispatcher path.
protected String
requestURI
The request URI for this request.
protected String
servletPath
The servlet path for this request.
protected org.apache.catalina.Session
session
The currently active session for this request.
private HashMap
specialAttributes
Special attributes.
private boolean
isIncludeDispatch
true if this wrapper has been created for an include dispatch, false otherwise
Constructors Summary
public ApplicationHttpRequest(HttpServletRequest request, org.apache.catalina.Context context, boolean crossContext)
Construct a new wrapped request around the specified servlet request.

param
request The servlet request being wrapped



    // ----------------------------------------------------------- Constructors


                          
        
                                    

        super(request);
        this.context = context;
        this.crossContext = crossContext;
        setRequest(request);

        if (context.getManager() != null) {
            isSessionVersioningSupported =
                context.getManager().isSessionVersioningSupported();
            if (isSessionVersioningSupported) {
                HashMap<String, String> sessionVersions =
                    (HashMap<String, String>) getAttribute(
                        Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE);
                if (sessionVersions != null) {
                    requestedSessionVersion = sessionVersions.get(
                        context.getPath());
                }
            }
        }
    
Methods Summary
java.util.MapcopyMap(java.util.Map orig)
Perform a shallow copy of the specified Map, and return the result.

param
orig Origin Map to be copied


        if (orig == null)
            return (new HashMap());
        HashMap dest = new HashMap();
        synchronized (orig) {
            Iterator keys = orig.keySet().iterator();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                dest.put(key, orig.get(key));
            }
        }
        return (dest);

    
public java.lang.ObjectgetAttribute(java.lang.String name)
Override the getAttribute() method of the wrapped request.

param
name Name of the attribute to retrieve



    // ------------------------------------------------- ServletRequest Methods


                         
        

        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
            return dispatcherType;
        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
            if ( requestDispatcherPath != null ){
                return requestDispatcherPath.toString();
            } else {
                return null;   
            }
        }

        if (!ApplicationRequest.isSpecial(name)) {
            return getRequest().getAttribute(name);
        } else {
            Object value = null;
            if (specialAttributes != null) {
                value = specialAttributes.get(name);
            }
            if (value == null && specialAttributes != null
                    && name.startsWith("javax.servlet.forward")) {
                // If it's a forward special attribute, and null, it means this
                // is an include, so we check the wrapped request since 
                // the request could have been forwarded before the include
                return getRequest().getAttribute(name);
            } else {
                return value;
            }
        }

    
public java.util.EnumerationgetAttributeNames()
Override the getAttributeNames() method of the wrapped request.

        return (new AttributeNamesEnumerator());
    
public java.lang.StringgetContextPath()
Override the getContextPath() method of the wrapped request.


        return (this.contextPath);

    
public java.lang.StringgetInfo()
Return descriptive information about this implementation.


        return (this.info);

    
public java.lang.StringgetParameter(java.lang.String name)
Override the getParameter() method of the wrapped request.

param
name Name of the requested parameter


	parseParameters();
        synchronized (parameters) {
            Object value = parameters.get(name);
            if (value == null)
                return (null);
            else if (value instanceof String[])
                return (((String[]) value)[0]);
            else if (value instanceof String)
                return ((String) value);
            else
                return (value.toString());
        }

    
public java.util.MapgetParameterMap()
Override the getParameterMap() method of the wrapped request.


	parseParameters();
        return (parameters);

    
public java.util.EnumerationgetParameterNames()
Override the getParameterNames() method of the wrapped request.


	parseParameters();
        synchronized (parameters) {
            return (new Enumerator(parameters.keySet()));
        }

    
public java.lang.String[]getParameterValues(java.lang.String name)
Override the getParameterValues() method of the wrapped request.

param
name Name of the requested parameter


	parseParameters();
        synchronized (parameters) {
            Object value = parameters.get(name);
            if (value == null)
                return ((String[]) null);
            else if (value instanceof String[])
                return ((String[]) value);
            else if (value instanceof String) {
                String values[] = new String[1];
                values[0] = (String) value;
                return (values);
            } else {
                String values[] = new String[1];
                values[0] = value.toString();
                return (values);
            }
        }

    
public java.lang.StringgetPathInfo()
Override the getPathInfo() method of the wrapped request.


        return (this.pathInfo);

    
public java.lang.StringgetQueryString()
Override the getQueryString() method of the wrapped request.


        return (this.queryString);

    
public javax.servlet.RequestDispatchergetRequestDispatcher(java.lang.String path)
Return a RequestDispatcher that wraps the resource at the specified path, which may be interpreted as relative to the current request path.

param
path Path of the resource to be wrapped


        if (context == null)
            return (null);

        // If the path is already context-relative, just pass it through
        if (path == null)
            return (null);
        else if (path.startsWith("/"))
            return (context.getServletContext().getRequestDispatcher(path));

        // Convert a request-relative path to a context-relative one
        String servletPath = 
            (String) getAttribute(Globals.INCLUDE_SERVLET_PATH_ATTR);
        if (servletPath == null)
            servletPath = getServletPath();

        // Add the path info, if there is any
        String pathInfo = getPathInfo();
        String requestPath = null;

        if (pathInfo == null) {
            requestPath = servletPath;
        } else {
            requestPath = servletPath + pathInfo;
        }

        int pos = requestPath.lastIndexOf('/");
        String relative = null;
        if (pos >= 0) {
            relative = RequestUtil.normalize
                (requestPath.substring(0, pos + 1) + path);
        } else {
            relative = RequestUtil.normalize(requestPath + path);
        }

        return (context.getServletContext().getRequestDispatcher(relative));

    
public java.lang.StringgetRequestURI()
Override the getRequestURI() method of the wrapped request.


        return (this.requestURI);

    
public java.lang.StringBuffergetRequestURL()
Override the getRequestURL() method of the wrapped request.


        StringBuffer url = new StringBuffer();
        String scheme = getScheme();
        int port = getServerPort();
        if (port < 0)
            port = 80; // Work around java.net.URL bug

        url.append(scheme);
        url.append("://");
        url.append(getServerName());
        if ((scheme.equals("http") && (port != 80))
            || (scheme.equals("https") && (port != 443))) {
            url.append(':");
            url.append(port);
        }
        url.append(getRequestURI());

        return (url);
    
public java.lang.StringgetServletPath()
Override the getServletPath() method of the wrapped request.


        return (this.servletPath);

    
public javax.servlet.http.HttpSessiongetSession()
Return the session associated with this Request, creating one if necessary.

        return (getSession(true));
    
public javax.servlet.http.HttpSessiongetSession(boolean create)
Return the session associated with this Request, creating one if necessary and requested.

param
create Create a new session if one does not exist


        if (crossContext) {
            
            // There cannot be a session if no context has been assigned yet
            if (context == null)
                return (null);

            // Return the current session if it exists and is valid
            if (session != null && session.isValid()) {
                return (session.getSession());
            }

            HttpSession other = super.getSession(false);
            if (create && (other == null)) {
                // First create a session in the first context: the problem is
                // that the top level request is the only one which can 
                // create the cookie safely
                other = super.getSession(true);
            }
            if (other != null) {
                Session localSession = null;
                try {
                    if (isSessionVersioningSupported) {
                        localSession =
                            context.getManager().findSession(
                                other.getId(),
                                requestedSessionVersion);
                        incrementSessionVersion((StandardSession) localSession,
                                                context);
                    } else {
                        localSession =
                            context.getManager().findSession(other.getId());
                    }
                } catch (IOException e) {
                    // Ignore
                }

                if ((localSession != null) && !localSession.isValid()) {
                    localSession = null;
                } else if (localSession == null && create) {
                    //START OF 6364900
                    localSession = 
                        context.getManager().createSession(other.getId());
                    if (isSessionVersioningSupported) {
                        incrementSessionVersion((StandardSession) localSession,
                                                context);
                    }
                    //END OF 6364900
                    /* CR 6364900
                    localSession = context.getManager().createEmptySession();
                    localSession.setNew(true);
                    localSession.setValid(true);
                    localSession.setCreationTime(System.currentTimeMillis());
                    localSession.setMaxInactiveInterval
                        (context.getManager().getMaxInactiveIntervalSeconds());
                    localSession.setId(other.getId());
                    */
                    // START GlassFish 896
                    SessionTracker tracker = (SessionTracker) getAttribute(
                        Globals.SESSION_TRACKER);
                    tracker.track(localSession);
                    // END GlassFish 896
                }
                if (localSession != null) {
                    localSession.access();
                    session = localSession;
                    return session.getSession();
                }
            }
            return null;

        } else {
            return super.getSession(create);
        }

    
private voidincrementSessionVersion(org.apache.catalina.session.StandardSession ss, org.apache.catalina.Context context)
Increments the version of the given session, and stores it as a request attribute, so it can later be included in a response cookie.


        if (ss == null || context == null) {
            return;
        }

        ss.incrementVersion();
        String versionString = Long.toString(ss.getVersion());

        HashMap<String, String> sessionVersions = (HashMap<String, String>)
            getAttribute(Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE);
        if (sessionVersions == null) {
            sessionVersions = new HashMap<String, String>();
            setAttribute(Globals.SESSION_VERSIONS_REQUEST_ATTRIBUTE,
                         sessionVersions);
        }
        String path = context.getPath();
        if ("".equals(path)) {
            path = "/";
        }
        sessionVersions.put(path, versionString);
    
voidinitSpecialAttributes(boolean isIncludeDispatch, java.lang.String requestUri, java.lang.String contextPath, java.lang.String servletPath, java.lang.String pathInfo, java.lang.String queryString)
Initializes the special attributes of this request wrapper.

param
isIncludeDispatch true if the given attributes are for an include dispatch, false if they are for a forward dispatch
param
requestUri The request URI
param
contextPath The context path
param
servletPath The servlet path
param
pathInfo The path info
param
queryString The query string


        this.isIncludeDispatch = isIncludeDispatch;

        specialAttributes = new HashMap(5);

        if (isIncludeDispatch) {        
            specialAttributes.put(Globals.INCLUDE_REQUEST_URI_ATTR,
                                  requestUri);
            specialAttributes.put(Globals.INCLUDE_CONTEXT_PATH_ATTR,
                                  contextPath);
            specialAttributes.put(Globals.INCLUDE_SERVLET_PATH_ATTR,
                                  servletPath);
            specialAttributes.put(Globals.INCLUDE_PATH_INFO_ATTR,
                                  pathInfo);
            specialAttributes.put(Globals.INCLUDE_QUERY_STRING_ATTR,
                                  queryString);
        } else {
            specialAttributes.put(Globals.FORWARD_REQUEST_URI_ATTR,
                                  requestUri);
            specialAttributes.put(Globals.FORWARD_CONTEXT_PATH_ATTR,
                                  contextPath);
            specialAttributes.put(Globals.FORWARD_SERVLET_PATH_ATTR,
                                  servletPath);
            specialAttributes.put(Globals.FORWARD_PATH_INFO_ATTR,
                                  pathInfo);
            specialAttributes.put(Globals.FORWARD_QUERY_STRING_ATTR,
                                  queryString);
        }
    
public booleanisRequestedSessionIdValid()
Returns true if the request specifies a JSESSIONID that is valid within the context of this ApplicationHttpRequest, false otherwise.

return
true if the request specifies a JSESSIONID that is valid within the context of this ApplicationHttpRequest, false otherwise.


        if (crossContext) {

            String requestedSessionId = getRequestedSessionId();
            if (requestedSessionId == null)
                return (false);
            if (context == null)
                return (false);

            if (session != null
                    && requestedSessionId.equals(session.getIdInternal())) {
                return session.isValid();
            }

            Manager manager = context.getManager();
            if (manager == null)
                return (false);
            Session localSession = null;
            try {
                if (isSessionVersioningSupported) {
                    localSession = manager.findSession(requestedSessionId,
                                                       requestedSessionVersion);
                } else {
                    localSession = manager.findSession(requestedSessionId);
                }
            } catch (IOException e) {
                localSession = null;
            }
            if ((localSession != null) && localSession.isValid()) {
                return (true);
            } else {
                return (false);
            }

        } else {
            return super.isRequestedSessionIdValid();
        }
    
private voidmergeParameters()
Merge the parameters from the saved query parameter string (if any), and the parameters already present on this request (if any), such that the parameter values from the query string show up first if there are duplicate parameter names.


        if ((queryParamString == null) || (queryParamString.length() < 1))
            return;

        HashMap queryParameters = new HashMap();
        String encoding = getCharacterEncoding();
        if (encoding == null)
            encoding = "ISO-8859-1";
        try {
            RequestUtil.parseParameters
                (queryParameters, queryParamString, encoding);
        } catch (Exception e) {
            ;
        }
        synchronized (parameters) {
            Iterator keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                Object value = queryParameters.get(key);
                if (value == null) {
                    queryParameters.put(key, parameters.get(key));
                    continue;
                }
                queryParameters.put
                    (key, mergeValues(value, parameters.get(key)));
            }
            parameters = queryParameters;
        }

    
protected java.lang.String[]mergeValues(java.lang.Object values1, java.lang.Object values2)
Merge the two sets of parameter values into a single String array.

param
values1 First set of values
param
values2 Second set of values


        ArrayList results = new ArrayList();

        if (values1 == null)
            ;
        else if (values1 instanceof String)
            results.add(values1);
        else if (values1 instanceof String[]) {
            String values[] = (String[]) values1;
            for (int i = 0; i < values.length; i++)
                results.add(values[i]);
        } else
            results.add(values1.toString());

        if (values2 == null)
            ;
        else if (values2 instanceof String)
            results.add(values2);
        else if (values2 instanceof String[]) {
            String values[] = (String[]) values2;
            for (int i = 0; i < values.length; i++)
                results.add(values[i]);
        } else
            results.add(values2.toString());

        String values[] = new String[results.size()];
        return ((String[]) results.toArray(values));

    
voidparseParameters()
Parses the parameters of this request. If parameters are present in both the query string and the request content, they are merged.


	if (parsedParams) {
	    return;
	}

        parameters = new HashMap();
        synchronized (parameters) {
            parameters = copyMap(getRequest().getParameterMap());
	    mergeParameters();
	    parsedParams = true;
        }
    
public voidrecycle()
Recycle this request

        if (session != null) {
            session.endAccess();
        }
    
public voidremoveAttribute(java.lang.String name)
Override the removeAttribute() method of the wrapped request.

param
name Name of the attribute to remove


        if (ApplicationRequest.isSpecial(name)) {
            if (specialAttributes != null) {
                specialAttributes.remove(name);
            }
        } else {
            getRequest().removeAttribute(name);
        }
    
public voidsetAttribute(java.lang.String name, java.lang.Object value)
Override the setAttribute() method of the wrapped request.

param
name Name of the attribute to set
param
value Value of the attribute to set


        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
            dispatcherType = value;
            return;
        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
            requestDispatcherPath = value;
            return;
        }

        if (ApplicationRequest.isSpecial(name)) {
            if (specialAttributes != null) {
                specialAttributes.put(name, value);
            }
        } else {
            getRequest().setAttribute(name, value);
        }
    
voidsetContextPath(java.lang.String contextPath)
Set the context path for this request.

param
contextPath The new context path


        this.contextPath = contextPath;

    
voidsetPathInfo(java.lang.String pathInfo)
Set the path information for this request.

param
pathInfo The new path info


        this.pathInfo = pathInfo;

    
voidsetQueryParams(java.lang.String queryString)
Save query parameters for this request.

param
queryString The query string containing parameters for this request

        this.queryParamString = queryString;
    
voidsetQueryString(java.lang.String queryString)
Set the query string for this request.

param
queryString The new query string


        this.queryString = queryString;

    
voidsetRequest(javax.servlet.http.HttpServletRequest request)
Set the request that we are wrapping.

param
request The new wrapped request


        super.setRequest(request);

        // Initialize the attributes for this request
        dispatcherType = request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);
        requestDispatcherPath = 
            request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);

        // Initialize the path elements for this request
        contextPath = request.getContextPath();
        pathInfo = request.getPathInfo();
        queryString = request.getQueryString();
        requestURI = request.getRequestURI();
        servletPath = request.getServletPath();

    
voidsetRequestURI(java.lang.String requestURI)
Set the request URI for this request.

param
requestURI The new request URI


        this.requestURI = requestURI;

    
voidsetServletPath(java.lang.String servletPath)
Set the servlet path for this request.

param
servletPath The new servlet path


        this.servletPath = servletPath;