For any request URL other than the context root, delegate to the
appropriate handler. If no handler is available, a 404 will be set
into the response.

@param request
@param response
@param pathInfo
@throws IOException
7900
private void handleWithDelegate(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
        //Delegate to handler
        boolean foundHandler = REST_HANDLER_CONTAINER.handleRequest(new ServletRESTRequestImpl(request), new ServletRESTResponseImpl(response));
        //RESTHandler handler = REST_HANDLER_CONTAINER.getHandler(pathInfo);
        if (!foundHandler) {
            //No handler found, so we send back a 404 "not found" response.
            String errorMsg = Tr.formatMessage(tc, "HANDLER_NOT_FOUND_ERROR", request.getRequestURI());
            response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
        }
    }
556701
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String servletPath = (String) request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
        String pathInfo = null;
        if (servletPath == null)
        {
            servletPath = request.getServletPath();
            pathInfo = request.getPathInfo();
        }
        else
            pathInfo = (String) request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);

        String pathInContext = URI.addPaths(servletPath, pathInfo);
                
        boolean endsWithSlash = pathInContext.endsWith("/");
        Resource resource = getResource(pathInContext);

        // Is the method allowed?
        String method = request.getMethod();
        if (_AllowString.indexOf(method) < 0)
        {
            if (resource != null && resource.exists())
            {
                response.setHeader(HttpFields.__Allow, _AllowString);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            else
                response.sendError(HttpResponse.__404_Not_Found);
            return;
        }

        // Handle the request
        try
        {
            // handle by method.
            if (method.equals(HttpRequest.__GET) || method.equals(HttpRequest.__POST) || method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, resource, endsWithSlash);
            else if (_putAllowed && method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (_delAllowed && method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (_putAllowed && _delAllowed && method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(request, response);
            else if (method.equals(HttpRequest.__TRACE))
                _servletHandler.handleTrace(request, response);
            else
            {
                // anything else...
                try
                {
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                    else
                        _servletHandler.notFound(request, response);
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            LogSupport.ignore(log, e);
        }
        finally
        {
            if (resource != null && !(resource instanceof CachedResource))
                resource.release();
        }

    }
1081932
function(context) {

            // Check path
            var path = context.request.urlInfo.pathname;

            if (path.indexOf(this.$.path) === 0) {
                // path matches
                if (this.$.route !== null) {
                    return (new RegExp(this.$.route, "i")).test(path);
                }

                return true;
            }

            return false;
        }
913608
void handlePut(HttpRequest request,
                   HttpResponse response,
                   String pathInContext,
                   Resource resource)
        throws IOException
    {
        if(log.isDebugEnabled())log.debug("PUT "+pathInContext+" in "+resource);

        boolean exists=resource!=null && resource.exists();
        if (exists &&
            !passConditionalHeaders(request,response,resource))
            return;
        
        if (pathInContext.endsWith("/"))
        {
            if (!exists)
            {
                if (!resource.getFile().mkdirs())
                    response.sendError(HttpResponse.__403_Forbidden, "Directories could not be created");
                else
                {
                    request.setHandled(true);
                    response.setStatus(HttpResponse.__201_Created);
                    response.commit();
                }
            }
            else
            {
                request.setHandled(true);
                response.setStatus(HttpResponse.__200_OK);
                response.commit();
            }
        }
        else
        {
            try
            {
                int toRead = request.getContentLength();
                InputStream in = request.getInputStream();
                OutputStream out = resource.getOutputStream();
                if (toRead>=0)
                    IO.copy(in,out,toRead);
                else
                    IO.copy(in,out);
                out.close();
                request.setHandled(true);
                response.setStatus(exists
                                   ?HttpResponse.__200_OK
                                   :HttpResponse.__201_Created);
                response.commit();
            }
            catch (Exception ex)
            {
                log.warn(LogSupport.EXCEPTION,ex);
                response.sendError(HttpResponse.__403_Forbidden,
                                   ex.getMessage());
            }
        }
    }
1164159
public void handle(
        String pathInContext,
        String pathParams,
        HttpRequest request,
        HttpResponse response)
        throws HttpException, IOException
    {
        response.setContentType(HttpFields.__TextHtml);
        ByteArrayISO8859Writer writer= new ByteArrayISO8859Writer(2048);
        writeErrorPage(request, writer, response.getStatus(), response.getReason());
        writer.flush();
        response.setContentLength(writer.size());
        writer.writeTo(response.getOutputStream());
        writer.destroy();
    }
780062
protected void handleOptions(HttpServletRequest request,
                              HttpServletResponse response)
        throws IOException
    {
        // Handle OPTIONS request for entire server
        if ("*".equals(request.getRequestURI()))
        {
            // 9.2
            response.setIntHeader(HttpFields.__ContentLength,0);
            response.setHeader(HttpFields.__Allow,__AllowString);                
            response.flushBuffer();
        }
        else
            response.sendError(HttpResponse.__404_Not_Found);
    }
1046146
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
   {
      String action = request.getParameter(ACTION_PARAM);

      if (action == null)
         action = DISPLAY_MBEANS_ACTION;

      if (action.equals(DISPLAY_MBEANS_ACTION))
         displayMBeans(request, response);
      else if (action.equals(INSPECT_MBEAN_ACTION))
         inspectMBean(request, response);
      else if (action.equals(UPDATE_ATTRIBUTES_ACTION))
         updateAttributes(request, response);
      else if (action.equals(INVOKE_OP_ACTION))
         invokeOp(request, response);
      else if (action.equals(INVOKE_OP_BY_NAME_ACTION))
         invokeOpByName(request, response);
   }
925464
@SuppressWarnings("unchecked")
    public static void after(Object request, Object response) {

        HttpData data = new HttpData();

        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        Class<?> respClass = response.getClass();
        try {
            /*
             * Retrieve the request tracker
             */
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            HttpRequestTracker tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                /*
                 * should never happen
                 */
                throw new JavametricsException("Unable to find request tracker");
            }

            /*
             * Decrement the nesting level and return if still nested
             */
            if (tracker.decrement()) {
                setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
                return;
            }

            /*
             * Clear the tracker
             */
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, null);

            data.setRequestTime(tracker.getRequestTime());

            Method getRequestURL = reqClass.getMethod(GET_REQUEST_URL);
            data.setUrl(((StringBuffer) getRequestURL.invoke(request)).toString());

            Method getMethod = reqClass.getMethod(GET_METHOD);
            data.setMethod((String) getMethod.invoke(request));

            Method getStatus = respClass.getMethod(GET_STATUS);
            data.setStatus((Integer) getStatus.invoke(response));

            if (detailed) {
                Method getContentType = respClass.getMethod(GET_CONTENT_TYPE);
                data.setContentType((String) getContentType.invoke(response));

                Method getHeaders = respClass.getMethod(GET_HEADER_NAMES);
                Method getHeader = respClass.getMethod(GET_HEADER, String.class);
                Collection<String> headers = (Collection<String>) getHeaders.invoke(response);
                if (headers != null) {
                    for (String headerName : headers) {
                        String header = (String) getHeader.invoke(response, headerName);
                        if (header != null) {
                            data.addHeader(headerName, header);
                        }
                    }
                }

                Method getReqHeaders = reqClass.getMethod(GET_HEADER_NAMES);
                Method getReqHeader = reqClass.getMethod(GET_HEADER, String.class);
                Enumeration<String> reqHeaders = (Enumeration<String>) getReqHeaders.invoke(request);
                if (reqHeaders != null) {
                    while (reqHeaders.hasMoreElements()) {
                        String headerName = reqHeaders.nextElement();
                        String header = (String) getReqHeader.invoke(request, headerName);
                        if (header != null) {
                            data.addRequestHeader(headerName, header);
                        }
                    }
                }
            }
            
            data.setDuration(System.currentTimeMillis() - tracker.getRequestTime());

            if (Agent.debug) {
                System.err.println("Javametrics: Sending {\"http\":" + data.toJsonString() + "}");
            }

            /*
             * Send the http request data to the Javametrics agent
             */
            Javametrics.getInstance().sendJSON(HTTP_TOPIC, data.toJsonString());

        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }

    }
948453
private static String getHandler(HttpServletRequest request) {
    String pathInfo = request.getPathInfo();
    return pathInfo == null ? "" : pathInfo.substring(1);
  }
441110
@Override
    @FFDCIgnore({ RESTHandlerInternalError.class, RESTHandlerUserError.class, RESTHandlerMethodNotAllowedError.class, RESTHandlerUnsupportedMediaType.class,
                 RESTHandlerJsonException.class })
    public boolean handleRequest(RESTRequest request, RESTResponse response) throws IOException {
        final String requestURL = request.getContextPath() + request.getPath();
        final HandlerInfo handlerInfo = getHandler(requestURL);
        final boolean isRouting = DefaultRoutingHelper.containsLegacyRoutingContext(request) || DefaultRoutingHelper.containsRoutingContext(request);

        if (handlerInfo == null && !isRouting) {
            //calling proxy servlet will handle this case 
            return false;
        }

        try {
            //Security checks applicable to /ibm/api participants
            if (request.getContextPath().equals(RESTHandler.PROPERTY_REST_HANDLER_DEFAULT_CONTEXT_ROOT)) {
                //Check if the handler is doing custom security or not.
                //The first argument will be true if we're routing the call and a corresponding service wasn't present on this controller
                if (handlerInfo == null || !hasProperty(handlerInfo.handlerRef, RESTHandler.PROPERTY_REST_HANDLER_CUSTOM_SECURITY)) {
                    //This path is not performing custom security, so check for default authorization
                    if (!getAuthorizationHelper().checkAdministratorRole(request, response)) {
                        //We failed the check, so return true, since the default authorization helper would have filled up the response already.
                        return true;
                    }
                }
            }

            //If we matched a path that had variables, extended the request to contain the resolved variables
            if (handlerInfo != null && handlerInfo.path != null && handlerInfo.path.containsVariable()) {
                //When mapping variables we don't include the context root
                request = new ExtendedRESTRequestImpl(request, handlerInfo.path.mapVariables(requestURL));
            }

            //Routing special code
            if (isRouting) {
                //Check if we're doing custom routing or not
                if (handlerInfo == null || !hasProperty(handlerInfo.handlerRef, RESTHandler.PROPERTY_REST_HANDLER_CUSTOM_ROUTING)) {
                    //This path is not doing custom routing, so use the routing helper
                    getRoutingHelper().routeRequest(request, response);
                    return true;
                }
                //...there's routing context, but matched handler wants to do custom routing, so let the request go through
            }

            try {
                //Delegate request to handler
                handlerInfo.handler.handleRequest(request, response);
            } catch (RESTHandlerInternalError ie) {
                //Handlers general internal errors and osgi errors
                response.sendError(ie.getStatusCode(), ie.getMessage());
            } catch (RESTHandlerUserError ue) {
                response.sendError(ue.getStatusCode(), ue.getMessage());
            } catch (RESTHandlerUnsupportedMediaType e) {
                response.sendError(e.getStatusCode(), e.getMessage());
            } catch (RESTHandlerMethodNotAllowedError e) {
                //A 405 response (Method Not Allowed) needs to have the response header of "Allow", to say which methods can be used
                response.setResponseHeader("Allow", e.getAllowedMethods());
                response.sendError(e.getStatusCode());
            } catch (RESTHandlerJsonException e) {
                if (e.isMessageContentJSON()) {
                    response.setStatus(e.getStatusCode());
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(e.getMessage());
                } else {
                    response.sendError(e.getStatusCode(), e.getMessage());
                }
            }

        } catch (IOException ioe) {
            response.sendError(500, ioe.getMessage());
        }

        return true;
    }
408637
public void setPathInfo(String pathinfo) {
		int qp = pathinfo.indexOf('?');
		if(qp<0) {
			client.setContext(isProxy?("/proxy"+pathinfo):pathinfo);
		} else {
			client.setContext(isProxy?("/proxy"+pathinfo.substring(0,qp)):pathinfo.substring(0,qp));
			client.setQueryParams(pathinfo.substring(qp+1));
		}
	}
676224
protected void service(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
    {
        // Get the requested path and info
        boolean included=false;
        String servlet_path=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
        if (servlet_path==null)
            servlet_path=request.getServletPath();
        else
            included=true;
        String path_info = (String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);
        if (path_info==null)
            path_info=request.getPathInfo();
        
        // Get the servlet class
        String servlet = path_info;
        if (servlet==null || servlet.length()<=1 )
        {
            response.sendError(404);
            return;
        }
        
        int i0=servlet.charAt(0)=='/'?1:0;
        int i1=servlet.indexOf('/',i0);
        servlet=i1<0?servlet.substring(i0):servlet.substring(i0,i1);

        // look for a named holder
        ServletHolder holder=_servletHandler.getServletHolder(servlet);
        if (holder!=null)
        {
            // Add named servlet mapping
            _servletHandler.addServletHolder(holder);
            _servletHandler.mapPathToServlet(URI.addPaths(servlet_path,servlet)+"/*", holder.getName());
        }
        else
        {
            // look for a class mapping
            if (servlet.endsWith(".class"))
                servlet=servlet.substring(0,servlet.length()-6);
            if (servlet==null || servlet.length()==0)
            {
                response.sendError(404);
                return;
            }   
        
            synchronized(_servletHandler)
            {
                // find the entry for the invoker
                if (_invokerEntry==null)
                    _invokerEntry=_servletHandler.getHolderEntry(servlet_path);
            
                // Check for existing mapping (avoid threaded race).
                String path=URI.addPaths(servlet_path,servlet);
                Map.Entry entry = _servletHandler.getHolderEntry(path);

                if (entry!=null && entry!=_invokerEntry)
                {
                    // Use the holder
                    holder=(ServletHolder)entry.getValue();       
                }
                else
                {
                    // Make a holder
                    holder=new ServletHolder(_servletHandler,servlet,servlet);
                    
                    if (_parameters!=null)
                        holder.putAll(_parameters);
                    
                    try {holder.start();}
                    catch (Exception e)
                    {
                        log.debug(LogSupport.EXCEPTION,e);
                        throw new UnavailableException(e.toString());
                    }
                    
                    // Check it is from an allowable classloader
                    if (!_nonContextServlets)
                    {
                        Object s=holder.getServlet();
                        
                        if (_servletHandler.getClassLoader()!=
                            s.getClass().getClassLoader())
                        {
                            holder.stop();
                            log.warn("Dynamic servlet "+s+
                                         " not loaded from context "+
                                         request.getContextPath());
                            throw new UnavailableException("Not in context");
                        }
                    }

                    // Add the holder for all the possible paths
                    if (_verbose)
                        log("Dynamic load '"+servlet+"' at "+path);
                    _servletHandler.addServletHolder(holder);
                    _servletHandler.mapPathToServlet(path+"/*",holder.getName());
                    _servletHandler.mapPathToServlet(path+".class/*",holder.getName());
                }
            }
            
        }
        
        if (holder!=null)
            holder.handle(new Request(request,included,servlet,servlet_path,path_info),
                          response);
        else
            response.sendError(404);
        
    }
86809
private void processInternal( HttpServletRequest request, HttpServletResponse response )
            throws IOException, ServletException
    {
        //
        // First wrap the request with an object that contains request-scoped values that our runtime uses.  This
        // is faster than sticking everything into attributes on the request (then basically reading from a HashMap).
        //
        request = PageFlowRequestWrapper.wrapRequest( request );

        String uri = InternalUtils.getDecodedServletPath( request );
        ServletContext servletContext = getServletContext();

        // The ServletContainerAdapter reference may have been lost during serialization/deserialization.
        if (_servletContainerAdapter == null) {
            _servletContainerAdapter = AdapterManager.getServletContainerAdapter( servletContext );
        }

        //
        // Allow the container to do a security check on forwarded requests, if that feature is enabled.
        //
        if ( LegacySettings.get( servletContext ).shouldDoSecureForwards()
             && PageFlowRequestWrapper.get( request ).isForwardedRequest() )
        {
            //
            // In some situations (namely, in scoped requests under portal), the initial
            // security check may not have been done for the request URI.  In this case, a redirect
            // to https may happen during checkSecurity().
            //
            if ( _servletContainerAdapter.doSecurityRedirect( uri, request, response ) )
            {
                if ( LOG.isDebugEnabled() )
                    LOG.debug( "checkSecurity() caused a redirect.  Ending processing for this request "
                               + '(' + uri + ')' );

                return;
            }
        }

        //
        // If we've come in on a forced redirect due to security constraints, look for request attrs
        // that we put into the session.
        //
        String hash = request.getParameter( REDIRECT_REQUEST_ATTRS_PARAM );
        if ( hash != null )
        {
            HttpSession session = request.getSession( false );

            if ( session != null )
            {
                String carryoverAttrName = makeRedirectedRequestAttrsKey( uri, hash );
                Map attrs = ( Map ) session.getAttribute( carryoverAttrName );
                session.removeAttribute( carryoverAttrName );

                if ( attrs != null )
                {
                    for ( Iterator i = attrs.entrySet().iterator(); i.hasNext(); )
                    {
                        Map.Entry entry = ( Map.Entry ) i.next();

                        String attrName = ( String ) entry.getKey();
                        if ( request.getAttribute( attrName ) == null )
                        {
                            request.setAttribute( attrName, entry.getValue() );
                        }
                    }
                }
            }
        }

        //
        // The requested action can be overridden by a request parameter.  In this case, we parse the action from
        // the request parameter and forward to a URI constructed from it.  If this happens, just return.
        //
        if ( processActionOverride( request, response ) ) return;

        //
        // Process any direct request for a page flow by forwarding to its "begin" action.
        //
        if ( processPageFlowRequest( request, response, uri ) ) return;

        //
        // Get the FlowController for this request (page flow or shared flow), and cache it in the request.
        //
        String flowControllerClassName = InternalUtils.getFlowControllerClassName( moduleConfig );

        if ( flowControllerClassName == null &&
             ! ( moduleConfig instanceof AutoRegisterActionServlet.MissingRootModuleControllerConfig ) )
        {
            //
            // If this isn't a blank module initialized in place of a missing root PageFlowController, emit a warning
            // about the missing controllerClass property.
            //
            if(LOG.isWarnEnabled())
                LOG.warn( "Struts module " + moduleConfig.getPrefix() + " is configured to use " + getClass().getName()
                    + " as the request processor, but the <controller> element does not contain a <set-property>"
                    + " for \"controllerClass\".  Page Flow actions in this module may not be handled correctly." );
        }

        //
        // Look up or create the appropriate SharedFlowControllers if they don't exist.
        //
        if ( LOG.isInfoEnabled() )
            LOG.info( "Attempting to instantiate SharedFlowControllers for request " + request.getRequestURI() );

        FlowController currentFlowController = null;

        try
        {
            RequestContext requestContext = new RequestContext( request, response );
            Map/*< String, SharedFlowController >*/ sharedFlows =
                    _flowControllerFactory.getSharedFlowsForRequest( requestContext );

            /* todo: why are the shared flow / global app objects loaded for data binding here? */
            ImplicitObjectUtil.loadSharedFlow( request, sharedFlows );
            ImplicitObjectUtil.loadGlobalApp( request, PageFlowUtils.getGlobalApp( request ) );

            if ( flowControllerClassName != null )
            {
                currentFlowController = getFlowController( requestContext, flowControllerClassName );
                PageFlowRequestWrapper.get( request ).setCurrentFlowController( currentFlowController );
            }
            else
            {
                PageFlowRequestWrapper.get( request ).setCurrentFlowController( null );
            }
        }
        catch ( ClassNotFoundException e )
        {
            LOG.error( "Could not find FlowController class " + flowControllerClassName, e );
            ServletUtils.throwServletException(e);
        }
        catch ( InstantiationException e )
        {
            LOG.error( "Could not instantiate FlowController of type " + flowControllerClassName, e );
            ServletUtils.throwServletException(e);
        }
        catch ( IllegalAccessException e )
        {
            LOG.error( "Could not instantiate FlowController of type " + flowControllerClassName, e );
            ServletUtils.throwServletException(e);
        }

        //
        // Get the page flow for this request.
        //
        PageFlowController jpf = PageFlowUtils.getCurrentPageFlow( request, getServletContext() );

        //
        // Remove any current JavaServer Faces backing bean.  We have "left" any JSF page and are now processing a
        // Page Flow action.
        //
        InternalUtils.removeCurrentFacesBackingBean( request, servletContext );

        //
        // Set up implicit objects used by the expression language in simple actions and in declarative validation.
        //
        ImplicitObjectUtil.loadImplicitObjects( request, response, servletContext, jpf );

        try
        {
            super.process( request, response );
        }
        catch ( UnhandledException unhandledException )
        {
            // If we get here, then we've already tried to find an exception handler.  Just throw.
            rethrowUnhandledException( unhandledException );
        }
        catch ( ServletException servletEx )
        {
            // If a ServletException escapes out of any of the processing methods, let the current FlowController handle it.
            if ( ! handleException( servletEx, currentFlowController, request, response ) )
                throw servletEx;
        }
        catch ( IOException ioe )
        {
            // If an IOException escapes out of any of the processing methods, let the current FlowController handle it.
            if ( ! handleException( ioe, currentFlowController, request, response ) )
                throw ioe;
        }
        catch ( Throwable th )
        {
            // If a Throwable escapes out of any of the processing methods, let the current FlowController handle it.
            if ( ! handleException( th, currentFlowController, request, response ) )
            {
                if ( th instanceof Error )
                    throw ( Error ) th;
                ServletUtils.throwServletException(th);
            }
        }
    }
1263184
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
            throws HttpException,IOException
    {
        String user=null;
        String password=null;
        boolean IPValid=true;

        if(log.isDebugEnabled())log.debug("HTAccessHandler pathInContext="+pathInContext);

        String credentials=request.getField(HttpFields.__Authorization);

        if (credentials!=null)
        {
            credentials=credentials.substring(credentials.indexOf(' ')+1);
            credentials=B64Code.decode(credentials,StringUtil.__ISO_8859_1);
            int i=credentials.indexOf(':');
            user=credentials.substring(0,i);
            password=credentials.substring(i+1);

            if(log.isDebugEnabled())log.debug("User="+user+", password="+
                    "******************************".substring(0,password.length()));
        }

        HTAccess ht=null;

        try
        {
            Resource resource=null;
            String directory=pathInContext.endsWith("/")
                    ?pathInContext:
                    URI.parentPath(pathInContext);

            // Look for htAccess resource
            while (directory!=null)
            {
                String htPath=directory+_accessFile;
                resource=getHttpContext().getResource(htPath);
                if(log.isDebugEnabled())log.debug("directory="+directory+" resource="+resource);

                if (resource!=null && resource.exists() && !resource.isDirectory())
                    break;
                resource=null;
                directory=URI.parentPath(directory);
            }

            // Try default directory
            if (resource==null && _default!=null)
            {
                resource=Resource.newResource(_default);
                if (!resource.exists() || resource.isDirectory())
                    return;
            }
            if (resource==null)
                return;

            if(log.isDebugEnabled())log.debug("HTACCESS="+resource);

            ht=(HTAccess)_htCache.get(resource);
            if (ht==null || ht.getLastModified()!=resource.lastModified())
            {
                ht=new HTAccess(resource);
                _htCache.put(resource,ht);
                if(log.isDebugEnabled())log.debug("HTCache loaded "+ht);
            }

            // prevent access to htaccess files
            if (pathInContext.endsWith(_accessFile))
            {
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            // See if there is a config problem
            if (ht.isForbidden())
            {
                log.warn("Mis-configured htaccess: "+ht);
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            //first see if we need to handle based on method type
            Map methods=ht.getMethods();
            if (methods.size()>0 && !methods.containsKey(request.getMethod()))
                return; //Nothing to check

            // Check the accesss
            int satisfy=ht.getSatisfy();

            // second check IP address
            IPValid=ht.checkAccess("",request.getRemoteAddr());
            if(log.isDebugEnabled())log.debug("IPValid = "+IPValid);

            // If IP is correct and satify is ANY then access is allowed
            if (IPValid==true && satisfy==HTAccess.ANY)
                return;

            // If IP is NOT correct and satify is ALL then access is forbidden
            if (IPValid==false && satisfy==HTAccess.ALL)
            {
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }

            // set required page
            if (!ht.checkAuth(user,password,getHttpContext(),request))
            {
                log.debug("Auth Failed");
                response.setField(HttpFields.__WwwAuthenticate,"basic realm="+ht.getName());
                response.sendError(HttpResponse.__401_Unauthorized);
                response.commit();
                request.setHandled(true);
                return;
            }

            // set user
            if (user!=null)
            {
                request.setAuthType(SecurityConstraint.__BASIC_AUTH);
                request.setAuthUser(user);
            }

        }
        catch (Exception ex)
        {
            log.warn(LogSupport.EXCEPTION,ex);
            if (ht!=null)
            {
                response.sendError(HttpResponse.__500_Internal_Server_Error);
                request.setHandled(true);
            }
        }
    }
1265038
protected void sendData(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws IOException
    {
        long resLength = resource.length();

        boolean include = request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) != null;

        // Get the output stream (or writer)
        OutputStream out = null;
        try
        {
            out = response.getOutputStream();
        }
        catch (IllegalStateException e)
        {
            out = new WriterOutputStream(response.getWriter());
        }

        // see if there are any range headers
        Enumeration reqRanges = include ? null : request.getHeaders(HttpFields.__Range);

        if (reqRanges == null || !reqRanges.hasMoreElements())
        {
            // if there were no ranges, send entire entity
            Resource data = resource;
            if (!include)
            {
                // look for a gziped content.
                if (_minGzipLength > 0)
                {
                    String accept = request.getHeader(HttpFields.__AcceptEncoding);
                    if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz"))
                    {
                        Resource gz = getResource(pathInContext + ".gz");
                        if (gz.exists() && accept.indexOf("gzip") >= 0 && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null)
                        {
                            response.setHeader(HttpFields.__ContentEncoding, "gzip");
                            data = gz;
                            resLength = data.length();
                        }
                    }
                }
                writeHeaders(response, resource, resLength);
            }

            data.writeTo(out, 0, resLength);
            return;
        }

        // Parse the satisfiable ranges
        List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength);

        // if there are no satisfiable ranges, send 416 response
        if (ranges == null || ranges.size() == 0)
        {
            writeHeaders(response, resource, resLength);
            response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable);
            response.setHeader(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength));
            resource.writeTo(out, 0, resLength);
            return;
        }

        // if there is only a single valid range (must be satisfiable
        // since were here now), send that range with a 216 response
        if (ranges.size() == 1)
        {
            InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0);
            long singleLength = singleSatisfiableRange.getSize(resLength);
            writeHeaders(response, resource, singleLength);
            response.setStatus(HttpResponse.__206_Partial_Content);
            response.setHeader(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength));
            resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength);
            return;
        }

        // multiple non-overlapping valid ranges cause a multipart
        // 216 response which does not require an overall
        // content-length header
        //
        writeHeaders(response, resource, -1);
        ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);
        String encoding = metaData.getMimeType();
        MultiPartResponse multi = new MultiPartResponse(response.getOutputStream());
        response.setStatus(HttpResponse.__206_Partial_Content);

        // If the request has a "Request-Range" header then we need to
        // send an old style multipart/x-byteranges Content-Type. This
        // keeps Netscape and acrobat happy. This is what Apache does.
        String ctp;
        if (request.getHeader(HttpFields.__RequestRange) != null)
            ctp = "multipart/x-byteranges; boundary=";
        else
            ctp = "multipart/byteranges; boundary=";
        response.setContentType(ctp + multi.getBoundary());

        InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream();
        long pos = 0;

        for (int i = 0; i < ranges.size(); i++)
        {
            InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
            String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength);
            multi.startPart(encoding, new String[]
            { header});

            long start = ibr.getFirst(resLength);
            long size = ibr.getSize(resLength);
            if (in != null)
            {
                // Handle non cached resource
                if (start < pos)
                {
                    in.close();
                    in = resource.getInputStream();
                    pos = 0;
                }
                if (pos < start)
                {
                    in.skip(start - pos);
                    pos = start;
                }
                IO.copy(in, out, size);
                pos += size;
            }
            else
                // Handle cached resource
                (resource).writeTo(out, start, size);

        }
        if (in != null)
            in.close();
        multi.close();

        return;
    }
24795
public void handleRequest(ServletRequest request, ServletResponse response) throws Exception {
        Object token = null;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest httpRequest = null; //PM88028
        StringBuffer path =null;
        WebAppDispatcherContext dispatchContext =null;
        String pathInfo = null; // PK64302
        FileNotFoundException fnf = null;
        
    	
//		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
//         	logger.entering(CLASS_NAME,"handleRequest : request--->" + req.getRequestURI()+ "<---");
//		}
		
        try {
        	//IExtendedRequest wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(request);
                //PM88028 Start
                IExtendedRequest wasreq = null;
                
                if(useOriginalRequestState){

                    WebContainerRequestState reqStateSaveRequest = WebContainerRequestState.getInstance(false);
                    if(reqStateSaveRequest != null){                        
                        httpRequest = (HttpServletRequest)reqStateSaveRequest.getAttribute("unFilteredRequestObject");
                        if(httpRequest != null) {
                            wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(httpRequest);  
                            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                logger.entering(CLASS_NAME,"handleRequest : useOriginalRequestState request--->" + httpRequest.getRequestURI()+ "<---");
                            }
                        }
                    } 
                }
                //if it is null then get it from the req
                if(httpRequest == null)
                {
                    httpRequest = (HttpServletRequest) request;
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                        logger.entering(CLASS_NAME,"handleRequest : request--->" + httpRequest.getRequestURI()+ "<---");
                    }
                    wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(request);
                }
            
		dispatchContext = (WebAppDispatcherContext)wasreq.getWebAppDispatcherContext();
			
        
            //LIBERTY: Talk to Namespace
                //webAppNameSpaceCollab.preInvoke(cmd);
			
            //remove since the preInvoke is done in WebAppFilterManager
			//The preInvoke in WebAppFilterManager calls with doAuth/enforceSecurity=true which will setup
			//the metadata for sync to thread just as well as a call with doAuth=false would.
			//securityPreInvokes.push(secCollab.preInvoke(req, resp, null, false));
        
            token = ThreadIdentityManager.runAsServer();
        
            boolean isInclude = false; // is this an include request?
            ServletContext context = _webapp;
            String fileSystemPath = null; // actual OS dependent path
            path = new StringBuffer(); // constructed path

            String servletPath = null; // PK64302
          //PM88028 change req to httpReques
            if (httpRequest.getAttribute(WebAppRequestDispatcher.REQUEST_URI_INCLUDE_ATTR) != null) {
                isInclude = true;
                servletPath = (String) httpRequest.getAttribute(WebAppRequestDispatcher.SERVLET_PATH_INCLUDE_ATTR);
                pathInfo = (String) httpRequest.getAttribute(WebAppRequestDispatcher.PATH_INFO_INCLUDE_ATTR);
            }// PM79476 (PM71901) Start
            else if(dispatchContext!= null && !handlingRequestWithOverridenPath){ //always here
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                        logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "relative uri -->["+ dispatchContext.getRelativeUri()+"]");
                }
                servletPath = dispatchContext.getServletPath();
                if(servletPath!= null) {servletPath = WebGroup.stripURL(servletPath,false);}                    
                
                pathInfo = dispatchContext.getPathInfo();
                if(pathInfo!= null) {pathInfo = WebGroup.stripURL(pathInfo,false);}
                if(pathInfo == ""){pathInfo = null;}
                
            }// PM71901 End
            else { // never be here 
                // not get these from request as these can be overridden
                servletPath = httpRequest.getServletPath();
                pathInfo = httpRequest.getPathInfo();
            }

            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "servletPath [" + servletPath +"] pathInfo [" + pathInfo +"]");
            }
            
            path.append(servletPath);

            if (pathInfo != null) {
            	int semicolon = pathInfo.indexOf(';');
                if (semicolon != -1)
                    pathInfo = pathInfo.substring(0, semicolon);
               
                path.append(pathInfo);
            }

            //PK36447

            String temporaryPath = WSUtil.resolveURI(path.toString());
            String upperMatchString = temporaryPath.toUpperCase();
            boolean forbidden = false;
            if (!exposeWebInfOnDispatch && (upperMatchString.startsWith("/WEB-INF/") || upperMatchString.equals("/WEB-INF")))
                forbidden = true;

            //We check META-INF by default in the JSP codepath
            else if (upperMatchString.startsWith("/META-INF/") || upperMatchString.equals("/META-INF"))
                forbidden = true;
            
            // PK24615 change conditionals from "indexOf() != -1" to "startsWith()"
            if (forbidden) {
                int statusCode;
                //We don't want to give out more information than required.  On tWAS, this code lived in the wrapper
                //and so returning a 403 would have meant that the file was, in fact, found.  Adding this check to maintain
                //the same behavior
                //If the path was encoded and illegal, then just return a 404.
                if (temporaryPath.equals(path.toString())) {
                    statusCode = HttpServletResponse.SC_FORBIDDEN;
                } else {
                    statusCode = HttpServletResponse.SC_NOT_FOUND;
                }
                resp.sendError(
                    statusCode,
                    MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { path.toString()}));
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    logger.exiting(CLASS_NAME,"handleRequest","Forbidden-WEB-INF/META-INF");
                return;
            }
            
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                logger.logp(Level.FINE, CLASS_NAME,"handleRequest"," after resolving the uri: path ---> " + path);

            
            //Liberty ArchiveAPI container to be used instead of File system.
            Container webModuleContainer = _webapp.getModuleContainer();

            /*
             * In Liberty, we'll leave the file system path as just the request path so we can keep 
             * the checks for illegal characters in the same code
             */
            fileSystemPath = path.toString();

            // PQ79698 part1 starts
            if (!isValidFilePath(fileSystemPath)) {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, nls.getString("File.name.contains.illegal.character", "File path contains illegal character."));
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                	logger.exiting(CLASS_NAME,"handleRequest","Forbidden-invalid file path");
                return;
            }
            // PQ79698 part1 ends
			// defect 220552: begin implement the deny feature for specified URI patterns
			else{
				Object matchedURI = denyPatterns.match(path.toString());
				if(matchedURI != null){	
					if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
						logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Attempted to serve URI that matches denied URL pattern URI =[" + path.toString() + "] matched [" + matchedURI + "]");
					}
					resp.sendError(HttpServletResponse.SC_FORBIDDEN,							
							MessageFormat.format(nls.getString(
							"File.not.found", "File not found: {0}"),
							new Object[] { path.toString() }));
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    	logger.exiting(CLASS_NAME,"handleRequest","Forbidden-denied pattern");
						return;
				}
			}
			// defect 220552: end implement the deny feature for specified URI patterns

            boolean fileIsDirectoryInDocumentRoot = false;         // PM17845

            File file = null;
            Entry entry = null;
            boolean requestForRoot = false;
           
            //Don't call getEntry for the root container's / as there is no entry.
            if(fileSystemPath.equals("/")){      
                requestForRoot = true;
            } 
            else {
                entry = webModuleContainer.getEntry(fileSystemPath);
            }
            
            //We failed to find something at the path, either in the filesystem or via the container.
            if ((file != null && !file.exists()) || (webModuleContainer != null && entry == null && !requestForRoot)) {
            	
            	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
    				logger.logp(Level.FINE, CLASS_NAME,"handleRequest","file does not exist --> " + path);
            	DocumentRootUtils docRoot = new DocumentRootUtils(context,extendedDocumentRoot,preFragmentExtendedDocumentRoot);
            	try {
            	    docRoot.handleDocumentRoots(path.toString());
            	} catch (FileNotFoundException fnfe) {
    				throw new FileNotFoundException(MessageFormat.format(nls.getString("File.not.found","File not found: {0}"), new Object[]{path}));
            	}
            	if (docRoot.isDirectory()) {
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    	logger.exiting(CLASS_NAME,"handleRequest","matchedfile is a directory");
    		    	if (!docRoot.isMatchedFromEDR() || WCCustomProperties.ALLOW_PARTIAL_URL_TO_EDR ) {
    		    		fileIsDirectoryInDocumentRoot = true;
    		    	} 
            	} else {
            		
                    if (isRequestForbidden(path))   
    	            {
                        resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(nls.getString("File.not.found","File not found: {0}"), new Object[]{httpRequest.getPathInfo()})); //PM88028
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        	logger.exiting(CLASS_NAME,"handleRequest","Forbidden-Extended doc root endsWith");
    		            return;
    	            }
            	
            	    ZipFileResource zipFileResource = docRoot.getMatchedZipFileResource();
            	    if (zipFileResource!=null)
            	    {            		
            		    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            		     logger.logp(Level.FINE, CLASS_NAME,"handleRequest","zip file found: Use ZipFileServletWrapper");
            			
           		         handleZipFileWrapper(req, httpRequest, resp, path, dispatchContext,zipFileResource);
           		         return;
            	     } else {
            	        EntryResource entryResource = docRoot.getMatchedEntryResource();
            	        if(entryResource != null){
            	            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	                logger.logp(Level.FINE, CLASS_NAME,"handleRequest","entry is found: Use EntryServletWrapper");
            	            EntryServletWrapper ewrapper = new EntryServletWrapper(_webapp, this, entryResource.getEntry());
            	            ewrapper.handleRequest(req, resp);
            	            
            	            if(!_webapp.isCachingEnabled()){

            	                //PM84305
            	                if(!_webapp.getConfiguration().isDisableStaticMappingCache()){
            	                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	                        logger.logp(Level.FINE, CLASS_NAME,"handleRequest","ewrapper addMappingTarget URI -> "+ path);

            	                    _webapp.addMappingTarget(path.toString(), ewrapper);
            	                }
            	                
            	                if (!dispatchContext.isInclude() && !dispatchContext.isForward()) {
            	                    WebContainer.addToCache(httpRequest, ewrapper, this._webapp); //PM88028
            	                }
            	            }
            	            
            	            return;
            	        }  
            	    
            	    
            		           		
            	        File matchedFile = docRoot.getMatchedFile();

            	        if (matchedFile !=null) {


            	            FileServletWrapper fwrapper = getStaticFileWrapper(_webapp, this, matchedFile);
            	            fwrapper.handleRequest(req, resp);
            	            if (!_webapp.isCachingEnabled()){
            	                try
            	                {
            	                    //PM84305
            	                    if(!_webapp.getConfiguration().isDisableStaticMappingCache()){
            	                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	                            logger.logp(Level.FINE, CLASS_NAME,"handleRequest","fwrapper addMappingTarget URI -> "+ path);

            	                        _webapp.addMappingTarget(path.toString(), fwrapper);
            	                    }

            	                    // begin 309663
            	                    // add to cache now versus wait until Webcontainer.handleRequest finds a IServletWrapper 
            	                    // (allows request.getPathInfo and request.servletPath() to stay valid)
            	                    if (!dispatchContext.isInclude() && !dispatchContext.isForward()) {
            	                        WebContainer.addToCache(httpRequest, fwrapper, this._webapp); //PM88028
            	                    }
            	                    // end 309663
            	                }
            	                catch (Exception e)
            	                {
            	                    // do nothing because its a race condition...won't happen again.
            	                }
            	            } 
            	            return;
            	        }
            	     }
            	}

               // PM17845 Add if statement
                if (!fileIsDirectoryInDocumentRoot) {
                    // Resource was not found...invoke filters                
    				throw new FileNotFoundException(MessageFormat.format(nls.getString("File.not.found","File not found: {0}"), new Object[]{path}));
                }   
            }    
            
            boolean isContainerDirectory = false;
            Container directory = null;
            // Determine if the entry is a directory
            if(webModuleContainer != null){
                if(requestForRoot){
                    directory = webModuleContainer;
                } else if (entry != null){
                    directory = entry.adapt(Container.class);
                }
                isContainerDirectory = requestForRoot || fileIsDirectoryInDocumentRoot || (entry.getSize()==0 && directory != null && directory.isRoot()==false);
            }
            
            // PM17845 Add check for ileIsDirectoryInExtendedDocumnetRoot
            if ((file != null && file.isDirectory()) || fileIsDirectoryInDocumentRoot || isContainerDirectory) 
            {
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
                    if (file != null) {
                        logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "file is a directory --> " + file.getPath());
                    } else if (entry!=null) {
                        logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "entry path --> " + entry.getPath());
                    } else {
                        logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "file is null");
                    }
                }
                
                /*
                 * The file is a directory so first see if we should append a trailing slash to the
                 * uri and redirect.  After that try and serve a welcome file or directory browse.
                 */
                String requestString = getURLWithRequestURIEncoded(httpRequest).toString(); //PM88028
                
                //start PI31447
                if(WCCustomProperties.IGNORE_SEMICOLON_ON_REDIRECT_TO_WELCOME_PAGE){
                        String requestURI = req.getRequestURI();
                        int indexAfterContextRoot = requestURI.indexOf(context.getContextPath()) + context.getContextPath().length();
                        if(!context.getContextPath().equals("/"))
                                //if the context root is not / look for the character after next since the next is /
                                indexAfterContextRoot++;
                        if(indexAfterContextRoot < requestURI.length() && requestURI.charAt(indexAfterContextRoot) == ';'){ 
                                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                                        logger.logp(Level.FINE, CLASS_NAME,"handleRequest","Removing semi-colon");
                                requestString = requestString.substring(0, requestString.indexOf(";"));
                        } 
                }
                //end PI31447
                
                String queryString = httpRequest.getQueryString(); //PM88028

                if (!requestString.endsWith("/")) {
                    if (isInclude == false) {
                        String tmpURL = requestString + "/"; // append a slash for redirect purposes.
//                        String qString;
//                        if ((qString = req.getQueryString()) != null) { // if query string exists; add it.
//                            tmpURL += "?" + qString;
//                        }
                        //PM88028
                        if (queryString != null){ // if query string exists; add it.
                            tmpURL += "?" +queryString;
                        }
                        
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","sendRedirect -->" + tmpURL);
                        
                        // encode redirect url to keep session info.
                        resp.sendRedirect(resp.encodeRedirectURL(tmpURL));
                        
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        	logger.exiting(CLASS_NAME,"handleRequest","redirect to context root");
                                              
                        return;
                    }
                }
                //begin PK10057
//                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
//                    logger.logp(Level.FINE, CLASS_NAME,"handleRequest","calling security check for URI --> " + path.toString() );
//                }
                
                //The preInvoke in WebAppFilterManager calls with doAuth/enforceSecurity=true
                //securityPreInvokes.push(secCollab.preInvoke ( req, resp, path.toString(), dispatchContext.isEnforceSecurity()));
             
//                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
//                    logger.logp(Level.FINE, CLASS_NAME,"handleRequest","returned from security check for URI --> " + path.toString() );
//                }
                //end PK10057
                
                String welcomeFileRedirectUri = null;
                String welcomeFileForwardUri = null;
                
                if ((welcomeFileList != null) && (welcomeFileList.size() != 0)) {
                	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                    	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Check welcome file list");
                	}
                    /*
                     * Check the welcome files to see if we should be serving
                     * one of them up here.
                     */
                    Iterator e = welcomeFileList.iterator();
                    String page = null;

                    while (e.hasNext()) {
                        page = (String) e.next();

                        if ((page.charAt(0) == '/'))
                            page = page.substring(1);

                        // begin 254491    [proxies BOTP] mis-handling of non-existent welcome-file's    WAS.webcontainer -- rewritten
                        RequestProcessor rp = _webapp.getRequestMapper().map(path.toString() + page);
                        if(rp == null){
                        	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "No request processor found for welcome file:" + path.toString() + page);
                        	}
                        	continue;
                        }
                        else if (rp instanceof WebExtensionProcessor){
                        	boolean available = ((WebExtensionProcessor)rp).isAvailable(path.toString() + page);
                        	if(available == false){
                        		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "No web extension processor found for welcome file:" + path.toString() + page);
                            	}
                        		continue;
                        	}
                        }
                        else if (rp instanceof IServletWrapper){
                        	boolean available = ((IServletWrapper)rp).isAvailable();
                        	if(available == false){
                        		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "No servlet wrapper found for welcome file:" + path.toString() + page);
                            	}  
                        		continue;
                        	}
                        }

                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                        	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Process welcome file: path: " + path.toString() + ", page: "+page);
                    	} 
                        // end 254491    [proxies BOTP] mis-handling of non-existent welcome-file's    WAS.webcontainer -- rewritten
                        if (redirectToWelcomeFile) {
                            String qString = "";
//                            if ((req.getQueryString()) != null) { // if query string exists; add it.
//                                qString = "?" + req.getQueryString();
//                            }
                            if(queryString != null) { // if query string exists; add it.
                                qString = "?" + queryString; //PM88028
                            }
                            String rPath = removeLeadingSlashes(path.toString());
                            if (rPath == null)
                                rPath = "";
                            //	BEGIN:PK15276
                            String redirectURI;
                            if(com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31 || WCCustomProperties.REDIRECT_WITH_PATH_INFO){
                                redirectURI= page + qString;
                                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                    logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Process welcome file: redirecting with pathInfo: " + redirectURI);
                                }
                            }
                            else{
                                redirectURI = rPath + page + qString;
                            }
                            
                            
                            
                            req.setAttribute("com.ibm.ws.webcontainer.welcomefile.redirecturl", redirectURI);
                            welcomeFileRedirectUri = redirectURI;

                        }
                        else {
                            //begin 267395    SVT: can not get Admin Console on Win2000 -- m0514.18 build    WAS.webcontainer    
                            String uri = path.toString() + page;
                            //PK78371 - start
                            if (WCCustomProperties.PROVIDE_QSTRING_TO_WELCOME_FILE){
//                                if ((req.getQueryString()) != null)
//                                    uri = uri + "?" + req.getQueryString();
                                if (queryString != null)
                                    uri = uri + "?" + queryString; //PM88028
                            }
                            //PK78371 - end 
                            req.setAttribute("com.ibm.ws.webcontainer.welcomefile.url", uri);
                            welcomeFileForwardUri = uri;
                        }
                        //end 267395    SVT: can not get Admin Console on Win2000 -- m0514.18 build    WAS.webcontainer    
                    	break; // Break out of the loop with the first match
                    }
                }
                
                if (welcomeFileRedirectUri!=null){
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.logp(Level.FINE,CLASS_NAME,"handleRequest", "sendRedirect to Welcome File:" + welcomeFileRedirectUri);

                    resp.sendRedirect(resp.encodeRedirectURL(welcomeFileRedirectUri));

                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.exiting(CLASS_NAME,"handleRequest");
                    return;

                } else if (welcomeFileForwardUri!=null){
                    RequestDispatcher rd = context.getRequestDispatcher(welcomeFileForwardUri);

                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.logp(Level.FINE,CLASS_NAME,"handleRequest", "forward :" + welcomeFileForwardUri);

                    rd.forward(req, resp);

                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.exiting(CLASS_NAME,"handleRequest");
                    return;
                }
                //End PK64097

                if (_webapp.getConfiguration().isDirectoryBrowsingEnabled()){
					RequestDispatcher dirBrowse = context.getRequestDispatcher(WebApp.DIR_BROWSING_MAPPING);

					if (dirBrowse != null) {
						
						/*
						 * invoke the directory browsing servlet
						 */
						req.setAttribute("com.ibm.servlet.engine.webapp.dir.browsing.path", fileSystemPath);
						req.setAttribute("com.ibm.servlet.engine.webapp.dir.browsing.uri", req.getRequestURI());

						  
						if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
							logger.logp(Level.FINE, CLASS_NAME,"handleRequest","Directory Browse" + fileSystemPath);           		
						dirBrowse.forward(req, resp);
						if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
							logger.exiting(CLASS_NAME,"handleRequest");
						return;
					}
                }

                /*
				 * could not find a welcome file and dir browsing not on
				 */    
                // PK31377 - added if/else
                if (!resp.isCommitted()){  
                    resp.sendError(404, MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] {pathInfo}));
       	   	  		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                	logger.exiting(CLASS_NAME,"handleRequest","handleRequest ---> File not found");
                }else{		    	   
                    logger.exiting("handleRequest", "handleRequest");               	
            	}
                //PK31377 - end
                return;
            }

		// PK23475 code to check for invalid charcters in the request moved to new private method isRequestForbidden

            // String matchString = path.toString();

            // defect 220552: removed checks for URI resources ending with "/" for JSP resources: handled above.

            /**
            * Do not allow ".." to appear in a path as it allows one to serve files from anywhere within
            * the file system.
            * Also check to see if the path or URI ends with '/', '\', or '.' .
            * PQ44346 - Allow files on DFS to be served.
            */
            //if ((matchString.lastIndexOf("..") != -1 && (!matchString.startsWith("/...")))
            //    || matchString.endsWith("\\")
            //    || req.getRequestURI().endsWith(".")
            //    // PK22928
            //    || req.getRequestURI().endsWith("/")){
            //    //PK22928
		
		    // PK23475 call isRequestForbidden to check if request includes ".." etc.
            if (isRequestForbidden(path))   
            {
                resp.sendError(
                    HttpServletResponse.SC_FORBIDDEN,
                    MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { pathInfo}));
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                	logger.exiting(CLASS_NAME,"handleRequest","handleRequest --> Forbidden-endsWith");
                return;
            }

            // 94578, "Case Sensitive Security Matching bug":  On Windows and Netware only, filename of
            //         requested file must exactly match case or we will throw FNF exception.
            if (webModuleContainer == null && com.ibm.ws.util.FileSystem.isCaseInsensitive) {
                File caseFile = new Java2SecurityFile(fileSystemPath);

                if (!com.ibm.ws.util.FileSystem.uriCaseCheck(caseFile, path.toString())) {
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","handleRequest --> Case sensitivity check - throw FileNotFoundException");               	
                    throw new FileNotFoundException(path.toString());
                }
            }
            // end 94578

            IServletWrapper fwrapper = null;
            
            if(file != null){
            // Create the FileServletWrapper to serve the file up.
              fwrapper = getStaticFileWrapper(_webapp, this, file);
			// 224858, must set pathElements for files mapped to staticFileServlet so getServletPath
			// is the same on the first request as on subsequent requests
        	//  begin 309663: should not be resetting path elements here (sitemesh issue since corrected).
			//dispatchContext.setPathElements(path.toString(),null);
        	//          end 309663
			// end 224858
            } else {
              fwrapper = getEntryWrapper(_webapp, this, entry);
            }
            
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","Use FileServletWrapper");
            
			fwrapper.handleRequest(req, resp);

			if (!_webapp.isCachingEnabled()){
			    try
			    {
			        //PM84305
			        if(!_webapp.getConfiguration().isDisableStaticMappingCache()){
			            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
			                logger.logp(Level.FINE, CLASS_NAME,"handleRequest","FileServletWrapper addMappingTarget URI -> "+ path);

			            _webapp.addMappingTarget(path.toString(), fwrapper);
			        }

			        // begin 309663
			        // add to cache now versus wait until Webcontainer.handleRequest finds a IServletWrapper 
			        // (allows request.getPathInfo and request.servletPath() to stay valid)
			        if (!dispatchContext.isInclude() && !dispatchContext.isForward()) {
			            WebContainer.addToCache(httpRequest, fwrapper, this._webapp); //PM88028
			        }
			        // end 309663			
			    }
			    catch (Exception e)
			    {
			        // do nothing because its a race condition...won't happen again.
			    }
			}
			
        }
        catch (FileNotFoundException e) 
		{
            // Give any registered FileNotFoundProcessors a chance to process the request
            if (!RegisterRequestInterceptor.notifyRequestInterceptors(RequestInterceptor.INTERCEPT_POINT_FNF,req, resp)) {
                 // PK64302 Start
                 if (!WCCustomProperties.THROW_404_IN_PREFERENCE_TO_403 && isDirectoryTraverse(path))   
                 {
                     resp.sendError(
                         HttpServletResponse.SC_FORBIDDEN,
                             MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { pathInfo}));
                     if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))
                         logger.exiting(CLASS_NAME, "handleRequest", "Forbidden-file does not exist");
                     return;
                 }
                 // PK64302 End
        	 // Begin PK27620
        	
        	WebAppErrorReport errorReport = new WebAppErrorReport(MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { e.getMessage()}), e);
    		logger.logp(Level.WARNING,CLASS_NAME,"handleRequest", e.getMessage());
            
        	errorReport.setErrorCode(HttpServletResponse.SC_NOT_FOUND);
        	errorReport.setTargetServletName ("DefaultExtensionProcessor");
        	
       		// Note: In V8 by default WCCustomProperties.MODIFIED_FNF_BEHAVIOR is true.
                if(!WCCustomProperties.MODIFIED_FNF_BEHAVIOR) { //PK65408
							
                com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest", "573", this);
							try
							{
								_webapp.sendError(req, resp, errorReport);
							}
							catch (Exception ex)
							{
								// ignore
							
							}
							//PK65408 Start
					 }
					else {
						if (!WCCustomProperties.SERVLET_30_FNF_BEHAVIOR||request.getDispatcherType()!=DispatcherType.INCLUDE){
							if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                				logger.logp(Level.FINE, CLASS_NAME,"handleRequest","dispatch type is not include, throw normal FNF");
                    
							fnf = e;
							resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
						}
						else {
//							Max: Must throw our own type of FNF to differentiate so we can support the following spec requirement
//							and not break backwards compatibility when the servlet itself throws FileNotFound or we're not in an include
//							Spec: If the default servlet is the target of a RequestDispatch.include() and the requested
//							resource does not exist, then the default servlet MUST throw
//							FileNotFoundException. If the exception isn't caught and handled, and the
//							response has not been committed, the status code MUST be set to 500.

							if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                				logger.logp(Level.FINE, CLASS_NAME,"handleRequest","throwing IncludeFileNotFoundException");
                    
							fnf = new IncludeFileNotFoundException(e.getMessage());
						}
						
					}
				
				
				// End PK27620
            }    
        }
	    catch (SecurityViolationException e){
	    	String strPath=null;
	    	if (path!=null){
	    		strPath=path.toString();
	    		collabHelper.processSecurityPreInvokeException (e, this, httpRequest, resp, dispatchContext, _webapp, strPath); //PM88028
	    	}
	    	return;
	    }
        finally {
            //begin PK10057
        	ThreadIdentityManager.reset(token);
        	
        	//The preInvoke in WebAppFilterManager calls with doAuth/enforceSecurity=true which will setup
//        	while (securityPreInvokes.size() != 0){ // may have null objects in list.
//        		secCollab.postInvoke(securityPreInvokes.pop());
//        	}
        	
        	//webAppNameSpaceCollab.postInvoke();
           //end PK10057
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","handleRequest");
          //PK65408 Start
    	    if(fnf!=null){
    	    	throw fnf;
    	    }
    	    //PK65408 End
        }
        return;
    }
614943
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest httpRequest,
                       HttpResponse httpResponse)
         throws IOException
    {
        if (!isStarted())
            return;
        
        // Handle TRACE
        if (HttpRequest.__TRACE.equals(httpRequest.getMethod()))
        {
            handleTrace(httpRequest,httpResponse);
            return;
        }

        // Look for existing request/response objects (from enterScope call)
        ServletHttpRequest request = (ServletHttpRequest) httpRequest.getWrapper();
        ServletHttpResponse response = (ServletHttpResponse) httpResponse.getWrapper();
        if (request==null)
        {
            // Not in ServletHttpContext, but bumble on anyway
            request = new ServletHttpRequest(this,pathInContext,httpRequest);
            response = new ServletHttpResponse(request,httpResponse);
            httpRequest.setWrapper(request);
            httpResponse.setWrapper(response);
        }
        else
        {
            request.recycle(this,pathInContext);
            response.recycle();
        }
        
        // Look for the servlet
        Map.Entry servlet=getHolderEntry(pathInContext);
        ServletHolder servletHolder=servlet==null?null:(ServletHolder)servlet.getValue();
        if(log.isDebugEnabled())log.debug("servlet="+servlet);
            
        try
        {
            // Adjust request paths
            if (servlet!=null)
            {
                String servletPathSpec=(String)servlet.getKey(); 
                request.setServletPaths(PathMap.pathMatch(servletPathSpec,pathInContext),
                                        PathMap.pathInfo(servletPathSpec,pathInContext),
                                        servletHolder);
            }
            
            // Handle the session ID
            request.setRequestedSessionId(pathParams);
            HttpSession session=request.getSession(false);
            if (session!=null)
                ((SessionManager.Session)session).access();
            if(log.isDebugEnabled())log.debug("session="+session);
            
            // Do that funky filter and servlet thang!
            if (servletHolder!=null)
                dispatch(pathInContext,request,response,servletHolder, Dispatcher.__REQUEST);
        }
        catch(Exception e)
        {
            log.debug(LogSupport.EXCEPTION,e);
            
            Throwable th=e;
            while (th instanceof ServletException)
            {
                log.warn(LogSupport.EXCEPTION, th);
                Throwable cause=((ServletException)th).getRootCause();
                if (cause==th || cause==null)
                    break;
                th=cause;
            }
            
            if (th instanceof HttpException)
                throw (HttpException)th;
            if (th instanceof EOFException)
                throw (IOException)th;
            else if (log.isDebugEnabled() || !( th instanceof java.io.IOException))
            {
                if (_contextLog!=null)
                {
                    if (th instanceof RuntimeException) 
                        _contextLog.error(httpRequest.getURI()+": ",th);
                    else
                        _contextLog.warn(httpRequest.getURI()+": ",th);
                }
                
                if(log.isDebugEnabled())
                {
                    if (th instanceof RuntimeException) 
                        log.error(httpRequest.getURI()+": ",th);
                    else
                        log.warn(httpRequest.getURI()+": ",th);
                    log.debug(httpRequest);
                }
            }
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
                if (th instanceof UnavailableException)
                {
                    UnavailableException ue = (UnavailableException)th;
                    if (ue.isPermanent())
                        response.sendError(HttpResponse.__404_Not_Found,e.getMessage());
                    else
                        response.sendError(HttpResponse.__503_Service_Unavailable,e.getMessage());
                }
                else
                    response.sendError(HttpResponse.__500_Internal_Server_Error,e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling "+th);
        }
        catch(Error e)
        {   
            log.warn("Error for "+httpRequest.getURI(),e);
            if(log.isDebugEnabled())log.debug(httpRequest);
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
                response.sendError(HttpResponse.__500_Internal_Server_Error,
                                   e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling ",e);
        }
        finally
        {
            if (servletHolder!=null && response!=null)
            {
                response.complete();
            }
        }
    }