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 static org.jboss.web.CatalinaMessages.MESSAGES;
 
 
 
Valve that implements the default basic behavior for the StandardHost container implementation.

USAGE CONSTRAINT: This implementation is likely to be useful only when processing HTTP requests.

Author(s):
Craig R. McClanahan
Remy Maucherat
Version:
$Revision: 1880 $ $Date: 2011-12-01 12:47:33 +0100 (Thu, 01 Dec 2011) $
 
 
 final class StandardHostValve
     extends ValveBase {
 
     // ----------------------------------------------------- Instance Variables
 

    
The descriptive information related to this implementation.
 
     private static final String info =
         "org.apache.catalina.core.StandardHostValve/1.0";
 
 
     // ------------------------------------------------------------- Properties
 

    
Return descriptive information about this Valve implementation.
 
     public String getInfo() {
 
         return ();
 
     }
 
 
     // --------------------------------------------------------- Public Methods
 

    
Select the appropriate child Context to process this request, based on the specified request URI. If no matching Context can be found, return an appropriate HTTP error.

Parameters:
request Request to be processed
response Response to be produced
valveContext Valve context used to forward to the next Valve
Throws:
java.io.IOException if an input/output error occurred
javax.servlet.ServletException if a servlet error occurred
 
    public final void invoke(Request requestResponse response)
        throws IOExceptionServletException {
        // Select the Context to be used for this Request
        Context context = request.getContext();
        if (context == null) {
            response.sendError
                (.,
                 .noContext());
            return;
        }
        // Bind the context CL to the current thread
        if (context.getLoader() != null) {
            Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
        }
        context.getThreadBindingListener().bind();
        // Enter application scope
        Object instances[] = context.getApplicationEventListeners();
        ServletRequestEvent event = null;
        if ((instances != null
                && (instances.length > 0)) {
            event = new ServletRequestEvent(context.getServletContext(), request.getRequest());
            // create pre-service event
            for (int i = 0; i < instances.lengthi++) {
                if (instances[i] == null)
                    continue;
                if (!(instances[iinstanceof ServletRequestListener))
                    continue;
                ServletRequestListener listener = (ServletRequestListenerinstances[i];
                try {
                    listener.requestInitialized(event);
                } catch (Throwable t) {
                    .getLogger().error(.requestListenerInitException(instances[i].getClass().getName()), t);
                    ServletRequest sreq = request.getRequest();
                    sreq.setAttribute(.t);
                    return;
                }
            }
        }
        // Ask this Context to process this request
        context.getPipeline().getFirst().invoke(requestresponse);
        // Access a session (if present) to update last accessed time, based on a
        // strict interpretation of the specification
        if (.) {
            request.getSession(false);
        }
        // Error page processing
        response.setSuspended(false);
        if (t != null) {
            throwable(requestresponset);
        } else {
            status(requestresponse);
        }
        // Exit application scope
        if ((instances !=null ) &&
                (instances.length > 0)) {
            // create post-service event
            for (int i = instances.length - 1; i >= 0; i--) {
                if (instances[i] == null)
                    continue;
                if (!(instances[iinstanceof ServletRequestListener))
                    continue;
                ServletRequestListener listener = (ServletRequestListenerinstances[i];
                try {
                    listener.requestDestroyed(event);
                } catch (Throwable t2) {
                    .getLogger().error(.requestListenerDestroyException(instances[i].getClass().getName()), t2);
                    ServletRequest sreq = request.getRequest();
                    sreq.setAttribute(.t2);
                }
            }
        }
        context.getThreadBindingListener().unbind();
        // Restore the context classloader
    }


    
Process Comet event.

Parameters:
request Request to be processed
response Response to be processed
event The event to be processed
Throws:
java.io.IOException if an input/output error occurred
javax.servlet.ServletException if a servlet error occurred
    public final void event(Request requestResponse responseHttpEvent event)
        throws IOExceptionServletException {
        // Select the Context to be used for this Request
        Context context = request.getContext();
        // Some regular callback events should be filtered out for Servlet 3 async
        if (request.getAsyncContext() != null) {
            Request.AsyncContextImpl asyncContext = (Request.AsyncContextImplrequest.getAsyncContext();
            if (event.getType() == . && asyncContext.getRunnable() == null 
                    && asyncContext.getPath() == null) {
                return;
            }
        }
        // Bind the context CL to the current thread
        if (context.getLoader() != null) {
            Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());
        }
        context.getThreadBindingListener().bind();
        // Enter application scope
        Object instances[] = context.getApplicationEventListeners();
        ServletRequestEvent event2 = null;
        if (instances != null && (instances.length > 0)) {
            event2 = new ServletRequestEvent(context.getServletContext(), request.getRequest());
            // create pre-service event
            for (int i = 0; i < instances.lengthi++) {
                if (instances[i] == null)
                    continue;
                if (!(instances[iinstanceof ServletRequestListener))
                    continue;
                ServletRequestListener listener = (ServletRequestListenerinstances[i];
                try {
                    listener.requestInitialized(event2);
                } catch (Throwable t) {
                    .getLogger().error(.requestListenerInitException(instances[i].getClass().getName()), t);
                    ServletRequest sreq = request.getRequest();
                    sreq.setAttribute(.t);
                    Thread.currentThread().setContextClassLoader(StandardHostValve.class.getClassLoader());
                    return;
                }
            }
        }
        // Ask this Context to process this request
        context.getPipeline().getFirst().event(requestresponseevent);
        // Access a session (if present) to update last accessed time, based on a
        // strict interpretation of the specification
        if (.) {
            request.getSession(false);
        }
        // Error page processing
        response.setSuspended(false);
        if (request.getAsyncContext() == null) {
            Throwable t = (Throwablerequest.getAttribute(.);
            if (t != null) {
                throwable(requestresponset);
            } else {
                status(requestresponse);
            }
        } else {
            Request.AsyncContextImpl asyncContext = (Request.AsyncContextImplrequest.getAsyncContext();
            if ((event.getType() == . || event.getType() == .)
                    && request.isEventMode() && asyncContext.getPath() == null) {
                Throwable t = (Throwablerequest.getAttribute(.);
                if (t != null) {
                    throwable(requestresponset);
                } else {
                    status(requestresponse);
                }
                // An error page (if any) must call complete or dispatch, if not the container calls complete
                if (request.isEventMode() && asyncContext.getPath() == null) {
                    asyncContext.complete();
                }
            }
        }
        // Exit application scope
        if (instances != null && (instances.length > 0)) {
            // create post-service event
            for (int i = instances.length - 1; i >= 0; i--) {
                if (instances[i] == null)
                    continue;
                if (!(instances[iinstanceof ServletRequestListener))
                    continue;
                ServletRequestListener listener = (ServletRequestListenerinstances[i];
                try {
                    listener.requestDestroyed(event2);
                } catch (Throwable t) {
                    .getLogger().error(.requestListenerDestroyException(instances[i].getClass().getName()), t);
                    ServletRequest sreq = request.getRequest();
                    sreq.setAttribute(.t);
                }
            }
        }
        context.getThreadBindingListener().unbind();
        // Restore the context classloader
    }
    // ------------------------------------------------------ Protected Methods


    
Handle the specified Throwable encountered while processing the specified Request to produce the specified Response. Any exceptions that occur during generation of the exception report are logged and swallowed.

Parameters:
request The request being processed
response The response being generated
throwable The exception that occurred (which possibly wraps a root cause exception
    protected void throwable(Request requestResponse response,
                             Throwable throwable) {
        Context context = request.getContext();
        if (context == null)
            return;
        Throwable realError = throwable;
        if (realError instanceof ServletException) {
            realError = ((ServletExceptionrealError).getRootCause();
            if (realError == null) {
                realError = throwable;
            }
        }
        // If this is an aborted request from a client just log it and return
        if (realError instanceof ClientAbortException ) {
            ..clientAbortException(realError.getCause().getMessage());
            return;
        }
        ErrorPage errorPage = findErrorPage(contextthrowable);
        if ((errorPage == null) && (realError != throwable)) {
            errorPage = findErrorPage(contextrealError);
        }
        if (errorPage != null) {
            response.setAppCommitted(false);
            request.setAttribute
                 errorPage.getLocation());
                    .);
            request.setAttribute
                (.,
                        Integer.valueOf(.));
            request.setAttribute(.,
                              throwable.getMessage());
            request.setAttribute(.,
                              realError);
            Wrapper wrapper = request.getWrapper();
            if (wrapper != null)
                request.setAttribute(.,
                                  wrapper.getName());
            request.setAttribute(.,
                                 request.getRequestURI());
            request.setAttribute(.,
                              realError.getClass());
            if (custom(requestresponseerrorPage)) {
                try {
                    response.flushBuffer();
                } catch (ClientAbortException e) {
                    // Ignore
                } catch (IOException e) {
                    .getLogger().warn(.errorProcessingErrorPage(errorPage.getLocation()), e);
                }
            }
        } else {
            // A custom error-page has not been defined for the exception
            // that was thrown during request processing. Check if an
            // error-page for error code 500 was specified and if so,
            // send that page back as the response.
            response.setStatus(.);
            // The response is an error
            response.setError();
            status(requestresponse);
        }
    }


    
Handle the HTTP status code (and corresponding message) generated while processing the specified Request to produce the specified Response. Any exceptions that occur during generation of the error report are logged and swallowed.

Parameters:
request The request being processed
response The response being generated
    protected void status(Request requestResponse response) {
        int statusCode = response.getStatus();
        // Handle a custom error page for this status code
        Context context = request.getContext();
        if (context == null)
            return;
        /* Only look for error pages when isError() is set.
         * isError() is set when response.sendError() is invoked. This
         * allows custom error pages without relying on default from
         * web.xml.
         */
        if (!response.isError())
            return;
        ErrorPage errorPage = context.findErrorPage(statusCode);
        if (errorPage == null) {
            // Look for a default error page
            errorPage = context.findErrorPage(0);
        }
        if (errorPage != null) {
            response.setAppCommitted(false);
            request.setAttribute(.,
                              Integer.valueOf(statusCode));
            String message = response.getMessage();
            if (message == null)
                message = "";
            request.setAttribute(.message);
            request.setAttribute
                 errorPage.getLocation());
                    .);
            Wrapper wrapper = request.getWrapper();
            if (wrapper != null)
                request.setAttribute(.,
                                  wrapper.getName());
            request.setAttribute(.,
                                 request.getRequestURI());
            if (custom(requestresponseerrorPage)) {
                try {
                    response.flushBuffer();
                } catch (ClientAbortException e) {
                    // Ignore
                } catch (IOException e) {
                    .getLogger().warn(.errorProcessingErrorPage(errorPage.getLocation()), e);
                }
            }
        }
    }


    
Find and return the ErrorPage instance for the specified exception's class, or an ErrorPage instance for the closest superclass for which there is such a definition. If no associated ErrorPage instance is found, return null.

Parameters:
context The Context in which to search
exception The exception for which to find an ErrorPage
    protected static ErrorPage findErrorPage
        (Context contextThrowable exception) {
        if (exception == null)
            return (null);
        Class<?> clazz = exception.getClass();
        String name = clazz.getName();
        while (!Object.class.equals(clazz)) {
            ErrorPage errorPage = context.findErrorPage(name);
            if (errorPage != null)
                return (errorPage);
            clazz = clazz.getSuperclass();
            if (clazz == null)
                break;
            name = clazz.getName();
        }
        return (null);
    }


    
Handle an HTTP status code or Java exception by forwarding control to the location included in the specified errorPage object. It is assumed that the caller has already recorded any request attributes that are to be forwarded to this page. Return true if we successfully utilized the specified error page location, or false if the default error report should be rendered.

Parameters:
request The request being processed
response The response being generated
errorPage The errorPage directive we are obeying
    protected boolean custom(Request requestResponse response,
                             ErrorPage errorPage) {
        if (.getLogger().isDebugEnabled())
            .getLogger().debug("Processing " + errorPage);
        request.setPathInfo(errorPage.getLocation());
        try {
            // Reset the response (keeping the real error code and message)
            response.resetBuffer(true);
            response.setContentLength(-1);
            // Forward control to the specified location
            ServletContext servletContext =
                request.getContext().getServletContext();
            RequestDispatcher rd =
                servletContext.getRequestDispatcher(errorPage.getLocation());
            rd.forward(request.getRequest(), response.getResponse());
            // If we forward, the response is suspended again
            response.setSuspended(false);
            // Indicate that we have successfully processed this custom page
            return (true);
        } catch (Throwable t) {
            // Report our failure to process this custom page
            .getLogger().error(.errorProcessingErrorPage(errorPage.getLocation()), t);
            return (false);
        }
    }
New to GrepCode? Check out our FAQ X