FileDocCategorySizeDatePackage
Request.javaAPI DocApache Tomcat 6.0.1473329Fri Jul 20 04:20:34 BST 2007org.apache.catalina.connector

Request

public class Request extends Object implements HttpServletRequest
Wrapper object for the Coyote request.
author
Remy Maucherat
author
Craig R. McClanahan
version
$Revision: 535030 $ $Date: 2007-05-04 01:54:31 +0200 (ven., 04 mai 2007) $

Fields Summary
protected org.apache.coyote.Request
coyoteRequest
Coyote request.
protected static final TimeZone
GMT_ZONE
protected static org.apache.catalina.util.StringManager
sm
The string manager for this package.
protected Cookie[]
cookies
The set of cookies associated with this Request.
protected SimpleDateFormat[]
formats
The set of SimpleDateFormat formats to use in getDateHeader(). Notice that because SimpleDateFormat is not thread-safe, we can't declare formats[] as a static variable.
protected static Locale
defaultLocale
The default Locale if none are specified.
protected HashMap
attributes
The attributes associated with this Request, keyed by attribute name.
private HashMap
readOnlyAttributes
List of read only attributes for this Request.
protected ArrayList
locales
The preferred Locales assocaited with this Request.
private transient HashMap
notes
Internal notes associated with this request by Catalina components and event listeners.
protected String
authType
Authentication type.
protected CometEventImpl
event
Associated event.
protected boolean
comet
Comet state
protected Object
dispatcherType
The current dispatcher type.
protected InputBuffer
inputBuffer
The associated input buffer.
protected CoyoteInputStream
inputStream
ServletInputStream.
protected CoyoteReader
reader
Reader.
protected boolean
usingInputStream
Using stream flag.
protected boolean
usingReader
Using writer flag.
protected Principal
userPrincipal
User principal.
protected boolean
sessionParsed
Session parsed flag.
protected boolean
parametersParsed
Request parameters parsed flag.
protected boolean
cookiesParsed
Cookies parsed flag.
protected boolean
secure
Secure flag.
protected transient Subject
subject
The Subject associated with the current AccessControllerContext
protected static int
CACHED_POST_LEN
Post data buffer.
protected byte[]
postData
protected org.apache.catalina.util.ParameterMap
parameterMap
Hash map used in the getParametersMap method.
protected org.apache.catalina.Session
session
The currently active session for this request.
protected Object
requestDispatcherPath
The current request dispatcher path.
protected boolean
requestedSessionCookie
Was the requested session ID received in a cookie?
protected String
requestedSessionId
The requested session ID (if any) for this request.
protected boolean
requestedSessionURL
Was the requested session ID received in a URL?
protected boolean
localesParsed
Parse locales.
private org.apache.catalina.util.StringParser
parser
The string parser we will use for parsing request lines.
protected int
localPort
Local port
protected String
remoteAddr
Remote address.
protected String
remoteHost
Remote host.
protected int
remotePort
Remote port
protected String
localAddr
Local address
protected String
localName
Local address
protected Connector
connector
Associated Catalina connector.
protected org.apache.catalina.Context
context
Associated context.
protected FilterChain
filterChain
Filter chain associated with the request.
protected static final String
info
Descriptive information about this Request implementation.
protected org.apache.tomcat.util.http.mapper.MappingData
mappingData
Mapping data.
protected RequestFacade
facade
The facade associated with this request.
protected org.apache.catalina.connector.Response
response
The response with which this request is associated.
protected org.apache.tomcat.util.buf.B2CConverter
URIConverter
URI byte to char converter (not recycled).
protected org.apache.catalina.Wrapper
wrapper
Associated wrapper.
Constructors Summary
public Request()

        // Ensure that classes are loaded for SM
        new StringCache.ByteEntry();
        new StringCache.CharEntry();
    

        formats[0].setTimeZone(GMT_ZONE);
        formats[1].setTimeZone(GMT_ZONE);
        formats[2].setTimeZone(GMT_ZONE);

    
Methods Summary
public voidaddCookie(javax.servlet.http.Cookie cookie)
Add a Cookie to the set of Cookies associated with this Request.

param
cookie The new cookie


        if (!cookiesParsed)
            parseCookies();

        int size = 0;
        if (cookies != null) {
            size = cookies.length;
        }

        Cookie[] newCookies = new Cookie[size + 1];
        for (int i = 0; i < size; i++) {
            newCookies[i] = cookies[i];
        }
        newCookies[size] = cookie;

        cookies = newCookies;

    
public voidaddHeader(java.lang.String name, java.lang.String value)
Add a Header to the set of Headers associated with this Request.

param
name The new header name
param
value The new header value

        // Not used
    
public voidaddLocale(java.util.Locale locale)
Add a Locale to the set of preferred Locales for this Request. The first added Locale will be the first one returned by getLocales().

param
locale The new preferred Locale

        locales.add(locale);
    
public voidaddParameter(java.lang.String name, java.lang.String[] values)
Add a parameter name and corresponding set of values to this Request. (This is used when restoring the original request on a form based login).

param
name Name of this request parameter
param
values Corresponding values for this request parameter

        coyoteRequest.getParameters().addParameterValues(name, values);
    
public voidclearCookies()
Clear the collection of Cookies associated with this Request.

        cookiesParsed = true;
        cookies = null;
    
public voidclearEncoders()
Clear cached encoders (to save memory for Comet requests).

        inputBuffer.clearEncoders();
    
public voidclearHeaders()
Clear the collection of Headers associated with this Request.

        // Not used
    
public voidclearLocales()
Clear the collection of Locales associated with this Request.

        locales.clear();
    
public voidclearParameters()
Clear the collection of parameters associated with this Request.

        // Not used
    
protected voidconfigureSessionCookie(javax.servlet.http.Cookie cookie)
Configures the given JSESSIONID cookie.

param
cookie The JSESSIONID cookie to be configured

        cookie.setMaxAge(-1);
        String contextPath = null;
        if (!connector.getEmptySessionPath() && (getContext() != null)) {
            contextPath = getContext().getEncodedPath();
        }
        if ((contextPath != null) && (contextPath.length() > 0)) {
            cookie.setPath(contextPath);
        } else {
            cookie.setPath("/");
        }
        if (isSecure()) {
            cookie.setSecure(true);
        }
    
public javax.servlet.ServletInputStreamcreateInputStream()
Create and return a ServletInputStream to read the content associated with this Request.

exception
IOException if an input/output error occurs

        if (inputStream == null) {
            inputStream = new CoyoteInputStream(inputBuffer);
        }
        return inputStream;
    
protected org.apache.catalina.SessiondoGetSession(boolean create)


        // 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())
            session = null;
        if (session != null)
            return (session);

        // Return the requested session if it exists and is valid
        Manager manager = null;
        if (context != null)
            manager = context.getManager();
        if (manager == null)
            return (null);      // Sessions are not supported
        if (requestedSessionId != null) {
            try {
                session = manager.findSession(requestedSessionId);
            } catch (IOException e) {
                session = null;
            }
            if ((session != null) && !session.isValid())
                session = null;
            if (session != null) {
                session.access();
                return (session);
            }
        }

        // Create a new session if requested and the response is not committed
        if (!create)
            return (null);
        if ((context != null) && (response != null) &&
            context.getCookies() &&
            response.getResponse().isCommitted()) {
            throw new IllegalStateException
              (sm.getString("coyoteRequest.sessionCreateCommitted"));
        }

        // Attempt to reuse session id if one was submitted in a cookie
        // Do not reuse the session id if it is from a URL, to prevent possible
        // phishing attacks
        if (connector.getEmptySessionPath() 
                && isRequestedSessionIdFromCookie()) {
            session = manager.createSession(getRequestedSessionId());
        } else {
            session = manager.createSession(null);
        }

        // Creating a new session cookie based on that session
        if ((session != null) && (getContext() != null)
               && getContext().getCookies()) {
            Cookie cookie = new Cookie(Globals.SESSION_COOKIE_NAME,
                                       session.getIdInternal());
            configureSessionCookie(cookie);
            response.addCookieInternal(cookie);
        }

        if (session != null) {
            session.access();
            return (session);
        } else {
            return (null);
        }

    
public voidfinishRequest()
Perform whatever actions are required to flush and close the input stream or reader, in a single operation.

exception
IOException if an input/output error occurs

        // The reader and input stream don't need to be closed
    
public java.lang.ObjectgetAttribute(java.lang.String name)
Return the specified request attribute if it exists; otherwise, return null.

param
name Name of the request attribute to return


        if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) {
            return (dispatcherType == null) 
                ? ApplicationFilterFactory.REQUEST_INTEGER
                : dispatcherType;
        } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) {
            return (requestDispatcherPath == null) 
                ? getRequestPathMB().toString()
                : requestDispatcherPath.toString();
        }

        Object attr=attributes.get(name);

        if(attr!=null)
            return(attr);

        attr =  coyoteRequest.getAttribute(name);
        if(attr != null)
            return attr;
        if( isSSLAttribute(name) ) {
            coyoteRequest.action(ActionCode.ACTION_REQ_SSL_ATTRIBUTE, 
                                 coyoteRequest);
            attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR);
            if( attr != null) {
                attributes.put(Globals.CERTIFICATES_ATTR, attr);
            }
            attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR);
            if(attr != null) {
                attributes.put(Globals.CIPHER_SUITE_ATTR, attr);
            }
            attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR);
            if(attr != null) {
                attributes.put(Globals.KEY_SIZE_ATTR, attr);
            }
            attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR);
            if(attr != null) {
                attributes.put(Globals.SSL_SESSION_ID_ATTR, attr);
            }
            attr = attributes.get(name);
        }
        return attr;
    
public java.util.EnumerationgetAttributeNames()
Return the names of all request attributes for this Request, or an empty Enumeration if there are none.

        if (isSecure()) {
            getAttribute(Globals.CERTIFICATES_ATTR);
        }
        return new Enumerator(attributes.keySet(), true);
    
public java.lang.StringgetAuthType()
Return the authentication type used for this Request.

        return (authType);
    
public booleangetAvailable()
Return true if bytes are available.

        return (inputBuffer.available() > 0);
    
public java.lang.StringgetCharacterEncoding()
Return the character encoding for this Request.

      return (coyoteRequest.getCharacterEncoding());
    
public ConnectorgetConnector()
Return the Connector through which this Request was received.

        return (this.connector);
    
public intgetContentLength()
Return the content length for this Request.

        return (coyoteRequest.getContentLength());
    
public java.lang.StringgetContentType()
Return the content type for this Request.

        return (coyoteRequest.getContentType());
    
public org.apache.catalina.ContextgetContext()
Return the Context within which this Request is being processed.


                   
       
        return (this.context);
    
public java.lang.StringgetContextPath()
Return the portion of the request URI used to select the Context of the Request.

        return (mappingData.contextPath.toString());
    
public org.apache.tomcat.util.buf.MessageBytesgetContextPathMB()
Get the context path.

return
the context path

        return (mappingData.contextPath);
    
public javax.servlet.http.Cookie[]getCookies()
Return the set of Cookies received with this Request.


        if (!cookiesParsed)
            parseCookies();

        return cookies;

    
public org.apache.coyote.RequestgetCoyoteRequest()
Get the Coyote request.

        return (this.coyoteRequest);
    
public longgetDateHeader(java.lang.String name)
Return the value of the specified date header, if any; otherwise return -1.

param
name Name of the requested date header
exception
IllegalArgumentException if the specified header value cannot be converted to a date


        String value = getHeader(name);
        if (value == null)
            return (-1L);

        // Attempt to convert the date header in a variety of formats
        long result = FastHttpDateFormat.parseDate(value, formats);
        if (result != (-1L)) {
            return result;
        }
        throw new IllegalArgumentException(value);

    
public java.lang.StringgetDecodedRequestURI()
Get the decoded request URI.

return
the URL decoded request URI

        return (coyoteRequest.decodedURI().toString());
    
public org.apache.tomcat.util.buf.MessageBytesgetDecodedRequestURIMB()
Get the decoded request URI.

return
the URL decoded request URI

        return (coyoteRequest.decodedURI());
    
public CometEventImplgetEvent()
Get the event associated with the request.

return

        if (event == null) {
            event = new CometEventImpl(this, response);
        }
        return event;
    
public javax.servlet.FilterChaingetFilterChain()
Get filter chain associated with the request.


                
       
        return (this.filterChain);
    
public java.lang.StringgetHeader(java.lang.String name)
Return the first value of the specified header, if any; otherwise, return null

param
name Name of the requested header

        return coyoteRequest.getHeader(name);
    
public java.util.EnumerationgetHeaderNames()
Return the names of all headers received with this request.

        return coyoteRequest.getMimeHeaders().names();
    
public java.util.EnumerationgetHeaders(java.lang.String name)
Return all of the values of the specified header, if any; otherwise, return an empty enumeration.

param
name Name of the requested header

        return coyoteRequest.getMimeHeaders().values(name);
    
public org.apache.catalina.HostgetHost()
Return the Host within which this Request is being processed.

        if (getContext() == null)
            return null;
        return (Host) getContext().getParent();
        //return ((Host) mappingData.host);
    
public java.lang.StringgetInfo()
Return descriptive information about this Request implementation and the corresponding version number, in the format <description>/<version>.


                         
       
        return (info);
    
public javax.servlet.ServletInputStreamgetInputStream()
Return the servlet input stream for this Request. The default implementation returns a servlet input stream created by createInputStream().

exception
IllegalStateException if getReader() has already been called for this request
exception
IOException if an input/output error occurs


        if (usingReader)
            throw new IllegalStateException
                (sm.getString("coyoteRequest.getInputStream.ise"));

        usingInputStream = true;
        if (inputStream == null) {
            inputStream = new CoyoteInputStream(inputBuffer);
        }
        return inputStream;

    
public intgetIntHeader(java.lang.String name)
Return the value of the specified header as an integer, or -1 if there is no such header for this request.

param
name Name of the requested header
exception
IllegalArgumentException if the specified header value cannot be converted to an integer


        String value = getHeader(name);
        if (value == null) {
            return (-1);
        } else {
            return (Integer.parseInt(value));
        }

    
public java.lang.StringgetLocalAddr()
Returns the Internet Protocol (IP) address of the interface on which the request was received.

        if (localAddr == null) {
            coyoteRequest.action
                (ActionCode.ACTION_REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest);
            localAddr = coyoteRequest.localAddr().toString();
        }
        return localAddr;    
    
public java.lang.StringgetLocalName()
Returns the host name of the Internet Protocol (IP) interface on which the request was received.

        if (localName == null) {
            coyoteRequest.action
                (ActionCode.ACTION_REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest);
            localName = coyoteRequest.localName().toString();
        }
        return localName;
    
public intgetLocalPort()
Returns the Internet Protocol (IP) port number of the interface on which the request was received.

        if (localPort == -1){
            coyoteRequest.action
                (ActionCode.ACTION_REQ_LOCALPORT_ATTRIBUTE, coyoteRequest);
            localPort = coyoteRequest.getLocalPort();
        }
        return localPort;
    
public java.util.LocalegetLocale()
Return the preferred Locale that the client will accept content in, based on the value for the first Accept-Language header that was encountered. If the request did not specify a preferred language, the server's default Locale is returned.


        if (!localesParsed)
            parseLocales();

        if (locales.size() > 0) {
            return ((Locale) locales.get(0));
        } else {
            return (defaultLocale);
        }

    
public java.util.EnumerationgetLocales()
Return the set of preferred Locales that the client will accept content in, based on the values for any Accept-Language headers that were encountered. If the request did not specify a preferred language, the server's default Locale is returned.


        if (!localesParsed)
            parseLocales();

        if (locales.size() > 0)
            return (new Enumerator(locales));
        ArrayList results = new ArrayList();
        results.add(defaultLocale);
        return (new Enumerator(results));

    
public org.apache.tomcat.util.http.mapper.MappingDatagetMappingData()
Return mapping data.


            
       
        return (mappingData);
    
public java.lang.StringgetMethod()
Return the HTTP request method used in this Request.

        return coyoteRequest.method().toString();
    
public java.lang.ObjectgetNote(java.lang.String name)
Return the object bound with the specified name to the internal notes for this request, or null if no such binding exists.

param
name Name of the note to be returned

        return (notes.get(name));
    
public java.util.IteratorgetNoteNames()
Return an Iterator containing the String names of all notes bindings that exist for this request.

        return (notes.keySet().iterator());
    
public java.lang.StringgetParameter(java.lang.String name)
Return the value of the specified request parameter, if any; otherwise, return null. If there is more than one value defined, return only the first one.

param
name Name of the desired request parameter


        if (!parametersParsed)
            parseParameters();

        return coyoteRequest.getParameters().getParameter(name);

    
public java.util.MapgetParameterMap()
Returns a Map of the parameters of this request. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

return
A Map containing parameter names as keys and parameter values as map values.


        if (parameterMap.isLocked())
            return parameterMap;

        Enumeration enumeration = getParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement().toString();
            String[] values = getParameterValues(name);
            parameterMap.put(name, values);
        }

        parameterMap.setLocked(true);

        return parameterMap;

    
public java.util.EnumerationgetParameterNames()
Return the names of all defined request parameters for this request.


        if (!parametersParsed)
            parseParameters();

        return coyoteRequest.getParameters().getParameterNames();

    
public java.lang.String[]getParameterValues(java.lang.String name)
Return the defined values for the specified request parameter, if any; otherwise, return null.

param
name Name of the desired request parameter


        if (!parametersParsed)
            parseParameters();

        return coyoteRequest.getParameters().getParameterValues(name);

    
public java.lang.StringgetPathInfo()
Return the path information associated with this Request.

        return (mappingData.pathInfo.toString());
    
public org.apache.tomcat.util.buf.MessageBytesgetPathInfoMB()
Get the path info.

return
the path info

        return (mappingData.pathInfo);
    
public java.lang.StringgetPathTranslated()
Return the extra path information for this request, translated to a real path.


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

        if (getPathInfo() == null) {
            return (null);
        } else {
            return (context.getServletContext().getRealPath(getPathInfo()));
        }

    
public java.security.PrincipalgetPrincipal()
Return the principal that has been authenticated for this Request.

        return (userPrincipal);
    
public java.lang.StringgetProtocol()
Return the protocol and version used to make this Request.

        return coyoteRequest.protocol().toString();
    
public java.lang.StringgetQueryString()
Return the query string associated with this request.

        String queryString = coyoteRequest.queryString().toString();
        if (queryString == null || queryString.equals("")) {
            return (null);
        } else {
            return queryString;
        }
    
public java.io.BufferedReadergetReader()
Read the Reader wrapping the input stream for this Request. The default implementation wraps a BufferedReader around the servlet input stream returned by createInputStream().

exception
IllegalStateException if getInputStream() has already been called for this request
exception
IOException if an input/output error occurs


        if (usingInputStream)
            throw new IllegalStateException
                (sm.getString("coyoteRequest.getReader.ise"));

        usingReader = true;
        inputBuffer.checkConverter();
        if (reader == null) {
            reader = new CoyoteReader(inputBuffer);
        }
        return reader;

    
public java.lang.StringgetRealPath(java.lang.String path)
Return the real path of the specified virtual path.

param
path Path to be translated
deprecated
As of version 2.1 of the Java Servlet API, use ServletContext.getRealPath().


        if (context == null)
            return (null);
        ServletContext servletContext = context.getServletContext();
        if (servletContext == null)
            return (null);
        else {
            try {
                return (servletContext.getRealPath(path));
            } catch (IllegalArgumentException e) {
                return (null);
            }
        }

    
public java.lang.StringgetRemoteAddr()
Return the remote IP address making this Request.

        if (remoteAddr == null) {
            coyoteRequest.action
                (ActionCode.ACTION_REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest);
            remoteAddr = coyoteRequest.remoteAddr().toString();
        }
        return remoteAddr;
    
public java.lang.StringgetRemoteHost()
Return the remote host name making this Request.

        if (remoteHost == null) {
            if (!connector.getEnableLookups()) {
                remoteHost = getRemoteAddr();
            } else {
                coyoteRequest.action
                    (ActionCode.ACTION_REQ_HOST_ATTRIBUTE, coyoteRequest);
                remoteHost = coyoteRequest.remoteHost().toString();
            }
        }
        return remoteHost;
    
public intgetRemotePort()
Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request.

        if (remotePort == -1) {
            coyoteRequest.action
                (ActionCode.ACTION_REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest);
            remotePort = coyoteRequest.getRemotePort();
        }
        return remotePort;    
    
public java.lang.StringgetRemoteUser()
Return the name of the remote user that has been authenticated for this Request.


        if (userPrincipal != null) {
            return (userPrincipal.getName());
        } else {
            return (null);
        }

    
public javax.servlet.http.HttpServletRequestgetRequest()
Return the ServletRequest for which this object is the facade. This method must be implemented by a subclass.


                            
       
        if (facade == null) {
            facade = new RequestFacade(this);
        } 
        return (facade);
    
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 org.apache.tomcat.util.buf.MessageBytesgetRequestPathMB()
Get the request path.

return
the request path

        return (mappingData.requestPath);
    
public java.lang.StringgetRequestURI()
Return the request URI for this request.

        return coyoteRequest.requestURI().toString();
    
public java.lang.StringBuffergetRequestURL()
Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.

Because this method returns a StringBuffer, not a String, you can modify the URL easily, for example, to append query parameters.

This method is useful for creating redirect messages and for reporting errors.

return
A StringBuffer object containing the reconstructed URL


        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.StringgetRequestedSessionId()
Return the session identifier included in this request, if any.

        return (requestedSessionId);
    
public org.apache.catalina.connector.ResponsegetResponse()
Return the Response with which this Request is associated.


                  
       
        return (this.response);
    
public java.lang.StringgetScheme()
Return the scheme used to make this Request.

        return (coyoteRequest.scheme().toString());
    
public java.lang.StringgetServerName()
Return the server name responding to this Request.

        return (coyoteRequest.serverName().toString());
    
public intgetServerPort()
Return the server port responding to this Request.

        return (coyoteRequest.getServerPort());
    
public java.lang.StringgetServletPath()
Return the portion of the request URI used to select the servlet that will process this request.

        return (mappingData.wrapperPath.toString());
    
public org.apache.tomcat.util.buf.MessageBytesgetServletPathMB()
Get the servlet path.

return
the servlet path

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

        Session session = doGetSession(true);
        if (session != null) {
            return session.getSession();
        } else {
            return null;
        }
    
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

        Session session = doGetSession(create);
        if (session != null) {
            return session.getSession();
        } else {
            return null;
        }
    
public org.apache.catalina.SessiongetSessionInternal()
Return the session associated with this Request, creating one if necessary.

        return doGetSession(true);
    
public org.apache.catalina.SessiongetSessionInternal(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

        return doGetSession(create);
    
public java.io.InputStreamgetStream()
Return the input stream associated with this Request.

        if (inputStream == null) {
            inputStream = new CoyoteInputStream(inputBuffer);
        }
        return inputStream;
    
protected org.apache.tomcat.util.buf.B2CConvertergetURIConverter()
Return the URI converter.


             
       
        return URIConverter;
    
public java.security.PrincipalgetUserPrincipal()
Return the principal that has been authenticated for this Request.

        if (userPrincipal instanceof GenericPrincipal) {
            return ((GenericPrincipal) userPrincipal).getUserPrincipal();
        } else {
            return (userPrincipal);
        }
    
public org.apache.catalina.WrappergetWrapper()
Return the Wrapper within which this Request is being processed.


                   
       
        return (this.wrapper);
    
protected static final booleanisAlpha(java.lang.String value)

        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            if (!((c >= 'a" && c <= 'z") || (c >= 'A" && c <= 'Z"))) {
                return false;
            }
        }
        return true;
    
public booleanisComet()
Return true if the current request is handling Comet traffic.

        return comet;
    
public booleanisRequestedSessionIdFromCookie()
Return true if the session identifier included in this request came from a cookie.


        if (requestedSessionId != null)
            return (requestedSessionCookie);
        else
            return (false);

    
public booleanisRequestedSessionIdFromURL()
Return true if the session identifier included in this request came from the request URI.


        if (requestedSessionId != null)
            return (requestedSessionURL);
        else
            return (false);

    
public booleanisRequestedSessionIdFromUrl()
Return true if the session identifier included in this request came from the request URI.

deprecated
As of Version 2.1 of the Java Servlet API, use isRequestedSessionIdFromURL() instead.

        return (isRequestedSessionIdFromURL());
    
public booleanisRequestedSessionIdValid()
Return true if the session identifier included in this request identifies a valid session.


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

    
static booleanisSSLAttribute(java.lang.String name)
Test if a given name is one of the special Servlet-spec SSL attributes.

        return Globals.CERTIFICATES_ATTR.equals(name) ||
            Globals.CIPHER_SUITE_ATTR.equals(name) ||
            Globals.KEY_SIZE_ATTR.equals(name)  ||
            Globals.SSL_SESSION_ID_ATTR.equals(name);
    
public booleanisSecure()
Was this request received on a secure connection?

        return (secure);
    
public booleanisUserInRole(java.lang.String role)
Return true if the authenticated user principal possesses the specified role name.

param
role Role name to be validated


        // Have we got an authenticated principal at all?
        if (userPrincipal == null)
            return (false);

        // Identify the Realm we will use for checking role assignmenets
        if (context == null)
            return (false);
        Realm realm = context.getRealm();
        if (realm == null)
            return (false);

        // Check for a role alias defined in a <security-role-ref> element
        if (wrapper != null) {
            String realRole = wrapper.findSecurityReference(role);
            if ((realRole != null) &&
                realm.hasRole(userPrincipal, realRole))
                return (true);
        }

        // Check for a role defined directly as a <security-role>
        return (realm.hasRole(userPrincipal, role));

    
protected voidparseCookies()
Parse cookies.


        cookiesParsed = true;

        Cookies serverCookies = coyoteRequest.getCookies();
        int count = serverCookies.getCookieCount();
        if (count <= 0)
            return;

        cookies = new Cookie[count];

        int idx=0;
        for (int i = 0; i < count; i++) {
            ServerCookie scookie = serverCookies.getCookie(i);
            try {
                Cookie cookie = new Cookie(scookie.getName().toString(),
                                           scookie.getValue().toString());
                cookie.setPath(scookie.getPath().toString());
                cookie.setVersion(scookie.getVersion());
                String domain = scookie.getDomain().toString();
                if (domain != null) {
                    cookie.setDomain(scookie.getDomain().toString());
                }
                cookies[idx++] = cookie;
            } catch(IllegalArgumentException e) {
                // Ignore bad cookie
            }
        }
        if( idx < count ) {
            Cookie [] ncookies = new Cookie[idx];
            System.arraycopy(cookies, 0, ncookies, 0, idx);
            cookies = ncookies;
        }

    
protected voidparseLocales()
Parse request locales.


        localesParsed = true;

        Enumeration values = getHeaders("accept-language");

        while (values.hasMoreElements()) {
            String value = values.nextElement().toString();
            parseLocalesHeader(value);
        }

    
protected voidparseLocalesHeader(java.lang.String value)
Parse accept-language header value.


        // Store the accumulated languages that have been requested in
        // a local collection, sorted by the quality value (so we can
        // add Locales in descending order).  The values will be ArrayLists
        // containing the corresponding Locales to be added
        TreeMap locales = new TreeMap();

        // Preprocess the value to remove all whitespace
        int white = value.indexOf(' ");
        if (white < 0)
            white = value.indexOf('\t");
        if (white >= 0) {
            StringBuffer sb = new StringBuffer();
            int len = value.length();
            for (int i = 0; i < len; i++) {
                char ch = value.charAt(i);
                if ((ch != ' ") && (ch != '\t"))
                    sb.append(ch);
            }
            value = sb.toString();
        }

        // Process each comma-delimited language specification
        parser.setString(value);        // ASSERT: parser is available to us
        int length = parser.getLength();
        while (true) {

            // Extract the next comma-delimited entry
            int start = parser.getIndex();
            if (start >= length)
                break;
            int end = parser.findChar(',");
            String entry = parser.extract(start, end).trim();
            parser.advance();   // For the following entry

            // Extract the quality factor for this entry
            double quality = 1.0;
            int semi = entry.indexOf(";q=");
            if (semi >= 0) {
                try {
                    quality = Double.parseDouble(entry.substring(semi + 3));
                } catch (NumberFormatException e) {
                    quality = 0.0;
                }
                entry = entry.substring(0, semi);
            }

            // Skip entries we are not going to keep track of
            if (quality < 0.00005)
                continue;       // Zero (or effectively zero) quality factors
            if ("*".equals(entry))
                continue;       // FIXME - "*" entries are not handled

            // Extract the language and country for this entry
            String language = null;
            String country = null;
            String variant = null;
            int dash = entry.indexOf('-");
            if (dash < 0) {
                language = entry;
                country = "";
                variant = "";
            } else {
                language = entry.substring(0, dash);
                country = entry.substring(dash + 1);
                int vDash = country.indexOf('-");
                if (vDash > 0) {
                    String cTemp = country.substring(0, vDash);
                    variant = country.substring(vDash + 1);
                    country = cTemp;
                } else {
                    variant = "";
                }
            }
            if (!isAlpha(language) || !isAlpha(country) || !isAlpha(variant)) {
                continue;
            }

            // Add a new Locale to the list of Locales for this quality level
            Locale locale = new Locale(language, country, variant);
            Double key = new Double(-quality);  // Reverse the order
            ArrayList values = (ArrayList) locales.get(key);
            if (values == null) {
                values = new ArrayList();
                locales.put(key, values);
            }
            values.add(locale);

        }

        // Process the quality values in highest->lowest order (due to
        // negating the Double value when creating the key)
        Iterator keys = locales.keySet().iterator();
        while (keys.hasNext()) {
            Double key = (Double) keys.next();
            ArrayList list = (ArrayList) locales.get(key);
            Iterator values = list.iterator();
            while (values.hasNext()) {
                Locale locale = (Locale) values.next();
                addLocale(locale);
            }
        }

    
protected voidparseParameters()
Parse request parameters.


        parametersParsed = true;

        Parameters parameters = coyoteRequest.getParameters();

        // getCharacterEncoding() may have been overridden to search for
        // hidden form field containing request encoding
        String enc = getCharacterEncoding();

        boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();
        if (enc != null) {
            parameters.setEncoding(enc);
            if (useBodyEncodingForURI) {
                parameters.setQueryStringEncoding(enc);
            }
        } else {
            parameters.setEncoding
                (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);
            if (useBodyEncodingForURI) {
                parameters.setQueryStringEncoding
                    (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);
            }
        }

        parameters.handleQueryParameters();

        if (usingInputStream || usingReader)
            return;

        if (!getMethod().equalsIgnoreCase("POST"))
            return;

        String contentType = getContentType();
        if (contentType == null)
            contentType = "";
        int semicolon = contentType.indexOf(';");
        if (semicolon >= 0) {
            contentType = contentType.substring(0, semicolon).trim();
        } else {
            contentType = contentType.trim();
        }
        if (!("application/x-www-form-urlencoded".equals(contentType)))
            return;

        int len = getContentLength();

        if (len > 0) {
            int maxPostSize = connector.getMaxPostSize();
            if ((maxPostSize > 0) && (len > maxPostSize)) {
                if (context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug("Post too large");
                }
                return;
            }
            byte[] formData = null;
            if (len < CACHED_POST_LEN) {
                if (postData == null)
                    postData = new byte[CACHED_POST_LEN];
                formData = postData;
            } else {
                formData = new byte[len];
            }
            try {
                if (readPostBody(formData, len) != len) {
                    return;
                }
            } catch (IOException e) {
                // Client disconnect
                if (context.getLogger().isDebugEnabled()) {
                    context.getLogger().debug(
                            sm.getString("coyoteRequest.parseParameters"), e);
                }
            }
            parameters.processParameters(formData, 0, len);
        }

    
public booleanread()
Clear cached encoders (to save memory for Comet requests).

        return (inputBuffer.realReadBytes(null, 0, 0) > 0);
    
protected intreadPostBody(byte[] body, int len)
Read post body in an array.


        int offset = 0;
        do {
            int inputLen = getStream().read(body, offset, len - offset);
            if (inputLen <= 0) {
                return offset;
            }
            offset += inputLen;
        } while ((len - offset) > 0);
        return len;

    
public voidrecycle()
Release all object references, and initialize instance variables, in preparation for reuse of this object.



    // --------------------------------------------------------- Public Methods


                        
       

        context = null;
        wrapper = null;

        dispatcherType = null;
        requestDispatcherPath = null;

        comet = false;
        if (event != null) {
            event.clear();
            event = null;
        }
        
        authType = null;
        inputBuffer.recycle();
        usingInputStream = false;
        usingReader = false;
        userPrincipal = null;
        subject = null;
        sessionParsed = false;
        parametersParsed = false;
        cookiesParsed = false;
        locales.clear();
        localesParsed = false;
        secure = false;
        remoteAddr = null;
        remoteHost = null;
        remotePort = -1;
        localPort = -1;
        localAddr = null;
        localName = null;

        attributes.clear();
        notes.clear();
        cookies = null;

        if (session != null) {
            session.endAccess();
        }
        session = null;
        requestedSessionCookie = false;
        requestedSessionId = null;
        requestedSessionURL = false;

        if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
            parameterMap = new ParameterMap();
        } else {
            parameterMap.setLocked(false);
            parameterMap.clear();
        }

        mappingData.recycle();

        if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
            if (facade != null) {
                facade.clear();
                facade = null;
            }
            if (inputStream != null) {
                inputStream.clear();
                inputStream = null;
            }
            if (reader != null) {
                reader.clear();
                reader = null;
            }
        }

    
public voidremoveAttribute(java.lang.String name)
Remove the specified request attribute if it exists.

param
name Name of the request attribute to remove

        Object value = null;
        boolean found = false;

        // Remove the specified attribute
        // Check for read only attribute
        // requests are per thread so synchronization unnecessary
        if (readOnlyAttributes.containsKey(name)) {
            return;
        }

        // Pass special attributes to the native layer
        if (name.startsWith("org.apache.tomcat.")) {
            coyoteRequest.getAttributes().remove(name);
        }

        found = attributes.containsKey(name);
        if (found) {
            value = attributes.get(name);
            attributes.remove(name);
        } else {
            return;
        }
        
        // Notify interested application event listeners
        Object listeners[] = context.getApplicationEventListeners();
        if ((listeners == null) || (listeners.length == 0))
            return;
        ServletRequestAttributeEvent event =
          new ServletRequestAttributeEvent(context.getServletContext(),
                                           getRequest(), name, value);
        for (int i = 0; i < listeners.length; i++) {
            if (!(listeners[i] instanceof ServletRequestAttributeListener))
                continue;
            ServletRequestAttributeListener listener =
                (ServletRequestAttributeListener) listeners[i];
            try {
                listener.attributeRemoved(event);
            } catch (Throwable t) {
                context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
                // Error valve will pick this execption up and display it to user
                attributes.put( Globals.EXCEPTION_ATTR, t );
            }
        }
    
public voidremoveNote(java.lang.String name)
Remove any object bound to the specified name in the internal notes for this request.

param
name Name of the note to be removed

        notes.remove(name);
    
public voidsetAttribute(java.lang.String name, java.lang.Object value)
Set the specified request attribute to the specified value.

param
name Name of the request attribute to set
param
value The associated value

	
        // Name cannot be null
        if (name == null)
            throw new IllegalArgumentException
                (sm.getString("coyoteRequest.setAttribute.namenull"));

        // Null value is the same as removeAttribute()
        if (value == null) {
            removeAttribute(name);
            return;
        }

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

        Object oldValue = null;
        boolean replaced = false;

        // Add or replace the specified attribute
        // Check for read only attribute
        // requests are per thread so synchronization unnecessary
        if (readOnlyAttributes.containsKey(name)) {
            return;
        }

        oldValue = attributes.put(name, value);
        if (oldValue != null) {
            replaced = true;
        }

        // Pass special attributes to the native layer
        if (name.startsWith("org.apache.tomcat.")) {
            coyoteRequest.setAttribute(name, value);
        }
        
        // Notify interested application event listeners
        Object listeners[] = context.getApplicationEventListeners();
        if ((listeners == null) || (listeners.length == 0))
            return;
        ServletRequestAttributeEvent event = null;
        if (replaced)
            event =
                new ServletRequestAttributeEvent(context.getServletContext(),
                                                 getRequest(), name, oldValue);
        else
            event =
                new ServletRequestAttributeEvent(context.getServletContext(),
                                                 getRequest(), name, value);

        for (int i = 0; i < listeners.length; i++) {
            if (!(listeners[i] instanceof ServletRequestAttributeListener))
                continue;
            ServletRequestAttributeListener listener =
                (ServletRequestAttributeListener) listeners[i];
            try {
                if (replaced) {
                    listener.attributeReplaced(event);
                } else {
                    listener.attributeAdded(event);
                }
            } catch (Throwable t) {
                context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
                // Error valve will pick this execption up and display it to user
                attributes.put( Globals.EXCEPTION_ATTR, t );
            }
        }
    
public voidsetAuthType(java.lang.String type)
Set the authentication type used for this request, if any; otherwise set the type to null. Typical values are "BASIC", "DIGEST", or "SSL".

param
type The authentication type used

        this.authType = type;
    
public voidsetCharacterEncoding(java.lang.String enc)
Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().

param
enc The character encoding to be used
exception
UnsupportedEncodingException if the specified encoding is not supported
since
Servlet 2.3


        if (usingReader)
            return;
        
        // Ensure that the specified encoding is valid
        byte buffer[] = new byte[1];
        buffer[0] = (byte) 'a";
        String dummy = new String(buffer, enc);

        // Save the validated encoding
        coyoteRequest.setCharacterEncoding(enc);

    
public voidsetComet(boolean comet)
Set comet state.

        this.comet = comet;
    
public voidsetConnector(Connector connector)
Set the Connector through which this Request was received.

param
connector The new connector

        this.connector = connector;
    
public voidsetContentLength(int length)
Set the content length associated with this Request.

param
length The new content length

        // Not used
    
public voidsetContentType(java.lang.String type)
Set the content type (and optionally the character encoding) associated with this Request. For example, text/html; charset=ISO-8859-4.

param
type The new content type

        // Not used
    
public voidsetContext(org.apache.catalina.Context context)
Set the Context within which this Request is being processed. This must be called as soon as the appropriate Context is identified, because it identifies the value to be returned by getContextPath(), and thus enables parsing of the request URI.

param
context The newly associated Context

        this.context = context;
    
public voidsetContextPath(java.lang.String path)
Set the context path for this Request. This will normally be called when the associated Context is mapping the Request to a particular Wrapper.

param
path The context path


        if (path == null) {
            mappingData.contextPath.setString("");
        } else {
            mappingData.contextPath.setString(path);
        }

    
public voidsetCookies(javax.servlet.http.Cookie[] cookies)
Set the set of cookies recieved with this Request.


        this.cookies = cookies;

    
public voidsetCoyoteRequest(org.apache.coyote.Request coyoteRequest)
Set the Coyote request.

param
coyoteRequest The Coyote request

        this.coyoteRequest = coyoteRequest;
        inputBuffer.setRequest(coyoteRequest);
    
public voidsetDecodedRequestURI(java.lang.String uri)
Set the decoded request URI.

param
uri The decoded request URI

        // Not used
    
public voidsetFilterChain(javax.servlet.FilterChain filterChain)
Set filter chain associated with the request.

param
filterChain new filter chain

        this.filterChain = filterChain;
    
public voidsetHost(org.apache.catalina.Host host)
Set the Host within which this Request is being processed. This must be called as soon as the appropriate Host is identified, and before the Request is passed to a context.

param
host The newly associated Host

        mappingData.host = host;
    
public voidsetMethod(java.lang.String method)
Set the HTTP request method used for this Request.

param
method The request method

        // Not used
    
public voidsetNote(java.lang.String name, java.lang.Object value)
Bind an object to a specified name in the internal notes associated with this request, replacing any existing binding for this name.

param
name Name to which the object should be bound
param
value Object to be bound to the specified name

        notes.put(name, value);
    
public voidsetPathInfo(java.lang.String path)
Set the path information for this Request. This will normally be called when the associated Context is mapping the Request to a particular Wrapper.

param
path The path information

        mappingData.pathInfo.setString(path);
    
public voidsetProtocol(java.lang.String protocol)
Set the protocol name and version associated with this Request.

param
protocol Protocol name and version

        // Not used
    
public voidsetQueryString(java.lang.String query)
Set the query string for this Request. This will normally be called by the HTTP Connector, when it parses the request headers.

param
query The query string

        // Not used
    
public voidsetRemoteAddr(java.lang.String remoteAddr)
Set the IP address of the remote client associated with this Request.

param
remoteAddr The remote IP address

        // Not used
    
public voidsetRemoteHost(java.lang.String remoteHost)
Set the fully qualified name of the remote client associated with this Request.

param
remoteHost The remote host name

        // Not used
    
public voidsetRequestURI(java.lang.String uri)
Set the unparsed request URI for this Request. This will normally be called by the HTTP Connector, when it parses the request headers.

param
uri The request URI

        // Not used
    
public voidsetRequestedSessionCookie(boolean flag)
Set a flag indicating whether or not the requested session ID for this request came in through a cookie. This is normally called by the HTTP Connector, when it parses the request headers.

param
flag The new flag


        this.requestedSessionCookie = flag;

    
public voidsetRequestedSessionId(java.lang.String id)
Set the requested session ID for this request. This is normally called by the HTTP Connector, when it parses the request headers.

param
id The new session id


        this.requestedSessionId = id;

    
public voidsetRequestedSessionURL(boolean flag)
Set a flag indicating whether or not the requested session ID for this request came in through a URL. This is normally called by the HTTP Connector, when it parses the request headers.

param
flag The new flag


        this.requestedSessionURL = flag;

    
public voidsetResponse(org.apache.catalina.connector.Response response)
Set the Response with which this Request is associated.

param
response The new associated response

        this.response = response;
    
public voidsetScheme(java.lang.String scheme)
Set the name of the scheme associated with this request. Typical values are http, https, and ftp.

param
scheme The scheme

        // Not used
    
public voidsetSecure(boolean secure)
Set the value to be returned by isSecure() for this Request.

param
secure The new isSecure value

        this.secure = secure;
    
public voidsetServerName(java.lang.String name)
Set the name of the server (virtual host) to process this request.

param
name The server name

        coyoteRequest.serverName().setString(name);
    
public voidsetServerPort(int port)
Set the port number of the server to process this request.

param
port The server port

        coyoteRequest.setServerPort(port);
    
public voidsetServletPath(java.lang.String path)
Set the servlet path for this Request. This will normally be called when the associated Context is mapping the Request to a particular Wrapper.

param
path The servlet path

        if (path != null)
            mappingData.wrapperPath.setString(path);
    
public voidsetStream(java.io.InputStream stream)
Set the input stream associated with this Request.

param
stream The new input stream

        // Ignore
    
protected voidsetURIConverter(org.apache.tomcat.util.buf.B2CConverter URIConverter)
Set the URI converter.

param
URIConverter the new URI connverter

        this.URIConverter = URIConverter;
    
public voidsetUserPrincipal(java.security.Principal principal)
Set the Principal who has been authenticated for this Request. This value is also used to calculate the value to be returned by the getRemoteUser() method.

param
principal The user Principal


        if (Globals.IS_SECURITY_ENABLED){
            HttpSession session = getSession(false);
            if ( (subject != null) && 
                 (!subject.getPrincipals().contains(principal)) ){
                subject.getPrincipals().add(principal);         
            } else if (session != null &&
                        session.getAttribute(Globals.SUBJECT_ATTR) == null) {
                subject = new Subject();
                subject.getPrincipals().add(principal);         
            }
            if (session != null){
                session.setAttribute(Globals.SUBJECT_ATTR, subject);
            }
        } 

        this.userPrincipal = principal;
    
public voidsetWrapper(org.apache.catalina.Wrapper wrapper)
Set the Wrapper within which this Request is being processed. This must be called as soon as the appropriate Wrapper is identified, and before the Request is ultimately passed to an application servlet.

param
wrapper The newly associated Wrapper

        this.wrapper = wrapper;