Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 
 package org.apache.catalina.core;
 
 
 import java.util.Map;
 
 
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(s):
Craig R. McClanahan
Remy Maucherat
Version:
$Revision: 1579 $ $Date: 2010-11-19 17:06:19 +0100 (Fri, 19 Nov 2010) $
 
 
 
 
     // ------------------------------------------------------- Static Variables
 

    
The set of attribute names that are special for request dispatchers.
 
     protected static final String specials[] =
         . };
 
 
     // ----------------------------------------------------------- Constructors
 

    
Construct a new wrapped request around the specified servlet request.

Parameters:
request The servlet request being wrapped
 
     public ApplicationHttpRequest(HttpServletRequest requestContext context,
                                   boolean crossContext) {
 
         super(request);
         this. = context;
         this. = crossContext;
         setRequest(request);
 
     }
 
    // ----------------------------------------------------- Instance Variables


    
The context for this request.
    protected Context context = null;
    
    
    
The context path for this request.
    protected String contextPath = null;


    
If this request is cross context, since this changes session accesss behavior.
    protected boolean crossContext = false;


    
The current dispatcher type.
    protected Object dispatcherType = null;


    
Descriptive information about this implementation.
    protected static final String info =
        "org.apache.catalina.core.ApplicationHttpRequest/1.0";


    
The request parameters for this request. This is initialized from the wrapped request, but updates are allowed.
    protected Map parameters = null;


    
Have the parameters for this request already been parsed?
    private boolean parsedParams = false;


    
The path information for this request.
    protected String pathInfo = null;


    
The query parameters for the current request.
    private String queryParamString = null;


    
The query string for this request.
    protected String queryString = null;


    
The current request dispatcher path.
    protected Object requestDispatcherPath = null;


    
The request URI for this request.
    protected String requestURI = null;


    
The servlet path for this request.
    protected String servletPath = null;


    
The currently active session for this request.
    protected Session session = null;


    
Special attributes.
    protected Object[] specialAttributes = new Object[.];
    // ------------------------------------------------- ServletRequest Methods


    
Override the getAttribute() method of the wrapped request.

Parameters:
name Name of the attribute to retrieve
    public Object getAttribute(String name) {
        if (name.equals(.)) {
            return ;
        } else if (name.equals(.)) {
            if (  != null ){
                return .toString();
            } else {
                return null;   
            }
        }
        int pos = getSpecial(name);
        if (pos == -1) {
            return getRequest().getAttribute(name);
        } else {
            if (([pos] == null
                && ([5] == null) && (pos >= 5)) {
                // 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 [pos];
            }
        }
    }
    public DispatcherType getDispatcherType() {
        if ( == null) {
            return .;
        } else if ( == .) {
            return .;
        } else if ( == .) {
            return .;
        } else if ( == .) {
            return .;
        } else if ( == .) {
            return .;
        } else if ( == .) {
            return .;
        }
        // Never happens
        throw new IllegalStateException();
    }


    
Override the getAttributeNames() method of the wrapped request.
    public Enumeration getAttributeNames() {
        return (new AttributeNamesEnumerator());
    }


    
Override the removeAttribute() method of the wrapped request.

Parameters:
name Name of the attribute to remove
    public void removeAttribute(String name) {
        if (!removeSpecial(name))
            getRequest().removeAttribute(name);
    }


    
Override the setAttribute() method of the wrapped request.

Parameters:
name Name of the attribute to set
value Value of the attribute to set
    public void setAttribute(String nameObject value) {
        if (name.equals(.)) {
             = value;
            return;
        } else if (name.equals(.)) {
             = value;
            return;
        }
        if (!setSpecial(namevalue)) {
            getRequest().setAttribute(namevalue);
        }
    }


    
Return a RequestDispatcher that wraps the resource at the specified path, which may be interpreted as relative to the current request path.

Parameters:
path Path of the resource to be wrapped
        if ( == null)
            return (null);
        // If the path is already context-relative, just pass it through
        if (path == null)
            return (null);
        else if (path.startsWith("/"))
            return (.getServletContext().getRequestDispatcher(path));
        // Convert a request-relative path to a context-relative one
        String servletPath = 
        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 = requestPath.substring(0, pos + 1) + path;
        } else {
            relative = requestPath + path;
        }
        return (.getServletContext().getRequestDispatcher(relative));
    }
    // --------------------------------------------- HttpServletRequest Methods


    
Override the getContextPath() method of the wrapped request.
    public String getContextPath() {
        return (this.);
    }


    
Override the getParameter() method of the wrapped request.

Parameters:
name Name of the requested parameter
    public String getParameter(String name) {
        Object value = .get(name);
        if (value == null)
            return (null);
        else if (value instanceof String[])
            return (((String[]) value)[0]);
        else if (value instanceof String)
            return ((Stringvalue);
        else
            return (value.toString());
    }


    
Override the getParameterMap() method of the wrapped request.
    public Map getParameterMap() {
        return ();
    }


    
Override the getParameterNames() method of the wrapped request.
    public Enumeration getParameterNames() {
        return (new Enumerator(.keySet()));
    }


    
Override the getParameterValues() method of the wrapped request.

Parameters:
name Name of the requested parameter
    public String[] getParameterValues(String name) {
        Object value = .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] = (Stringvalue;
            return (values);
        } else {
            String values[] = new String[1];
            values[0] = value.toString();
            return (values);
        }
    }


    
Override the getPathInfo() method of the wrapped request.
    public String getPathInfo() {
        return (this.);
    }


    
Override the getQueryString() method of the wrapped request.
    public String getQueryString() {
        return (this.);
    }


    
Override the getRequestURI() method of the wrapped request.
    public String getRequestURI() {
        return (this.);
    }


    
Override the getRequestURL() method of the wrapped request.
    public StringBuffer getRequestURL() {
        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);
    }


    
Override the getServletPath() method of the wrapped request.
    public String getServletPath() {
        return (this.);
    }


    
Return the session associated with this Request, creating one if necessary.
    public HttpSession getSession() {
        return (getSession(true));
    }


    
Return the session associated with this Request, creating one if necessary and requested.

Parameters:
create Create a new session if one does not exist
    public HttpSession getSession(boolean create) {
        if () {
            
            // There cannot be a session if no context has been assigned yet
            if ( == null)
                return (null);
            // Return the current session if it exists and is valid
            if ( != null && .isValid()) {
                return (.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 {
                    localSession =
                        .getManager().findSession(other.getId());
                } catch (IOException e) {
                    // Ignore
                }
                if ((localSession != null) && !localSession.isValid())
                    localSession = null;
                if (localSession == null && create) {
                    localSession = 
                        .getManager().createSession(other.getId(), null);
                }
                if (localSession != null) {
                    localSession.access();
                     = localSession;
                    return .getSession();
                }
            }
            return null;
        } else {
            return super.getSession(create);
        }
    }


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

Returns:
true if the request specifies a JSESSIONID that is valid within the context of this ApplicationHttpRequest, false otherwise.
    public boolean isRequestedSessionIdValid() {
        if () {
            String requestedSessionId = getRequestedSessionId();
            if (requestedSessionId == null)
                return (false);
            if ( == null)
                return (false);
            Manager manager = .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);
            }
        } else {
            return super.isRequestedSessionIdValid();
        }
    }
    // -------------------------------------------------------- Package Methods


    
Recycle this request
    public void recycle() {
        if ( != null) {
            .endAccess();
        }
    }


    
Return descriptive information about this implementation.
    public String getInfo() {
        return ();
    }


    
Perform a shallow copy of the specified Map, and return the result.

Parameters:
orig Origin Map to be copied
    Map<StringString[]> copyMap(Map<StringString[]> orig) {
        if (orig == null)
            return (new HashMap<StringString[]>());
        HashMap<StringString[]> dest = new HashMap<StringString[]>();
        
        for (Map.Entry<StringString[]> entry : orig.entrySet()) {
            dest.put(entry.getKey(), entry.getValue());
        }
        return (dest);
    }


    
Set the context path for this request.

Parameters:
contextPath The new context path
    void setContextPath(String contextPath) {
        this. = contextPath;
    }


    
Set the path information for this request.

Parameters:
pathInfo The new path info
    void setPathInfo(String pathInfo) {
        this. = pathInfo;
    }


    
Set the query string for this request.

Parameters:
queryString The new query string
    void setQueryString(String queryString) {
        this. = queryString;
    }


    
Set the request that we are wrapping.

Parameters:
request The new wrapped request
    void setRequest(HttpServletRequest request) {
        super.setRequest(request);
        // Initialize the attributes for this request
         = 
            request.getAttribute(.);
        // Initialize the path elements for this request
         = request.getContextPath();
         = request.getPathInfo();
         = request.getQueryString();
         = request.getRequestURI();
         = request.getServletPath();
    }


    
Set the request URI for this request.

Parameters:
requestURI The new request URI
    void setRequestURI(String requestURI) {
        this. = requestURI;
    }


    
Set the servlet path for this request.

Parameters:
servletPath The new servlet path
    void setServletPath(String servletPath) {
        this. = servletPath;
    }


    
Parses the parameters of this request. If parameters are present in both the query string and the request content, they are merged.
    void parseParameters() {
	if () {
	    return;
	}
         = new HashMap();
        mergeParameters();
         = true;
    }


    
Save query parameters for this request.

Parameters:
queryString The query string containing parameters for this request
    void setQueryParams(String queryString) {
        this. = queryString;
    }
    // ------------------------------------------------------ Protected Methods


    
Is this attribute name one of the special ones that is added only for included servlets?

Parameters:
name Attribute name to be tested
    protected boolean isSpecial(String name) {
        for (int i = 0; i < .i++) {
            if ([i].equals(name))
                return (true);
        }
        return (false);
    }


    
Get a special attribute.

Returns:
the special attribute pos, or -1 if it is not a special attribute
    protected int getSpecial(String name) {
        for (int i = 0; i < .i++) {
            if ([i].equals(name)) {
                return (i);
            }
        }
        return (-1);
    }


    
Set a special attribute.

Returns:
true if the attribute was a special attribute, false otherwise
    protected boolean setSpecial(String nameObject value) {
        for (int i = 0; i < .i++) {
            if ([i].equals(name)) {
                [i] = value;
                return (true);
            }
        }
        return (false);
    }


    
Remove a special attribute.

Returns:
true if the attribute was a special attribute, false otherwise
    protected boolean removeSpecial(String name) {
        for (int i = 0; i < .i++) {
            if ([i].equals(name)) {
                [i] = null;
                return (true);
            }
        }
        return (false);
    }


    
Merge the two sets of parameter values into a single String array.

Parameters:
values1 First set of values
values2 Second set of values
    protected String[] mergeValues(Object values1Object values2) {
        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.lengthi++)
                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.lengthi++)
                results.add(values[i]);
        } else
            results.add(values2.toString());
        String values[] = new String[results.size()];
        return ((String[]) results.toArray(values));
    }
    // ------------------------------------------------------ Private Methods


    
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.
    private void mergeParameters() {
        if (( == null) || (.length() < 1))
            return;
        HashMap queryParameters = new HashMap();
        String encoding = getCharacterEncoding();
        if (encoding == null)
            encoding = "ISO-8859-1";
        try {
            RequestUtil.parseParameters
                (queryParametersencoding);
        } catch (Exception e) {
            ;
        }
        Iterator keys = .keySet().iterator();
        while (keys.hasNext()) {
            String key = (Stringkeys.next();
            Object value = queryParameters.get(key);
            if (value == null) {
                queryParameters.put(key.get(key));
                continue;
            }
            queryParameters.put
                (keymergeValues(value.get(key)));
        }
         = queryParameters;
    }
    // ----------------------------------- AttributeNamesEnumerator Inner Class


    
Utility class used to expose the special attributes as being available as request attributes.
    protected class AttributeNamesEnumerator implements Enumeration {
        protected int pos = -1;
        protected int last = -1;
        protected Enumeration parentEnumeration = null;
        protected String next = null;
        public AttributeNamesEnumerator() {
             = getRequest().getAttributeNames();
            for (int i = 0; i < .i++) {
                if (getAttribute([i]) != null) {
                     = i;
                }
            }
        }
        public boolean hasMoreElements() {
            return (( != ) || ( != null
                    || (( = findNext()) != null));
        }
        public Object nextElement() {
            if ( != ) {
                for (int i =  + 1; i <= i++) {
                    if (getAttribute([i]) != null) {
                         = i;
                        return ([i]);
                    }
                }
            }
            String result = ;
            if ( != null) {
                 = findNext();
            } else {
                throw new NoSuchElementException();
            }
            return result;
        }
        protected String findNext() {
            String result = null;
            while ((result == null) && (.hasMoreElements())) {
                String current = (String.nextElement();
                if (!isSpecial(current)) {
                    result = current;
                }
            }
            return result;
        }
    }
New to GrepCode? Check out our FAQ X