Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   //
   //  ========================================================================
   //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
   //  ------------------------------------------------------------------------
   //  All rights reserved. This program and the accompanying materials
   //  are made available under the terms of the Eclipse Public License v1.0
   //  and Apache License v2.0 which accompanies this distribution.
   //
   //      The Eclipse Public License is available at
  //      http://www.eclipse.org/legal/epl-v10.html
  //
  //      The Apache License v2.0 is available at
  //      http://www.opensource.org/licenses/apache2.0.php
  //
  //  You may elect to redistribute this code under either of these licenses.
  //  ========================================================================
  //
  
  package org.eclipse.jetty.server.handler;
  
  import java.io.File;
  import java.net.URL;
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Locale;
  import java.util.Map;
  import java.util.Set;
  import java.util.EnumSet;
  
  
  
  /* ------------------------------------------------------------ */
ContextHandler. This handler wraps a call to handle by setting the context and servlet path, plus setting the context classloader.

If the context init parameter "org.eclipse.jetty.server.context.ManagedAttributes" is set to a comma separated list of names, then they are treated as context attribute names, which if set as attributes are passed to the servers Container so that they may be managed with JMX.

The maximum size of a form that can be processed by this context is controlled by the system properties org.eclipse.jetty.server.Request.maxFormKeys and org.eclipse.jetty.server.Request.maxFormContentSize. These can also be configured with setMaxFormContentSize(int) and setMaxFormKeys(int)

Org.apache.xbean.XBean:
description="Creates a basic HTTP context"
  
 public class ContextHandler extends ScopedHandler implements AttributesServer.Graceful
 {
     private static final Logger LOG = Log.getLogger(ContextHandler.class);
 
     private static final ThreadLocal<Context__context = new ThreadLocal<Context>();

    
If a context attribute with this name is set, it is interpreted as a comma separated list of attribute name. Any other context attributes that are set with a name from this list will result in a call to setManagedAttribute(java.lang.String,java.lang.Object), which typically initiates the creation of a JMX MBean for the attribute value.
 
     public static final String MANAGED_ATTRIBUTES = "org.eclipse.jetty.server.context.ManagedAttributes";
 
     /* ------------------------------------------------------------ */
    
Get the current ServletContext implementation.

Returns:
ServletContext implementation
 
     public static Context getCurrentContext()
     {
         return .get();
     }
 
     protected Context _scontext;
 
     private final AttributesMap _attributes;
     private final AttributesMap _contextAttributes;
     private final Map<StringString_initParams;
     private ClassLoader _classLoader;
     private String _contextPath = "/";
     private String _displayName;
     private Resource _baseResource;
     private MimeTypes _mimeTypes;
     private Map<StringString_localeEncodingMap;
     private String[] _welcomeFiles;
     private ErrorHandler _errorHandler;
     private String[] _vhosts;
     private Set<String_connectors;
     private EventListener[] _eventListeners;
     private Logger _logger;
     private boolean _allowNullPathInfo;
     private int _maxFormKeys = Integer.getInteger("org.eclipse.jetty.server.Request.maxFormKeys",1000).intValue();
     private int _maxFormContentSize = Integer.getInteger("org.eclipse.jetty.server.Request.maxFormContentSize",200000).intValue();
     private boolean _compactPath = false;
     private boolean _aliases = false;
 
     private Object _contextListeners;
     private Object _requestListeners;
     private Map<StringObject_managedAttributes;
     private String[] _protectedTargets;
 
     private boolean _shutdown = false;
     private boolean _available = true;
     private volatile int _availability// 0=STOPPED, 1=AVAILABLE, 2=SHUTDOWN, 3=UNAVAILABLE
 
     private final static int __STOPPED = 0, __AVAILABLE = 1, __SHUTDOWN = 2, __UNAVAILABLE = 3;
 
     /* ------------------------------------------------------------ */
    
 
     public ContextHandler()
     {
         super();
          = new Context();
          = new AttributesMap();
          = new AttributesMap();
          = new HashMap<StringString>();
     }
 
     /* ------------------------------------------------------------ */
    
 
     protected ContextHandler(Context context)
     {
         super();
          = context;
          = new AttributesMap();
          = new AttributesMap();
          = new HashMap<StringString>();
     }
 
     /* ------------------------------------------------------------ */
    
 
     public ContextHandler(String contextPath)
     {
         this();
         setContextPath(contextPath);
     }
 
     /* ------------------------------------------------------------ */
    
 
     public ContextHandler(HandlerContainer parentString contextPath)
     {
         this();
         setContextPath(contextPath);
         if (parent instanceof HandlerWrapper)
             ((HandlerWrapper)parent).setHandler(this);
         else if (parent instanceof HandlerCollection)
             ((HandlerCollection)parent).addHandler(this);
     }
 
     /* ------------------------------------------------------------ */
     @Override
     public void dump(Appendable outString indentthrows IOException
     {
         dumpThis(out);
         dump(out,indent,Collections.singletonList(new CLDump(getClassLoader())),TypeUtil.asList(getHandlers()),getBeans(),.entrySet(),
     }
 
     /* ------------------------------------------------------------ */
     public Context getServletContext()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
the allowNullPathInfo true if /context is not redirected to /context/
 
     public boolean getAllowNullPathInfo()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Parameters:
allowNullPathInfo true if /context is not redirected to /context/
 
     public void setAllowNullPathInfo(boolean allowNullPathInfo)
     {
          = allowNullPathInfo;
     }
 
     /* ------------------------------------------------------------ */
     @Override
     public void setServer(Server server)
     {
         if ( != null)
         {
             Server old_server = getServer();
             if (old_server != null && old_server != server)
                 old_server.getContainer().update(this,,null,"error",true);
             super.setServer(server);
             if (server != null && server != old_server)
                 server.getContainer().update(this,null,,"error",true);
             .setServer(server);
         }
         else
             super.setServer(server);
     }
 
     /* ------------------------------------------------------------ */
    
Set the virtual hosts for the context. Only requests that have a matching host header or fully qualified URL will be passed to that context with a virtual host name. A context with no virtual host names or a null virtual host name is available to all requests that are not served by a context with a matching virtual host name.

Parameters:
vhosts Array of virtual hosts that this context responds to. A null host name or null/empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names.
 
     public void setVirtualHosts(String[] vhosts)
     {
         if (vhosts == null)
         {
              = vhosts;
         }
         else
         {
              = new String[vhosts.length];
             for (int i = 0; i < vhosts.lengthi++)
                 [i] = normalizeHostname(vhosts[i]);
         }
     }
 
     /* ------------------------------------------------------------ */
    
Either set virtual hosts or add to an existing set of virtual hosts.

Parameters:
virtualHosts Array of virtual hosts that this context responds to. A null host name or null/empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names.
 
     public void addVirtualHosts(String[] virtualHosts)
     {
         if (virtualHosts == null)  // since this is add, we don't null the old ones
         {
             return;
         }
         else
         {
             List<StringcurrentVirtualHosts = null;
             if ( != null)
             {
                 currentVirtualHosts = new ArrayList<String>(Arrays.asList());
             }
             else
             {
                 currentVirtualHosts = new ArrayList<String>();
             }
 
             for (int i = 0; i < virtualHosts.lengthi++)
             {
                 String normVhost = normalizeHostname(virtualHosts[i]);
                 if (!currentVirtualHosts.contains(normVhost))
                 {
                     currentVirtualHosts.add(normVhost);
                 }
             }
              = currentVirtualHosts.toArray(new String[0]);
         }
     }
 
     /* ------------------------------------------------------------ */
    
Removes an array of virtual host entries, if this removes all entries the _vhosts will be set to null

Parameters:
virtualHosts Array of virtual hosts that this context responds to. A null host name or null/empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names.
 
     public void removeVirtualHosts(String[] virtualHosts)
     {
         if (virtualHosts == null)
         {
             return// do nothing
         }
         else if (  == null || . == 0)
         {
             return// do nothing
         }
         else
         {
             List<StringexistingVirtualHosts = new ArrayList<String>(Arrays.asList());
 
             for (int i = 0; i < virtualHosts.lengthi++)
             {
                 String toRemoveVirtualHost = normalizeHostname(virtualHosts[i]);
                 if (existingVirtualHosts.contains(toRemoveVirtualHost))
                 {
                     existingVirtualHosts.remove(toRemoveVirtualHost);
                 }
             }
 
             if (existingVirtualHosts.isEmpty())
             {
                  = null// if we ended up removing them all, just null out _vhosts
             }
             else
             {
                  = existingVirtualHosts.toArray(new String[0]);
             }
         }
     }
 
     /* ------------------------------------------------------------ */
    
Get the virtual hosts for the context. Only requests that have a matching host header or fully qualified URL will be passed to that context with a virtual host name. A context with no virtual host names or a null virtual host name is available to all requests that are not served by a context with a matching virtual host name.

Returns:
Array of virtual hosts that this context responds to. A null host name or empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names.
 
     public String[] getVirtualHosts()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
an array of connector names that this context will accept a request from.
 
     public String[] getConnectorNames()
     {
         if ( == null || .size() == 0)
             return null;
 
         return .toArray(new String[.size()]);
     }
 
     /* ------------------------------------------------------------ */
    
Set the names of accepted connectors. Names are either "host:port" or a specific configured name for a connector.

Parameters:
connectors If non null, an array of connector names that this context will accept a request from.
 
     public void setConnectorNames(String[] connectors)
     {
         if (connectors == null || connectors.length == 0)
              = null;
         else
              = new HashSet<String>(Arrays.asList(connectors));
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see javax.servlet.ServletContext#getAttribute(java.lang.String)
      */
     public Object getAttribute(String name)
     {
         return .getAttribute(name);
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see javax.servlet.ServletContext#getAttributeNames()
      */
     @SuppressWarnings("unchecked")
     public Enumeration getAttributeNames()
     {
         return AttributesMap.getAttributeNamesCopy();
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the attributes.
 
     public Attributes getAttributes()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the classLoader.
 
     public ClassLoader getClassLoader()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    
Make best effort to extract a file classpath from the context classloader

Returns:
Returns the classLoader.
 
     public String getClassPath()
     {
         if ( == null || !( instanceof URLClassLoader))
             return null;
         URLClassLoader loader = (URLClassLoader);
         URL[] urls = loader.getURLs();
         StringBuilder classpath = new StringBuilder();
         for (int i = 0; i < urls.lengthi++)
         {
             try
             {
                 Resource resource = newResource(urls[i]);
                 File file = resource.getFile();
                 if (file != null && file.exists())
                 {
                     if (classpath.length() > 0)
                         classpath.append(.);
                     classpath.append(file.getAbsolutePath());
                 }
             }
             catch (IOException e)
             {
                 .debug(e);
             }
         }
         if (classpath.length() == 0)
             return null;
         return classpath.toString();
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the _contextPath.
 
     public String getContextPath()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see javax.servlet.ServletContext#getInitParameter(java.lang.String)
      */
     public String getInitParameter(String name)
     {
         return .get(name);
     }
 
     /* ------------------------------------------------------------ */
     /*
      */
     public String setInitParameter(String nameString value)
     {
         return .put(name,value);
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see javax.servlet.ServletContext#getInitParameterNames()
      */
     @SuppressWarnings("rawtypes")
     {
         return Collections.enumeration(.keySet());
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
Returns the initParams.
 
     public Map<StringStringgetInitParams()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see javax.servlet.ServletContext#getServletContextName()
      */
     public String getDisplayName()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public EventListener[] getEventListeners()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    
 
     public void setEventListeners(EventListener[] eventListeners)
     {
          = null;
          = null;
          = null;
          = null;
 
          = eventListeners;
 
         for (int i = 0; eventListeners != null && i < eventListeners.lengthi++)
         {
             EventListener listener = [i];
 
             if (listener instanceof ServletContextListener)
                  = LazyList.add(,listener);
 
             if (listener instanceof ServletContextAttributeListener)
                  = LazyList.add(,listener);
 
             if (listener instanceof ServletRequestListener)
                  = LazyList.add(,listener);
 
             if (listener instanceof ServletRequestAttributeListener)
                  = LazyList.add(,listener);
         }
     }
 
     /* ------------------------------------------------------------ */
    
 
     public void addEventListener(EventListener listener)
     {
         setEventListeners((EventListener[])LazyList.addToArray(getEventListeners(),listener,EventListener.class));
     }
    
   
    
Apply any necessary restrictions on a programmatically added listener. Superclasses should implement.

Parameters:
listener
 
     public void restrictEventListener (EventListener listener)
     {
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
true if this context is accepting new requests
 
     public boolean isShutdown()
     {
         synchronized (this)
         {
             return !;
         }
     }
 
     /* ------------------------------------------------------------ */
    
Set shutdown status. This field allows for graceful shutdown of a context. A started context may be put into non accepting state so that existing requests can complete, but no new requests are accepted.

Parameters:
shutdown true if this context is (not?) accepting new requests
 
     public void setShutdown(boolean shutdown)
     {
         synchronized (this)
         {
              = shutdown;
         }
     }
 
     /* ------------------------------------------------------------ */
    

Returns:
false if this context is unavailable (sends 503)
 
     public boolean isAvailable()
     {
         synchronized (this)
         {
             return ;
         }
     }
 
     /* ------------------------------------------------------------ */
    
Set Available status.
 
     public void setAvailable(boolean available)
     {
         synchronized (this)
         {
              = available;
         }
     }
 
     /* ------------------------------------------------------------ */
     public Logger getLogger()
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
     public void setLogger(Logger logger)
     {
          = logger;
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see org.eclipse.thread.AbstractLifeCycle#doStart()
      */
     @Override
     protected void doStart() throws Exception
     {
          = ;
 
         if ( == null)
             throw new IllegalStateException("Null contextPath");
 
          = Log.getLogger(getDisplayName() == null?getContextPath():getDisplayName());
         ClassLoader old_classloader = null;
         Thread current_thread = null;
         Context old_context = null;
 
         try
         {
             // Set the classloader
             if ( != null)
             {
                 current_thread = Thread.currentThread();
                 old_classloader = current_thread.getContextClassLoader();
                 current_thread.setContextClassLoader();
             }
 
             if ( == null)
                  = new MimeTypes();
 
             old_context = .get();
             .set();
 
             // defers the calling of super.doStart()
             startContext();
 
             synchronized(this)
             {
             }
         }
         finally
         {
             .set(old_context);
 
             // reset the classloader
             if ( != null)
             {
                 current_thread.setContextClassLoader(old_classloader);
             }
 
         }
     }
 
     /* ------------------------------------------------------------ */
    
Extensible startContext. this method is called from doStart() instead of a call to super.doStart(). This allows derived classes to insert additional handling (Eg configuration) before the call to super.doStart by this method will start contained handlers.

 
     protected void startContext() throws Exception
     {
         String managedAttributes = .get();
         if (managedAttributes != null)
         {
              = new HashMap<StringObject>();
             String[] attributes = managedAttributes.split(",");
             for (String attribute : attributes)
                 .put(attribute,null);
 
             Enumeration e = .getAttributeNames();
             while (e.hasMoreElements())
             {
                 String name = (String)e.nextElement();
                 Object value = .getAttribute(name);
                 checkManagedAttribute(name,value);
             }
         }
 
         super.doStart();
 
         if ( != null)
             .start();
 
         // Context listeners
         if ( != null)
         {
             ServletContextEvent event = new ServletContextEvent();
             for (int i = 0; i < LazyList.size(); i++)
             {
                 callContextInitialized(((ServletContextListener)LazyList.get(i)), event);
             }
         }
     }
 
     /* ------------------------------------------------------------ */
     {
         l.contextInitialized(e);
         .info("started {}",this);
     }
 
     /* ------------------------------------------------------------ */
     {
         l.contextDestroyed(e);
     }
     
     /* ------------------------------------------------------------ */
     /*
      * @see org.eclipse.thread.AbstractLifeCycle#doStop()
      */
     @Override
     protected void doStop() throws Exception
     {
          = ;
 
         ClassLoader old_classloader = null;
         Thread current_thread = null;
 
         Context old_context = .get();
         .set();
         try
         {
             // Set the classloader
             if ( != null)
             {
                 current_thread = Thread.currentThread();
                 old_classloader = current_thread.getContextClassLoader();
                 current_thread.setContextClassLoader();
             }
 
             super.doStop();
 
             // Context listeners
             if ( != null)
             {
                 ServletContextEvent event = new ServletContextEvent();
                 for (int i = LazyList.size(); i-- > 0;)
                 {
                     ((ServletContextListener)LazyList.get(,i)).contextDestroyed(event);
                 }
             }
 
             if ( != null)
                 .stop();
 
             Enumeration e = .getAttributeNames();
             while (e.hasMoreElements())
             {
                 String name = (String)e.nextElement();
                 checkManagedAttribute(name,null);
             }
         }
         finally
         {
             .info("stopped {}",this);
             .set(old_context);
             // reset the classloader
             if ( != null)
                 current_thread.setContextClassLoader(old_classloader);
         }
 
     }
 
     /* ------------------------------------------------------------ */
     /*
      * @see org.eclipse.jetty.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
      */
     public boolean checkContext(final String targetfinal Request baseRequestfinal HttpServletResponse responsethrows IOExceptionServletException
     {
         DispatcherType dispatch = baseRequest.getDispatcherType();
 
         switch ()
         {
             case :
             case :
                 return false;
             case :
                 baseRequest.setHandled(true);
                 response.sendError(.);
                 return false;
             default:
                 if ((..equals(dispatch) && baseRequest.isHandled()))
                     return false;
         }
 
         // Check the vhosts
         if ( != null && . > 0)
         {
             String vhost = normalizeHostname(baseRequest.getServerName());
 
             boolean match = false;
 
             // TODO non-linear lookup
             for (int i = 0; !match && i < .i++)
             {
                 String contextVhost = [i];
                 if (contextVhost == null)
                     continue;
                 if (contextVhost.startsWith("*."))
                 {
                     // wildcard only at the beginning, and only for one additional subdomain level
                     match = contextVhost.regionMatches(true,2,vhost,vhost.indexOf(".") + 1,contextVhost.length() - 2);
                 }
                 else
                     match = contextVhost.equalsIgnoreCase(vhost);
             }
             if (!match)
                 return false;
         }
 
         // Check the connector
         if ( != null && .size() > 0)
         {
             String connector = AbstractHttpConnection.getCurrentConnection().getConnector().getName();
             if (connector == null || !.contains(connector))
                 return false;
         }
 
         // Are we not the root context?
         if (.length() > 1)
         {
             // reject requests that are not for us
             if (!target.startsWith())
                 return false;
             if (target.length() > .length() && target.charAt(.length()) != '/')
                 return false;
 
             // redirect null path infos
             if (! && .length() == target.length())
             {
                 // context request must end with /
                 baseRequest.setHandled(true);
                 if (baseRequest.getQueryString() != null)
                     response.sendRedirect(URIUtil.addPaths(baseRequest.getRequestURI(),.) + "?" + baseRequest.getQueryString());
                 else
                     response.sendRedirect(URIUtil.addPaths(baseRequest.getRequestURI(),.));
                 return false;
             }
         }
 
         return true;
     }
 
     /* ------------------------------------------------------------ */
    
 
     @Override
     public void doScope(String targetRequest baseRequestHttpServletRequest requestHttpServletResponse responsethrows IOExceptionServletException
     {
         if (.isDebugEnabled())
             .debug("scope {}|{}|{} @ {}",baseRequest.getContextPath(),baseRequest.getServletPath(),baseRequest.getPathInfo(),this);
 
         Context old_context = null;
         String old_context_path = null;
         String old_servlet_path = null;
         String old_path_info = null;
         ClassLoader old_classloader = null;
         Thread current_thread = null;
         String pathInfo = target;
 
         DispatcherType dispatch = baseRequest.getDispatcherType();
 
         old_context = baseRequest.getContext();
 
         // Are we already in this context?
         if (old_context != )
         {
             // check the target.
             if (..equals(dispatch) || ..equals(dispatch))
             {
                 if ()
                     target = URIUtil.compactPath(target);
                 if (!checkContext(target,baseRequest,response))
                     return;
 
                 if (target.length() > .length())
                 {
                     if (.length() > 1)
                         target = target.substring(.length());
                     pathInfo = target;
                 }
                 else if (.length() == 1)
                 {
                     target = .;
                     pathInfo = .;
                 }
                 else
                 {
                     target = .;
                     pathInfo = null;
                 }
             }
 
             // Set the classloader
             if ( != null)
             {
                 current_thread = Thread.currentThread();
                 old_classloader = current_thread.getContextClassLoader();
                 current_thread.setContextClassLoader();
             }
         }
 
         try
         {
             old_context_path = baseRequest.getContextPath();
             old_servlet_path = baseRequest.getServletPath();
             old_path_info = baseRequest.getPathInfo();
 
             // Update the paths
             baseRequest.setContext();
             .set();
             if (!..equals(dispatch) && target.startsWith("/"))
             {
                 if (.length() == 1)
                     baseRequest.setContextPath("");
                 else
                     baseRequest.setContextPath();
                 baseRequest.setServletPath(null);
                 baseRequest.setPathInfo(pathInfo);
             }
 
             if (.isDebugEnabled())
                .debug("context={}|{}|{} @ {}",baseRequest.getContextPath(),baseRequest.getServletPath(), baseRequest.getPathInfo(),this);
            // start manual inline of nextScope(target,baseRequest,request,response);
            if (never())
                nextScope(target,baseRequest,request,response);
            else if ( != null)
                .doScope(target,baseRequest,request,response);
            else if ( != null)
                .doHandle(target,baseRequest,request,response);
            else
                doHandle(target,baseRequest,request,response);
            // end manual inline (pathentic attempt to reduce stack depth)
        }
        finally
        {
            if (old_context != )
            {
                // reset the classloader
                if ( != null)
                {
                    current_thread.setContextClassLoader(old_classloader);
                }
                // reset the context and servlet path.
                baseRequest.setContext(old_context);
                .set(old_context);
                baseRequest.setContextPath(old_context_path);
                baseRequest.setServletPath(old_servlet_path);
                baseRequest.setPathInfo(old_path_info);
            }
        }
    }
    /* ------------------------------------------------------------ */
    
    @Override
    public void doHandle(String targetRequest baseRequestHttpServletRequest requestHttpServletResponse responsethrows IOExceptionServletException
    {
        final DispatcherType dispatch = baseRequest.getDispatcherType();
        final boolean new_context = baseRequest.takeNewContext();
        try
        {
            if (new_context)
            {
                // Handle the REALLY SILLY request events!
                if ( != null)
                {
                    final int s = LazyList.size();
                    for (int i = 0; i < si++)
                        baseRequest.addEventListener(((EventListener)LazyList.get(,i)));
                }
                if ( != null)
                {
                    final int s = LazyList.size();
                    final ServletRequestEvent sre = new ServletRequestEvent(,request);
                    for (int i = 0; i < si++)
                        ((ServletRequestListener)LazyList.get(,i)).requestInitialized(sre);
                }
            }
            if (..equals(dispatch) && isProtectedTarget(target))
                throw new HttpException(.);
            // start manual inline of nextHandle(target,baseRequest,request,response);
            // noinspection ConstantIfStatement
            if (never())
                nextHandle(target,baseRequest,request,response);
            else if ( != null &&  == )
                .doHandle(target,baseRequest,request,response);
            else if ( != null)
                .handle(target,baseRequest,request,response);
            // end manual inline
        }
        catch (HttpException e)
        {
            .debug(e);
            baseRequest.setHandled(true);
            response.sendError(e.getStatus(),e.getReason());
        }
        finally
        {
            // Handle more REALLY SILLY request events!
            if (new_context)
            {
                if ( != null)
                {
                    final ServletRequestEvent sre = new ServletRequestEvent(,request);
                    for (int i = LazyList.size(); i-- > 0;)
                        ((ServletRequestListener)LazyList.get(,i)).requestDestroyed(sre);
                }
                if ( != null)
                {
                    for (int i = LazyList.size(); i-- > 0;)
                        baseRequest.removeEventListener(((EventListener)LazyList.get(,i)));
                }
            }
        }
    }
    /* ------------------------------------------------------------ */
    /*
     * Handle a runnable in this context
     */
    public void handle(Runnable runnable)
    {
        ClassLoader old_classloader = null;
        Thread current_thread = null;
        Context old_context = null;
        try
        {
            old_context = .get();
            .set();
            // Set the classloader
            if ( != null)
            {
                current_thread = Thread.currentThread();
                old_classloader = current_thread.getContextClassLoader();
                current_thread.setContextClassLoader();
            }
            runnable.run();
        }
        finally
        {
            .set(old_context);
            if (old_classloader != null)
            {
                current_thread.setContextClassLoader(old_classloader);
            }
        }
    }
    /* ------------------------------------------------------------ */
    
Check the target. Called by ScopedHandler.handle(java.lang.String,org.eclipse.jetty.server.Request,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) when a target within a context is determined. If the target is protected, 404 is returned.
    /* ------------------------------------------------------------ */
    public boolean isProtectedTarget(String target)
    {
        if (target == null ||  == null)
            return false;
        
        while (target.startsWith("//"))
            target=URIUtil.compactPath(target);
        
        boolean isProtected = false;
        int i=0;
        while (!isProtected && i<.)
        {
            isProtected = StringUtil.startsWithIgnoreCase(target[i++]);
        }
        return isProtected;
    }
    
    
    public void setProtectedTargets (String[] targets)
    {
        if (targets == null)
        {
             = null;
            return;
        }
        
         = new String[targets.length];
        System.arraycopy(targets, 0, , 0, targets.length);
    }
    
    public String[] getProtectedTargets ()
    {
        if ( == null)
            return null;
        
        String[] tmp = new String[.];
        System.arraycopy(, 0, tmp, 0, .);
        return tmp;
    }
    
    /* ------------------------------------------------------------ */
    /*
     * @see javax.servlet.ServletContext#removeAttribute(java.lang.String)
     */
    public void removeAttribute(String name)
    {
        checkManagedAttribute(name,null);
        .removeAttribute(name);
    }