Save This Page
Home » apache-tomcat-6.0.16-src » org.apache » catalina » core » [javadoc | source]
    1   /*
    2    * Licensed to the Apache Software Foundation (ASF) under one or more
    3    * contributor license agreements.  See the NOTICE file distributed with
    4    * this work for additional information regarding copyright ownership.
    5    * The ASF licenses this file to You under the Apache License, Version 2.0
    6    * (the "License"); you may not use this file except in compliance with
    7    * the License.  You may obtain a copy of the License at
    8    * 
    9    *      http://www.apache.org/licenses/LICENSE-2.0
   10    * 
   11    * Unless required by applicable law or agreed to in writing, software
   12    * distributed under the License is distributed on an "AS IS" BASIS,
   13    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   14    * See the License for the specific language governing permissions and
   15    * limitations under the License.
   16    */
   17   
   18   
   19   package org.apache.catalina.core;
   20   
   21   import java.io.IOException;
   22   import java.io.PrintWriter;
   23   import java.security.AccessController;
   24   import java.security.PrivilegedActionException;
   25   import java.security.PrivilegedExceptionAction;
   26   
   27   import javax.servlet.RequestDispatcher;
   28   import javax.servlet.Servlet;
   29   import javax.servlet.ServletException;
   30   import javax.servlet.ServletOutputStream;
   31   import javax.servlet.ServletRequest;
   32   import javax.servlet.ServletRequestWrapper;
   33   import javax.servlet.ServletResponse;
   34   import javax.servlet.ServletResponseWrapper;
   35   import javax.servlet.UnavailableException;
   36   import javax.servlet.http.HttpServletRequest;
   37   import javax.servlet.http.HttpServletResponse;
   38   
   39   import org.apache.catalina.Context;
   40   import org.apache.catalina.Globals;
   41   import org.apache.catalina.InstanceEvent;
   42   import org.apache.catalina.Wrapper;
   43   import org.apache.catalina.connector.ClientAbortException;
   44   import org.apache.catalina.connector.Request;
   45   import org.apache.catalina.connector.RequestFacade;
   46   import org.apache.catalina.connector.Response;
   47   import org.apache.catalina.connector.ResponseFacade;
   48   import org.apache.catalina.util.InstanceSupport;
   49   import org.apache.catalina.util.StringManager;
   50   
   51   /**
   52    * Standard implementation of <code>RequestDispatcher</code> that allows a
   53    * request to be forwarded to a different resource to create the ultimate
   54    * response, or to include the output of another resource in the response
   55    * from this resource.  This implementation allows application level servlets
   56    * to wrap the request and/or response objects that are passed on to the
   57    * called resource, as long as the wrapping classes extend
   58    * <code>javax.servlet.ServletRequestWrapper</code> and
   59    * <code>javax.servlet.ServletResponseWrapper</code>.
   60    *
   61    * @author Craig R. McClanahan
   62    * @version $Revision: 588477 $ $Date: 2007-10-26 04:37:39 +0200 (ven., 26 oct. 2007) $
   63    */
   64   
   65   final class ApplicationDispatcher
   66       implements RequestDispatcher {
   67   
   68   
   69       protected class PrivilegedForward implements PrivilegedExceptionAction {
   70           private ServletRequest request;
   71           private ServletResponse response;
   72   
   73           PrivilegedForward(ServletRequest request, ServletResponse response)
   74           {
   75               this.request = request;
   76               this.response = response;
   77           }
   78   
   79           public Object run() throws java.lang.Exception {
   80               doForward(request,response);
   81               return null;
   82           }
   83       }
   84   
   85       protected class PrivilegedInclude implements PrivilegedExceptionAction {
   86           private ServletRequest request;
   87           private ServletResponse response;
   88   
   89           PrivilegedInclude(ServletRequest request, ServletResponse response)
   90           {
   91               this.request = request;
   92               this.response = response;
   93           }
   94   
   95           public Object run() throws ServletException, IOException {
   96               doInclude(request,response);
   97               return null;
   98           }
   99       }
  100   
  101       
  102       /**
  103        * Used to pass state when the request dispatcher is used. Using instance
  104        * variables causes threading issues and state is too complex to pass and
  105        * return single ServletRequest or ServletResponse objects.
  106        */
  107       private class State {
  108           State(ServletRequest request, ServletResponse response,
  109                   boolean including) {
  110               this.outerRequest = request;
  111               this.outerResponse = response;
  112               this.including = including;
  113           }
  114   
  115           /**
  116            * The outermost request that will be passed on to the invoked servlet.
  117            */
  118           ServletRequest outerRequest = null;
  119   
  120   
  121           /**
  122            * The outermost response that will be passed on to the invoked servlet.
  123            */
  124           ServletResponse outerResponse = null;
  125           
  126           /**
  127            * The request wrapper we have created and installed (if any).
  128            */
  129           ServletRequest wrapRequest = null;
  130   
  131   
  132           /**
  133            * The response wrapper we have created and installed (if any).
  134            */
  135           ServletResponse wrapResponse = null;
  136           
  137           /**
  138            * Are we performing an include() instead of a forward()?
  139            */
  140           boolean including = false;
  141   
  142           /**
  143            * Outer most HttpServletRequest in the chain
  144            */
  145           HttpServletRequest hrequest = null;
  146   
  147           /**
  148            * Outermost HttpServletResponse in the chain
  149            */
  150           HttpServletResponse hresponse = null;
  151       }
  152   
  153       // ----------------------------------------------------------- Constructors
  154   
  155   
  156       /**
  157        * Construct a new instance of this class, configured according to the
  158        * specified parameters.  If both servletPath and pathInfo are
  159        * <code>null</code>, it will be assumed that this RequestDispatcher
  160        * was acquired by name, rather than by path.
  161        *
  162        * @param wrapper The Wrapper associated with the resource that will
  163        *  be forwarded to or included (required)
  164        * @param requestURI The request URI to this resource (if any)
  165        * @param servletPath The revised servlet path to this resource (if any)
  166        * @param pathInfo The revised extra path information to this resource
  167        *  (if any)
  168        * @param queryString Query string parameters included with this request
  169        *  (if any)
  170        * @param name Servlet name (if a named dispatcher was created)
  171        *  else <code>null</code>
  172        */
  173       public ApplicationDispatcher
  174           (Wrapper wrapper, String requestURI, String servletPath,
  175            String pathInfo, String queryString, String name) {
  176   
  177           super();
  178   
  179           // Save all of our configuration parameters
  180           this.wrapper = wrapper;
  181           this.context = (Context) wrapper.getParent();
  182           this.requestURI = requestURI;
  183           this.servletPath = servletPath;
  184           this.pathInfo = pathInfo;
  185           this.queryString = queryString;
  186           this.name = name;
  187           if (wrapper instanceof StandardWrapper)
  188               this.support = ((StandardWrapper) wrapper).getInstanceSupport();
  189           else
  190               this.support = new InstanceSupport(wrapper);
  191   
  192       }
  193   
  194   
  195       // ----------------------------------------------------- Instance Variables
  196   
  197       /**
  198        * The Context this RequestDispatcher is associated with.
  199        */
  200       private Context context = null;
  201   
  202   
  203       /**
  204        * Descriptive information about this implementation.
  205        */
  206       private static final String info =
  207           "org.apache.catalina.core.ApplicationDispatcher/1.0";
  208   
  209   
  210       /**
  211        * The servlet name for a named dispatcher.
  212        */
  213       private String name = null;
  214   
  215   
  216       /**
  217        * The extra path information for this RequestDispatcher.
  218        */
  219       private String pathInfo = null;
  220   
  221   
  222       /**
  223        * The query string parameters for this RequestDispatcher.
  224        */
  225       private String queryString = null;
  226   
  227   
  228       /**
  229        * The request URI for this RequestDispatcher.
  230        */
  231       private String requestURI = null;
  232   
  233   
  234       /**
  235        * The servlet path for this RequestDispatcher.
  236        */
  237       private String servletPath = null;
  238   
  239   
  240       /**
  241        * The StringManager for this package.
  242        */
  243       private static final StringManager sm =
  244         StringManager.getManager(Constants.Package);
  245   
  246   
  247       /**
  248        * The InstanceSupport instance associated with our Wrapper (used to
  249        * send "before dispatch" and "after dispatch" events.
  250        */
  251       private InstanceSupport support = null;
  252   
  253   
  254       /**
  255        * The Wrapper associated with the resource that will be forwarded to
  256        * or included.
  257        */
  258       private Wrapper wrapper = null;
  259   
  260   
  261       // ------------------------------------------------------------- Properties
  262   
  263   
  264       /**
  265        * Return the descriptive information about this implementation.
  266        */
  267       public String getInfo() {
  268   
  269           return (info);
  270   
  271       }
  272   
  273   
  274       // --------------------------------------------------------- Public Methods
  275   
  276   
  277       /**
  278        * Forward this request and response to another resource for processing.
  279        * Any runtime exception, IOException, or ServletException thrown by the
  280        * called servlet will be propogated to the caller.
  281        *
  282        * @param request The servlet request to be forwarded
  283        * @param response The servlet response to be forwarded
  284        *
  285        * @exception IOException if an input/output error occurs
  286        * @exception ServletException if a servlet exception occurs
  287        */
  288       public void forward(ServletRequest request, ServletResponse response)
  289           throws ServletException, IOException
  290       {
  291           if (Globals.IS_SECURITY_ENABLED) {
  292               try {
  293                   PrivilegedForward dp = new PrivilegedForward(request,response);
  294                   AccessController.doPrivileged(dp);
  295               } catch (PrivilegedActionException pe) {
  296                   Exception e = pe.getException();
  297                   if (e instanceof ServletException)
  298                       throw (ServletException) e;
  299                   throw (IOException) e;
  300               }
  301           } else {
  302               doForward(request,response);
  303           }
  304       }
  305   
  306       private void doForward(ServletRequest request, ServletResponse response)
  307           throws ServletException, IOException
  308       {
  309           
  310           // Reset any output that has been buffered, but keep headers/cookies
  311           if (response.isCommitted()) {
  312               throw new IllegalStateException
  313                   (sm.getString("applicationDispatcher.forward.ise"));
  314           }
  315           try {
  316               response.resetBuffer();
  317           } catch (IllegalStateException e) {
  318               throw e;
  319           }
  320   
  321           // Set up to handle the specified request and response
  322           State state = new State(request, response, false);
  323   
  324           if (Globals.STRICT_SERVLET_COMPLIANCE) {
  325               // Check SRV.8.2 / SRV.14.2.5.1 compliance
  326               checkSameObjects(request, response);
  327           }
  328   
  329           wrapResponse(state);
  330           // Handle an HTTP named dispatcher forward
  331           if ((servletPath == null) && (pathInfo == null)) {
  332   
  333               ApplicationHttpRequest wrequest =
  334                   (ApplicationHttpRequest) wrapRequest(state);
  335               HttpServletRequest hrequest = state.hrequest;
  336               wrequest.setRequestURI(hrequest.getRequestURI());
  337               wrequest.setContextPath(hrequest.getContextPath());
  338               wrequest.setServletPath(hrequest.getServletPath());
  339               wrequest.setPathInfo(hrequest.getPathInfo());
  340               wrequest.setQueryString(hrequest.getQueryString());
  341   
  342               processRequest(request,response,state);
  343           }
  344   
  345           // Handle an HTTP path-based forward
  346           else {
  347   
  348               ApplicationHttpRequest wrequest =
  349                   (ApplicationHttpRequest) wrapRequest(state);
  350               String contextPath = context.getPath();
  351               HttpServletRequest hrequest = state.hrequest;
  352               if (hrequest.getAttribute(Globals.FORWARD_REQUEST_URI_ATTR) == null) {
  353                   wrequest.setAttribute(Globals.FORWARD_REQUEST_URI_ATTR,
  354                                         hrequest.getRequestURI());
  355                   wrequest.setAttribute(Globals.FORWARD_CONTEXT_PATH_ATTR,
  356                                         hrequest.getContextPath());
  357                   wrequest.setAttribute(Globals.FORWARD_SERVLET_PATH_ATTR,
  358                                         hrequest.getServletPath());
  359                   wrequest.setAttribute(Globals.FORWARD_PATH_INFO_ATTR,
  360                                         hrequest.getPathInfo());
  361                   wrequest.setAttribute(Globals.FORWARD_QUERY_STRING_ATTR,
  362                                         hrequest.getQueryString());
  363               }
  364    
  365               wrequest.setContextPath(contextPath);
  366               wrequest.setRequestURI(requestURI);
  367               wrequest.setServletPath(servletPath);
  368               wrequest.setPathInfo(pathInfo);
  369               if (queryString != null) {
  370                   wrequest.setQueryString(queryString);
  371                   wrequest.setQueryParams(queryString);
  372               }
  373   
  374               processRequest(request,response,state);
  375           }
  376   
  377           // This is not a real close in order to support error processing
  378           if (wrapper.getLogger().isDebugEnabled() )
  379               wrapper.getLogger().debug(" Disabling the response for futher output");
  380   
  381           if  (response instanceof ResponseFacade) {
  382               ((ResponseFacade) response).finish();
  383           } else {
  384               // Servlet SRV.6.2.2. The Resquest/Response may have been wrapped
  385               // and may no longer be instance of RequestFacade 
  386               if (wrapper.getLogger().isDebugEnabled()){
  387                   wrapper.getLogger().debug( " The Response is vehiculed using a wrapper: " 
  388                              + response.getClass().getName() );
  389               }
  390   
  391               // Close anyway
  392               try {
  393                   PrintWriter writer = response.getWriter();
  394                   writer.close();
  395               } catch (IllegalStateException e) {
  396                   try {
  397                       ServletOutputStream stream = response.getOutputStream();
  398                       stream.close();
  399                   } catch (IllegalStateException f) {
  400                       ;
  401                   } catch (IOException f) {
  402                       ;
  403                   }
  404               } catch (IOException e) {
  405                   ;
  406               }
  407           }
  408   
  409       }
  410   
  411       
  412       /**
  413        * Prepare the request based on the filter configuration.
  414        * @param request The servlet request we are processing
  415        * @param response The servlet response we are creating
  416        * @param state The RD state
  417        *
  418        * @exception IOException if an input/output error occurs
  419        * @exception ServletException if a servlet error occurs
  420        */
  421       private void processRequest(ServletRequest request, 
  422                                   ServletResponse response,
  423                                   State state)
  424           throws IOException, ServletException {
  425                   
  426           Integer disInt = (Integer) request.getAttribute
  427               (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR);
  428           if (disInt != null) {
  429               if (disInt.intValue() != ApplicationFilterFactory.ERROR) {
  430                   state.outerRequest.setAttribute
  431                       (ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR,
  432                        servletPath);
  433                   state.outerRequest.setAttribute
  434                       (ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
  435                        Integer.valueOf(ApplicationFilterFactory.FORWARD));
  436                   invoke(state.outerRequest, response, state);
  437               } else {
  438                   invoke(state.outerRequest, response, state);
  439               }
  440           }
  441   
  442       }
  443       
  444       
  445       
  446       /**
  447        * Include the response from another resource in the current response.
  448        * Any runtime exception, IOException, or ServletException thrown by the
  449        * called servlet will be propogated to the caller.
  450        *
  451        * @param request The servlet request that is including this one
  452        * @param response The servlet response to be appended to
  453        *
  454        * @exception IOException if an input/output error occurs
  455        * @exception ServletException if a servlet exception occurs
  456        */
  457       public void include(ServletRequest request, ServletResponse response)
  458           throws ServletException, IOException
  459       {
  460           if (Globals.IS_SECURITY_ENABLED) {
  461               try {
  462                   PrivilegedInclude dp = new PrivilegedInclude(request,response);
  463                   AccessController.doPrivileged(dp);
  464               } catch (PrivilegedActionException pe) {
  465                   Exception e = pe.getException();
  466   
  467                   if (e instanceof ServletException)
  468                       throw (ServletException) e;
  469                   throw (IOException) e;
  470               }
  471           } else {
  472               doInclude(request,response);
  473           }
  474       }
  475   
  476       private void doInclude(ServletRequest request, ServletResponse response)
  477           throws ServletException, IOException
  478       {
  479           // Set up to handle the specified request and response
  480           State state = new State(request, response, true);
  481   
  482           if (Globals.STRICT_SERVLET_COMPLIANCE) {
  483               // Check SRV.8.2 / SRV.14.2.5.1 compliance
  484               checkSameObjects(request, response);
  485           }
  486           
  487           // Create a wrapped response to use for this request
  488           wrapResponse(state);
  489   
  490           // Handle an HTTP named dispatcher include
  491           if (name != null) {
  492   
  493               ApplicationHttpRequest wrequest =
  494                   (ApplicationHttpRequest) wrapRequest(state);
  495               wrequest.setAttribute(Globals.NAMED_DISPATCHER_ATTR, name);
  496               if (servletPath != null)
  497                   wrequest.setServletPath(servletPath);
  498               wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
  499                       Integer.valueOf(ApplicationFilterFactory.INCLUDE));
  500               wrequest.setAttribute(
  501                       ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR,
  502                       servletPath);
  503               invoke(state.outerRequest, state.outerResponse, state);
  504           }
  505   
  506           // Handle an HTTP path based include
  507           else {
  508   
  509               ApplicationHttpRequest wrequest =
  510                   (ApplicationHttpRequest) wrapRequest(state);
  511               String contextPath = context.getPath();
  512               if (requestURI != null)
  513                   wrequest.setAttribute(Globals.INCLUDE_REQUEST_URI_ATTR,
  514                                         requestURI);
  515               if (contextPath != null)
  516                   wrequest.setAttribute(Globals.INCLUDE_CONTEXT_PATH_ATTR,
  517                                         contextPath);
  518               if (servletPath != null)
  519                   wrequest.setAttribute(Globals.INCLUDE_SERVLET_PATH_ATTR,
  520                                         servletPath);
  521               if (pathInfo != null)
  522                   wrequest.setAttribute(Globals.INCLUDE_PATH_INFO_ATTR,
  523                                         pathInfo);
  524               if (queryString != null) {
  525                   wrequest.setAttribute(Globals.INCLUDE_QUERY_STRING_ATTR,
  526                                         queryString);
  527                   wrequest.setQueryParams(queryString);
  528               }
  529               
  530               wrequest.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR,
  531                       Integer.valueOf(ApplicationFilterFactory.INCLUDE));
  532               wrequest.setAttribute(
  533                       ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR,
  534                       servletPath);
  535               invoke(state.outerRequest, state.outerResponse, state);
  536           }
  537   
  538       }
  539   
  540   
  541       // -------------------------------------------------------- Private Methods
  542   
  543   
  544       /**
  545        * Ask the resource represented by this RequestDispatcher to process
  546        * the associated request, and create (or append to) the associated
  547        * response.
  548        * <p>
  549        * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
  550        * that no filters are applied to a forwarded or included resource,
  551        * because they were already done for the original request.
  552        *
  553        * @param request The servlet request we are processing
  554        * @param response The servlet response we are creating
  555        *
  556        * @exception IOException if an input/output error occurs
  557        * @exception ServletException if a servlet error occurs
  558        */
  559       private void invoke(ServletRequest request, ServletResponse response,
  560               State state) throws IOException, ServletException {
  561   
  562           // Checking to see if the context classloader is the current context
  563           // classloader. If it's not, we're saving it, and setting the context
  564           // classloader to the Context classloader
  565           ClassLoader oldCCL = Thread.currentThread().getContextClassLoader();
  566           ClassLoader contextClassLoader = context.getLoader().getClassLoader();
  567   
  568           if (oldCCL != contextClassLoader) {
  569               Thread.currentThread().setContextClassLoader(contextClassLoader);
  570           } else {
  571               oldCCL = null;
  572           }
  573   
  574           // Initialize local variables we may need
  575           HttpServletResponse hresponse = state.hresponse;
  576           Servlet servlet = null;
  577           IOException ioException = null;
  578           ServletException servletException = null;
  579           RuntimeException runtimeException = null;
  580           boolean unavailable = false;
  581   
  582           // Check for the servlet being marked unavailable
  583           if (wrapper.isUnavailable()) {
  584               wrapper.getLogger().warn(
  585                       sm.getString("applicationDispatcher.isUnavailable", 
  586                       wrapper.getName()));
  587               long available = wrapper.getAvailable();
  588               if ((available > 0L) && (available < Long.MAX_VALUE))
  589                   hresponse.setDateHeader("Retry-After", available);
  590               hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm
  591                       .getString("applicationDispatcher.isUnavailable", wrapper
  592                               .getName()));
  593               unavailable = true;
  594           }
  595   
  596           // Allocate a servlet instance to process this request
  597           try {
  598               if (!unavailable) {
  599                   servlet = wrapper.allocate();
  600               }
  601           } catch (ServletException e) {
  602               wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException",
  603                                wrapper.getName()), StandardWrapper.getRootCause(e));
  604               servletException = e;
  605               servlet = null;
  606           } catch (Throwable e) {
  607               wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException",
  608                                wrapper.getName()), e);
  609               servletException = new ServletException
  610                   (sm.getString("applicationDispatcher.allocateException",
  611                                 wrapper.getName()), e);
  612               servlet = null;
  613           }
  614                   
  615           // Get the FilterChain Here
  616           ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
  617           ApplicationFilterChain filterChain = factory.createFilterChain(request,
  618                                                                   wrapper,servlet);
  619           // Call the service() method for the allocated servlet instance
  620           try {
  621               String jspFile = wrapper.getJspFile();
  622               if (jspFile != null)
  623                   request.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
  624               else
  625                   request.removeAttribute(Globals.JSP_FILE_ATTR);
  626               support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT,
  627                                         servlet, request, response);
  628               // for includes/forwards
  629               if ((servlet != null) && (filterChain != null)) {
  630                  filterChain.doFilter(request, response);
  631                }
  632               // Servlet Service Method is called by the FilterChain
  633               request.removeAttribute(Globals.JSP_FILE_ATTR);
  634               support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT,
  635                                         servlet, request, response);
  636           } catch (ClientAbortException e) {
  637               request.removeAttribute(Globals.JSP_FILE_ATTR);
  638               support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT,
  639                                         servlet, request, response);
  640               ioException = e;
  641           } catch (IOException e) {
  642               request.removeAttribute(Globals.JSP_FILE_ATTR);
  643               support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT,
  644                                         servlet, request, response);
  645               wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
  646                                wrapper.getName()), e);
  647               ioException = e;
  648           } catch (UnavailableException e) {
  649               request.removeAttribute(Globals.JSP_FILE_ATTR);
  650               support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT,
  651                                         servlet, request, response);
  652               wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
  653                                wrapper.getName()), e);
  654               servletException = e;
  655               wrapper.unavailable(e);
  656           } catch (ServletException e) {
  657               request.removeAttribute(Globals.JSP_FILE_ATTR);
  658               support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT,
  659                                         servlet, request, response);
  660               Throwable rootCause = StandardWrapper.getRootCause(e);
  661               if (!(rootCause instanceof ClientAbortException)) {
  662                   wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
  663                           wrapper.getName()), rootCause);
  664               }
  665               servletException = e;
  666           } catch (RuntimeException e) {
  667               request.removeAttribute(Globals.JSP_FILE_ATTR);
  668               support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT,
  669                                         servlet, request, response);
  670               wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException",
  671                                wrapper.getName()), e);
  672               runtimeException = e;
  673           }
  674   
  675           // Release the filter chain (if any) for this request
  676           try {
  677               if (filterChain != null)
  678                   filterChain.release();
  679           } catch (Throwable e) {
  680               wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters",
  681                                wrapper.getName()), e);
  682               // FIXME: Exception handling needs to be simpiler to what is in the StandardWrapperValue
  683           }
  684   
  685           // Deallocate the allocated servlet instance
  686           try {
  687               if (servlet != null) {
  688                   wrapper.deallocate(servlet);
  689               }
  690           } catch (ServletException e) {
  691               wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException",
  692                                wrapper.getName()), e);
  693               servletException = e;
  694           } catch (Throwable e) {
  695               wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException",
  696                                wrapper.getName()), e);
  697               servletException = new ServletException
  698                   (sm.getString("applicationDispatcher.deallocateException",
  699                                 wrapper.getName()), e);
  700           }
  701   
  702           // Reset the old context class loader
  703           if (oldCCL != null)
  704               Thread.currentThread().setContextClassLoader(oldCCL);
  705           
  706           // Unwrap request/response if needed
  707           // See Bugzilla 30949
  708           unwrapRequest(state);
  709           unwrapResponse(state);
  710           // Recycle request if necessary (also BZ 30949)
  711           recycleRequestWrapper(state);
  712           
  713           // Rethrow an exception if one was thrown by the invoked servlet
  714           if (ioException != null)
  715               throw ioException;
  716           if (servletException != null)
  717               throw servletException;
  718           if (runtimeException != null)
  719               throw runtimeException;
  720   
  721       }
  722   
  723   
  724       /**
  725        * Unwrap the request if we have wrapped it.
  726        */
  727       private void unwrapRequest(State state) {
  728   
  729           if (state.wrapRequest == null)
  730               return;
  731   
  732           ServletRequest previous = null;
  733           ServletRequest current = state.outerRequest;
  734           while (current != null) {
  735   
  736               // If we run into the container request we are done
  737               if ((current instanceof Request)
  738                   || (current instanceof RequestFacade))
  739                   break;
  740   
  741               // Remove the current request if it is our wrapper
  742               if (current == state.wrapRequest) {
  743                   ServletRequest next =
  744                     ((ServletRequestWrapper) current).getRequest();
  745                   if (previous == null)
  746                       state.outerRequest = next;
  747                   else
  748                       ((ServletRequestWrapper) previous).setRequest(next);
  749                   break;
  750               }
  751   
  752               // Advance to the next request in the chain
  753               previous = current;
  754               current = ((ServletRequestWrapper) current).getRequest();
  755   
  756           }
  757   
  758       }
  759   
  760   
  761       /**
  762        * Unwrap the response if we have wrapped it.
  763        */
  764       private void unwrapResponse(State state) {
  765   
  766           if (state.wrapResponse == null)
  767               return;
  768   
  769           ServletResponse previous = null;
  770           ServletResponse current = state.outerResponse;
  771           while (current != null) {
  772   
  773               // If we run into the container response we are done
  774               if ((current instanceof Response)
  775                   || (current instanceof ResponseFacade))
  776                   break;
  777   
  778               // Remove the current response if it is our wrapper
  779               if (current == state.wrapResponse) {
  780                   ServletResponse next =
  781                     ((ServletResponseWrapper) current).getResponse();
  782                   if (previous == null)
  783                       state.outerResponse = next;
  784                   else
  785                       ((ServletResponseWrapper) previous).setResponse(next);
  786                   break;
  787               }
  788   
  789               // Advance to the next response in the chain
  790               previous = current;
  791               current = ((ServletResponseWrapper) current).getResponse();
  792   
  793           }
  794   
  795       }
  796   
  797   
  798       /**
  799        * Create and return a request wrapper that has been inserted in the
  800        * appropriate spot in the request chain.
  801        */
  802       private ServletRequest wrapRequest(State state) {
  803   
  804           // Locate the request we should insert in front of
  805           ServletRequest previous = null;
  806           ServletRequest current = state.outerRequest;
  807           while (current != null) {
  808               if(state.hrequest == null && (current instanceof HttpServletRequest))
  809                   state.hrequest = (HttpServletRequest)current;
  810               if ("org.apache.catalina.servlets.InvokerHttpRequest".
  811                   equals(current.getClass().getName()))
  812                   break; // KLUDGE - Make nested RD.forward() using invoker work
  813               if (!(current instanceof ServletRequestWrapper))
  814                   break;
  815               if (current instanceof ApplicationHttpRequest)
  816                   break;
  817               if (current instanceof ApplicationRequest)
  818                   break;
  819               if (current instanceof Request)
  820                   break;
  821               previous = current;
  822               current = ((ServletRequestWrapper) current).getRequest();
  823           }
  824   
  825           // Instantiate a new wrapper at this point and insert it in the chain
  826           ServletRequest wrapper = null;
  827           if ((current instanceof ApplicationHttpRequest) ||
  828               (current instanceof Request) ||
  829               (current instanceof HttpServletRequest)) {
  830               // Compute a crossContext flag
  831               HttpServletRequest hcurrent = (HttpServletRequest) current;
  832               boolean crossContext = false;
  833               if ((state.outerRequest instanceof ApplicationHttpRequest) ||
  834                   (state.outerRequest instanceof Request) ||
  835                   (state.outerRequest instanceof HttpServletRequest)) {
  836                   HttpServletRequest houterRequest = 
  837                       (HttpServletRequest) state.outerRequest;
  838                   Object contextPath = houterRequest.getAttribute
  839                       (Globals.INCLUDE_CONTEXT_PATH_ATTR);
  840                   if (contextPath == null) {
  841                       // Forward
  842                       contextPath = houterRequest.getContextPath();
  843                   }
  844                   crossContext = !(context.getPath().equals(contextPath));
  845               }
  846               wrapper = new ApplicationHttpRequest
  847                   (hcurrent, context, crossContext);
  848           } else {
  849               wrapper = new ApplicationRequest(current);
  850           }
  851           if (previous == null)
  852               state.outerRequest = wrapper;
  853           else
  854               ((ServletRequestWrapper) previous).setRequest(wrapper);
  855           state.wrapRequest = wrapper;
  856           return (wrapper);
  857   
  858       }
  859   
  860   
  861       /**
  862        * Create and return a response wrapper that has been inserted in the
  863        * appropriate spot in the response chain.
  864        */
  865       private ServletResponse wrapResponse(State state) {
  866   
  867           // Locate the response we should insert in front of
  868           ServletResponse previous = null;
  869           ServletResponse current = state.outerResponse;
  870           while (current != null) {
  871               if(state.hresponse == null && (current instanceof HttpServletResponse)) {
  872                   state.hresponse = (HttpServletResponse)current;
  873                   if(!state.including) // Forward only needs hresponse
  874                       return null;
  875               }
  876               if (!(current instanceof ServletResponseWrapper))
  877                   break;
  878               if (current instanceof ApplicationHttpResponse)
  879                   break;
  880               if (current instanceof ApplicationResponse)
  881                   break;
  882               if (current instanceof Response)
  883                   break;
  884               previous = current;
  885               current = ((ServletResponseWrapper) current).getResponse();
  886           }
  887   
  888           // Instantiate a new wrapper at this point and insert it in the chain
  889           ServletResponse wrapper = null;
  890           if ((current instanceof ApplicationHttpResponse) ||
  891               (current instanceof Response) ||
  892               (current instanceof HttpServletResponse))
  893               wrapper =
  894                   new ApplicationHttpResponse((HttpServletResponse) current,
  895                           state.including);
  896           else
  897               wrapper = new ApplicationResponse(current, state.including);
  898           if (previous == null)
  899               state.outerResponse = wrapper;
  900           else
  901               ((ServletResponseWrapper) previous).setResponse(wrapper);
  902           state.wrapResponse = wrapper;
  903           return (wrapper);
  904   
  905       }
  906   
  907       private void checkSameObjects(ServletRequest appRequest,
  908               ServletResponse appResponse) throws ServletException {
  909           ServletRequest originalRequest =
  910               ApplicationFilterChain.getLastServicedRequest();
  911           ServletResponse originalResponse =
  912               ApplicationFilterChain.getLastServicedResponse();
  913           
  914           // Some forwards, eg from valves will not set original values 
  915           if (originalRequest == null || originalResponse == null) {
  916               return;
  917           }
  918           
  919           boolean same = false;
  920           ServletRequest dispatchedRequest = appRequest;
  921           
  922           //find the request that was passed into the service method
  923           while (originalRequest instanceof ServletRequestWrapper &&
  924                   ((ServletRequestWrapper) originalRequest).getRequest()!=null ) {
  925               originalRequest =
  926                   ((ServletRequestWrapper) originalRequest).getRequest();
  927           }
  928           //compare with the dispatched request
  929           while (!same) {
  930               if (originalRequest.equals(dispatchedRequest)) {
  931                   same = true;
  932               }
  933               if (!same && dispatchedRequest instanceof ServletRequestWrapper) {
  934                   dispatchedRequest =
  935                       ((ServletRequestWrapper) dispatchedRequest).getRequest();
  936               } else {
  937                   break;
  938               }
  939           }
  940           if (!same) {
  941               throw new ServletException(sm.getString(
  942                       "applicationDispatcher.specViolation.request"));
  943           }
  944           
  945           same = false;
  946           ServletResponse dispatchedResponse = appResponse;
  947           
  948           //find the response that was passed into the service method
  949           while (originalResponse instanceof ServletResponseWrapper &&
  950                   ((ServletResponseWrapper) originalResponse).getResponse() != 
  951                       null ) {
  952               originalResponse =
  953                   ((ServletResponseWrapper) originalResponse).getResponse();
  954           }
  955           //compare with the dispatched response
  956           while (!same) {
  957               if (originalResponse.equals(dispatchedResponse)) {
  958                   same = true;
  959               }
  960               
  961               if (!same && dispatchedResponse instanceof ServletResponseWrapper) {
  962                   dispatchedResponse =
  963                       ((ServletResponseWrapper) dispatchedResponse).getResponse();
  964               } else {
  965                   break;
  966               }
  967           }
  968   
  969           if (!same) {
  970               throw new ServletException(sm.getString(
  971                       "applicationDispatcher.specViolation.response"));
  972           }
  973       }
  974   
  975       private void recycleRequestWrapper(State state) {
  976           if (state.wrapRequest instanceof ApplicationHttpRequest) {
  977               ((ApplicationHttpRequest) state.wrapRequest).recycle();        }
  978       }
  979   }

Save This Page
Home » apache-tomcat-6.0.16-src » org.apache » catalina » core » [javadoc | source]