Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2012 Red Hat, Inc., and individual contributors
   * as indicated by the @author tags.
   *
   * Licensed 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 StandardWrapper container implementation.

Author(s):
Craig R. McClanahan
Version:
$Revision: 2040 $ $Date: 2012-06-07 15:48:42 +0200 (Thu, 07 Jun 2012) $
 
 
 final class StandardWrapperValve
     extends ValveBase {
 
     
     protected static final boolean SERVLET_STATS = 
         || Boolean.valueOf(System.getProperty("org.apache.catalina.core.StandardWrapperValve.SERVLET_STATS""false")).booleanValue();
 
 
     // ----------------------------------------------------- Instance Variables
 
 
     // Some JMX statistics. This vavle is associated with a StandardWrapper.
     // We expose the StandardWrapper as JMX ( j2eeType=Servlet ). The fields
     // are here for performance.
     private volatile long processingTime;
     private volatile long maxTime;
     private volatile long minTime = .;
     private volatile int eventCount;
     private volatile int requestCount;
     private volatile int errorCount;
     private InstanceSupport support;
 
 
     // --------------------------------------------------------- Public Methods
 
 
     public void setContainer(Container container) {
         super.setContainer(container);
         if (container instanceof Wrapper) {
              = ((Wrappercontainer).getInstanceSupport();
         }
         if ( == null) {
             throw .missingInstanceSupport(container.getName());
         }
     }
    
    
Invoke the servlet we are managing, respecting the rules regarding servlet lifecycle and SingleThreadModel support.

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 {
        // Initialize local variables we may need
        boolean unavailable = false;
        Throwable throwable = null;
        // This should be a Request attribute...
        long t1 = 0;
        if () {
            t1 = System.currentTimeMillis();
            ++;
        }
        StandardWrapper wrapper = (StandardWrappergetContainer();
        Servlet servlet = null;
        Context context = (Contextwrapper.getParent();
        
        // Check for the application being marked unavailable
        if (!context.getAvailable()) {
                           .unavailable());
            unavailable = true;
        }
        // Check for the servlet being marked unavailable
        if (!unavailable && wrapper.isUnavailable()) {
            .getLogger().info(.servletIsUnavailable(wrapper.getName()));
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < .)) {
                response.setDateHeader("Retry-After"available);
                response.sendError(.,
                        .servletIsUnavailable(wrapper.getName()));
            } else if (available == .) {
                response.sendError(.,
                        .servletIsUnavailable(wrapper.getName()));
            }
            unavailable = true;
        }
        // Allocate a servlet instance to process this request
        try {
            if (!unavailable) {
                servlet = wrapper.allocate();
            }
        } catch (UnavailableException e) {
            .getLogger().error(.servletAllocateException(wrapper.getName()), e);
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < .)) {
            	response.setDateHeader("Retry-After"available);
            	response.sendError(.,
            	        .servletIsUnavailable(wrapper.getName()));
            } else if (available == .) {
            	response.sendError(.,
            	        .servletIsUnavailable(wrapper.getName()));
            }
        } catch (ServletException e) {
            .getLogger().error(.servletAllocateException(wrapper.getName()), StandardWrapper.getRootCause(e));
            throwable = e;
            exception(requestresponsee);
            servlet = null;
        } catch (Throwable e) {
            .getLogger().error(.servletAllocateException(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
            servlet = null;
        }
        // Identify if the request should be switched to event mode now that 
        // the servlet has been allocated
        boolean event = false;
        if (servlet instanceof HttpEventServlet 
                && request.getConnector().hasIoEvents()) {
            event = true;
            request.setEventMode(true);
        }
        
        // Acknowledge the request
        try {
            response.sendAcknowledgement();
        } catch (IOException e) {
        	request.removeAttribute(.);
            .getLogger().warn(.errorAcknowledgingRequest(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
        } catch (Throwable e) {
            .getLogger().error(.errorAcknowledgingRequest(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
            servlet = null;
        }
        request.setAttribute
             .);
        request.setAttribute
                    request.getRequestPathMB());
        // Create the filter chain for this request
        ApplicationFilterFactory factory =
            ApplicationFilterFactory.getInstance();
        ApplicationFilterChain filterChain =
            factory.createFilterChain(requestwrapperservlet);
        // Reset event flag value after creating the filter chain
        request.setEventMode(false);
        // Call the filter chain for this request
        // NOTE: This also calls the servlet's service() method
        String jspFile = wrapper.getJspFile();
        try {
            if (jspFile != null) {
            	request.setAttribute(.jspFile);
            } else {
            	request.removeAttribute(.);
            }
                    servletrequestresponse);
            if ((servlet != null) && (filterChain != null)) {
                if (event) {
                    request.setEventMode(true);
                    request.getSession(true);
                    filterChain.doFilterEvent(request.getEvent());
                } else {
                    filterChain.doFilter
                    (request.getRequest(), response.getResponse());
                }
            }
        } catch (ClientAbortException e) {
            throwable = e;
            exception(requestresponsee);
        } catch (IOException e) {
            .getLogger().error(.servletServiceException(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
        } catch (UnavailableException e) {
            .getLogger().error(.servletServiceException(wrapper.getName()), e);
            //            throwable = e;
            //            exception(request, response, e);
            wrapper.unavailable(e);
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < .)) {
                response.setDateHeader("Retry-After"available);
                response.sendError(.,
                        .servletIsUnavailable(wrapper.getName()));
            } else if (available == .) {
            	response.sendError(.,
            	        .servletIsUnavailable(wrapper.getName()));
            }
            // Do not save exception in 'throwable', because we
            // do not want to do exception(request, response, e) processing
        } catch (ServletException e) {
            Throwable rootCause = StandardWrapper.getRootCause(e);
            if (!(rootCause instanceof ClientAbortException)) {
                .getLogger().error(.servletServiceException(wrapper.getName()), rootCause);
            }
            throwable = e;
            exception(requestresponsee);
        } catch (Throwable e) {
            .getLogger().error(.servletServiceException(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
        } finally {
            if (jspFile != null) {
                request.removeAttribute(.);
            }
                    servletrequestresponsethrowable);
        }
        // Release the filter chain (if any) for this request
        if (filterChain != null) {
            if (request.isEventMode() && !request.isAsyncStarted()) {
                // If this is a event request, then the same chain will be used for the
                // processing of all subsequent events.
                filterChain.reuse();
            } else {
                filterChain.release();
            }
        }
        // Deallocate the allocated servlet instance
        try {
            if (servlet != null) {
                wrapper.deallocate(servlet);
            }
        } catch (Throwable e) {
            .getLogger().error(.servletDeallocateException(wrapper.getName()), e);
            if (throwable == null) {
                throwable = e;
                exception(requestresponsee);
            }
        }
        // If this servlet has been marked permanently unavailable,
        // unload it and release this instance
        try {
            if ((servlet != null) &&
                (wrapper.getAvailable() == .)) {
                wrapper.unload();
            }
        } catch (Throwable e) {
            .getLogger().error(.errorUnloadingServlet(wrapper.getName()), e);
            if (throwable == null) {
                throwable = e;
                exception(requestresponsee);
            }
        }
        if () {
            long time = System.currentTimeMillis() - t1;
             += time;
            if (time > ) {
                 = time;
            }
            if (time < ) {
                 = time;
            }
        }
    }


    
Process an event. The main differences here are to not use sendError (the response is committed), to avoid creating a new filter chain (which would work but be pointless), and a few very minor tweaks.

Parameters:
request The servlet request to be processed
response The servlet response to be created
event The event to be processed
Throws:
java.io.IOException if an input/output error occurs, or is thrown by a subsequently invoked Valve, Filter, or Servlet
javax.servlet.ServletException if a servlet error occurs, or is thrown by a subsequently invoked Valve, Filter, or Servlet
    public void event(Request requestResponse responseHttpEvent event)
        throws IOExceptionServletException {
        
        // Async processing
        AsyncContext asyncContext = request.getAsyncContext();
        if (asyncContext != null) {
            async(requestresponseevent);
            return;
        }
        
        // Initialize local variables we may need
        Throwable throwable = null;
        // This should be a Request attribute...
        long t1 = 0;
        if () {
            t1 = System.currentTimeMillis();
            ++;
        }
        StandardWrapper wrapper = (StandardWrappergetContainer();
        Servlet servlet = null;
        Context context = (Contextwrapper.getParent();
        // Check for the application being marked unavailable
        boolean unavailable = !context.getAvailable() || wrapper.isUnavailable();
        
        // Allocate a servlet instance to process this request
        try {
            if (!unavailable) {
                servlet = wrapper.allocate();
            }
        } catch (UnavailableException e) {
            // The response is already committed, so it's not possible to do anything
        } catch (ServletException e) {
            .getLogger().error(.servletAllocateException(wrapper.getName()), StandardWrapper.getRootCause(e));
            throwable = e;
            exception(requestresponsee);
            servlet = null;
        } catch (Throwable e) {
            .getLogger().error(.servletAllocateException(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
            servlet = null;
        }
        request.setAttribute
             .);
        request.setAttribute
                    request.getRequestPathMB());
        
        // Get the current (unchanged) filter chain for this request
        ApplicationFilterChain filterChain = 
            (ApplicationFilterChainrequest.getFilterChain();
        // Call the filter chain for this request
        // NOTE: This also calls the servlet's event() method
        String jspFile = wrapper.getJspFile();
        try {
            if (jspFile != null) {
                request.setAttribute(.jspFile);
            } else {
                request.removeAttribute(.);
            }
                    servletrequestresponse);
            if ((servlet != null) && (filterChain != null)) {
                filterChain.doFilterEvent(request.getEvent());
            }
        } catch (ClientAbortException e) {
            throwable = e;
            exception(requestresponsee);
        } catch (IOException e) {
            .getLogger().error(.servletServiceException(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
        } catch (UnavailableException e) {
            .getLogger().error(.servletServiceException(wrapper.getName()), e);
            // Do not save exception in 'throwable', because we
            // do not want to do exception(request, response, e) processing
        } catch (ServletException e) {
            Throwable rootCause = StandardWrapper.getRootCause(e);
            if (!(rootCause instanceof ClientAbortException)) {
                .getLogger().error(.servletServiceException(wrapper.getName()), rootCause);
            }
            throwable = e;
            exception(requestresponsee);
        } catch (Throwable e) {
            .getLogger().error(.servletServiceException(wrapper.getName()), e);
            throwable = e;
            exception(requestresponsee);
        } finally {
            if (jspFile != null) {
                request.removeAttribute(.);
            }
                    servletrequestresponsethrowable);
        }
        // Release the filter chain (if any) for this request
        if (filterChain != null) {
            if (request.isAsyncStarted()) {
                filterChain.release();
            } else {
                filterChain.reuse();
            }
        }
        // Deallocate the allocated servlet instance
        try {
            if (servlet != null) {
                wrapper.deallocate(servlet);
            }
        } catch (Throwable e) {
            .getLogger().error(.servletDeallocateException(wrapper.getName()), e);
            if (throwable == null) {
                throwable = e;
                exception(requestresponsee);
            }
        }
        // If this servlet has been marked permanently unavailable,
        // unload it and release this instance
        try {
            if ((servlet != null) &&
                (wrapper.getAvailable() == .)) {
                wrapper.unload();
            }
        } catch (Throwable e) {
            .getLogger().error(.errorUnloadingServlet(wrapper.getName()), e);
            if (throwable == null) {
                throwable = e;
                exception(requestresponsee);
            }
        }
        if () {
            long time = System.currentTimeMillis() - t1;
             += time;
            if (time > ) {
                 = time;
            }
            if (time < ) {
                 = time;
            }
        }
    }


    
Process an async dispatch. This is never a direct wrapper invocation.

Parameters:
request The servlet request to be processed
response The servlet response to be processed
event The event to be processed
Throws:
java.io.IOException if an input/output error occurs, or is thrown by a subsequently invoked Valve, Filter, or Servlet
javax.servlet.ServletException if a servlet error occurs, or is thrown by a subsequently invoked Valve, Filter, or Servlet
    public void async(Request requestResponse responseHttpEvent event)
        throws IOExceptionServletException {
        
        Request.AsyncContextImpl asyncContext = (Request.AsyncContextImplrequest.getAsyncContext();
        if (asyncContext != null) {
            if (event.getType() == . || event.getType() == .
                    || event.getType() == .) {
                // Invoke the listeners with onComplete or onTimeout
                boolean timeout = (event.getType() == .);
                boolean error = (event.getType() == .);
                Iterator<AsyncListenerRegistrationasyncListenerRegistrations = 
                    asyncContext.getAsyncListeners().values().iterator();
                while (asyncListenerRegistrations.hasNext()) {
                    AsyncListenerRegistration asyncListenerRegistration = asyncListenerRegistrations.next();
                    AsyncListener asyncListener = asyncListenerRegistration.getListener();
                    try {
                        if (timeout) {
                            AsyncEvent asyncEvent = new AsyncEvent(asyncContext
                                    asyncListenerRegistration.getRequest(), asyncListenerRegistration.getResponse());
                            asyncListener.onTimeout(asyncEvent);
                        } else if (error) {
                            AsyncEvent asyncEvent = new AsyncEvent(asyncContext
                                    asyncListenerRegistration.getRequest(), asyncListenerRegistration.getResponse(), asyncContext.getError());
                            asyncListener.onError(asyncEvent);
                        } else {
                            AsyncEvent asyncEvent = new AsyncEvent(asyncContext
                                    asyncListenerRegistration.getRequest(), asyncListenerRegistration.getResponse());
                            asyncListener.onComplete(asyncEvent);
                        }
                    } catch (Throwable e) {
                        .getLogger().error(.asyncListenerError(getContainer().getName()), e);
                        exception(requestresponsee);
                    }
                }
                boolean end = (event.getType() == .) || error;
                if (timeout && request.isEventMode() && asyncContext.getPath() == null) {
                    response.setStatus(.);
                    end = true;
                }
                try {
                    // Call error notifications for IO listeners
                    if (error) {
                        Throwable throwable = asyncContext.getError();
                        if (throwable == null) {
                            throwable = response.getCoyoteResponse().getErrorException();
                            if (throwable != null){
                                if (!(throwable instanceof IOException)) {
                                    throwable = new IOException(throwable);
                                }
                            } else {
                                throwable = new EOFException();
                            }
                        }
                        if (request.getReadListener() != null) { 
                            request.getReadListener().onError(throwable);
                        }
                        if (response.getWriteListener() != null) {
                            response.getWriteListener().onError(throwable);
                        }
                    }
                } catch (Throwable e) {
                    .getLogger().error(.ioListenerError(getContainer().getName()), e);
                    exception(requestresponsee);
                }
                if (end && (request.getUpgradeHandler() != null)) {
                    try {
                        // FIXME: Examine if need to call elsewhere
                        request.getUpgradeHandler().destroy();
                    } catch (Throwable e) {
                        .getLogger().error(.upgradeHandlerDestroyError(getContainer().getName()), e);
                        exception(requestresponsee);
                    }
                }
                if (error && request.isEventMode() && asyncContext.getPath() == null) {
                    exception(requestresponseasyncContext.getError());
                }
            } else if (event.getType() == .) {
                // Read notification
                if (request.getReadListener() != null) {
                    try {
                        request.getReadListener().onDataAvailable();
                    } catch (Throwable e) {
                        .getLogger().error(.ioListenerError(getContainer().getName()), e);
                        exception(requestresponsee);
                    }
                }
            } else if (event.getType() == .) {
                // End of stream notification
                if (request.getReadListener() != null) {
                    try {
                        request.getReadListener().onAllDataRead();
                    } catch (Throwable e) {
                        .getLogger().error(.ioListenerError(getContainer().getName()), e);
                        exception(requestresponsee);
                    }
                }
            } else if (event.getType() == .) {
                // Write notification
                if (response.getWriteListener() != null) {
                    try {
                        response.getWriteListener().onWritePossible();
                    } catch (Throwable e) {
                        .getLogger().error(.ioListenerError(getContainer().getName()), e);
                        exception(requestresponsee);
                    }
                }
            } else if (asyncContext.getRunnable() != null) {
                // Execute the runnable
                try {
                    asyncContext.runRunnable().run();
                } catch (Throwable e) {
                    .getLogger().error(.asyncRunnableError(getContainer().getName()), e);
                    asyncContext.setError(e);
                }
            } else if (asyncContext.getPath() != null) {
                // We executed the dispatch
                asyncContext.done();
                // Remap the request, set the dispatch attributes, create the filter chain
                // and invoke the Servlet
                Context context = (ContextgetContainer().getParent();
                ServletContext servletContext = context.getServletContext();
                if (asyncContext.getServletContext() != null) {
                    // Cross context
                    servletContext = asyncContext.getServletContext();
                }
                request.setCanStartAsync(true);
                ApplicationDispatcher dispatcher = 
                    (ApplicationDispatcherservletContext.getRequestDispatcher(asyncContext.getPath());
                // Invoke the dispatcher async method with the attributes flag
                try {
                    dispatcher.async(asyncContext.getRequest(), asyncContext.getResponse(), 
                            asyncContext.getUseAttributes());
                } catch (Throwable e) {
                    .getLogger().error(.asyncDispatchError(getContainer().getName()), e);
                    asyncContext.setError(e);
                }
                request.setCanStartAsync(false);
                // If there is no new startAsync, then close the response
                // Note: The spec uses the same asyncContext instance
                if (!asyncContext.isReady()) {
                    asyncContext.complete();
                }
            }
        }
    }
        
    // -------------------------------------------------------- Private Methods


    
Handle the specified ServletException 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
exception The exception that occurred (which possibly wraps a root cause exception
    private void exception(Request requestResponse response,
                           Throwable exception) {
    	request.setAttribute(.exception);
    }
    public long getProcessingTime() {
        return ;
    }
    public void setProcessingTime(long processingTime) {
        this. = processingTime;
    }
    public long getMaxTime() {
        return ;
    }
    public void setMaxTime(long maxTime) {
        this. = maxTime;
    }
    public long getMinTime() {
        return ;
    }
    public void setMinTime(long minTime) {
        this. = minTime;
    }
    public int getRequestCount() {
        return ;
    }
    public void setRequestCount(int requestCount) {
        this. = requestCount;
    }
    public int getErrorCount() {
        return ;
    }
    public void setErrorCount(int errorCount) {
        this. = errorCount;
    }
    public int getEventCount() {
        return ;
    }
    public void setEventCount(int eventCount) {
        this. = eventCount;
    }
    // Don't register in JMX
    public ObjectName createObjectName(String domainObjectName parent)
            throws MalformedObjectNameException
    {
        return null;
    }
New to GrepCode? Check out our FAQ X