jetty-servlet-8.1.0.v20120127

16:37:33.867 INFO  jd.cli.Main - Decompiling jetty-servlet-8.1.0.v20120127.jar
package org.eclipse.jetty.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletSecurityElement;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.continuation.ContinuationThrowable;
import org.eclipse.jetty.http.HttpException;
import org.eclipse.jetty.http.PathMap;
import org.eclipse.jetty.http.PathMap.Entry;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.security.IdentityService;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.server.AbstractHttpConnection;
import org.eclipse.jetty.server.Dispatcher;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServletRequestHttpWrapper;
import org.eclipse.jetty.server.ServletResponseHttpWrapper;
import org.eclipse.jetty.server.UserIdentity.Scope;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.handler.ScopedHandler;
import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

public class ServletHandler
  extends ScopedHandler
{
  private static final Logger LOG = Log.getLogger(ServletHandler.class);
  public static final String __DEFAULT_SERVLET = "default";
  private ServletContextHandler _contextHandler;
  private ContextHandler.Context _servletContext;
  private FilterHolder[] _filters = new FilterHolder[0];
  private FilterMapping[] _filterMappings;
  private boolean _filterChainsCached = true;
  private int _maxFilterChainsCacheSize = 512;
  private boolean _startWithUnavailable = true;
  private IdentityService _identityService;
  private ServletHolder[] _servlets = new ServletHolder[0];
  private ServletMapping[] _servletMappings;
  private final Map<String, FilterHolder> _filterNameMap = new HashMap();
  private List<FilterMapping> _filterPathMappings;
  private MultiMap<String> _filterNameMappings;
  private final Map<String, ServletHolder> _servletNameMap = new HashMap();
  private PathMap _servletPathMap;
  protected final ConcurrentMap<String, FilterChain>[] _chainCache = new ConcurrentMap[31];
  protected final Queue<String>[] _chainLRU = new Queue[31];
  
  public void setServer(Server server)
  {
    Server old = getServer();
    if ((old != null) && (old != server))
    {
      getServer().getContainer().update(this, _filters, null, "filter", true);
      getServer().getContainer().update(this, _filterMappings, null, "filterMapping", true);
      getServer().getContainer().update(this, _servlets, null, "servlet", true);
      getServer().getContainer().update(this, _servletMappings, null, "servletMapping", true);
    }
    super.setServer(server);
    if ((server != null) && (old != server))
    {
      server.getContainer().update(this, null, _filters, "filter", true);
      server.getContainer().update(this, null, _filterMappings, "filterMapping", true);
      server.getContainer().update(this, null, _servlets, "servlet", true);
      server.getContainer().update(this, null, _servletMappings, "servletMapping", true);
    }
  }
  
  protected synchronized void doStart()
    throws Exception
  {
    _servletContext = ContextHandler.getCurrentContext();
    _contextHandler = ((ServletContextHandler)(_servletContext == null ? null : _servletContext.getContextHandler()));
    if (_contextHandler != null)
    {
      SecurityHandler security_handler = (SecurityHandler)_contextHandler.getChildHandlerByClass(SecurityHandler.class);
      if (security_handler != null) {
        _identityService = security_handler.getIdentityService();
      }
    }
    updateNameMappings();
    updateMappings();
    if (_filterChainsCached)
    {
      _chainCache[1] = new ConcurrentHashMap();
      _chainCache[2] = new ConcurrentHashMap();
      _chainCache[4] = new ConcurrentHashMap();
      _chainCache[8] = new ConcurrentHashMap();
      _chainCache[16] = new ConcurrentHashMap();
      
      _chainLRU[1] = new ConcurrentLinkedQueue();
      _chainLRU[2] = new ConcurrentLinkedQueue();
      _chainLRU[4] = new ConcurrentLinkedQueue();
      _chainLRU[8] = new ConcurrentLinkedQueue();
      _chainLRU[16] = new ConcurrentLinkedQueue();
    }
    super.doStart();
    if ((_contextHandler == null) || (!(_contextHandler instanceof ServletContextHandler))) {
      initialize();
    }
  }
  
  protected synchronized void doStop()
    throws Exception
  {
    super.doStop();
    if (_filters != null) {
      for (int i = _filters.length; i-- > 0; LOG.warn("EXCEPTION ", e)) {
        try
        {
          _filters[i].stop();
        }
        catch (Exception e) {}
      }
    }
    if (_servlets != null) {
      for (int i = _servlets.length; i-- > 0; LOG.warn("EXCEPTION ", e)) {
        try
        {
          _servlets[i].stop();
        }
        catch (Exception e) {}
      }
    }
    _filterPathMappings = null;
    _filterNameMappings = null;
    
    _servletPathMap = null;
  }
  
  IdentityService getIdentityService()
  {
    return _identityService;
  }
  
  public Object getContextLog()
  {
    return null;
  }
  
  public FilterMapping[] getFilterMappings()
  {
    return _filterMappings;
  }
  
  public FilterHolder[] getFilters()
  {
    return _filters;
  }
  
  public PathMap.Entry getHolderEntry(String pathInContext)
  {
    if (_servletPathMap == null) {
      return null;
    }
    return _servletPathMap.getMatch(pathInContext);
  }
  
  public RequestDispatcher getRequestDispatcher(String uriInContext)
  {
    if ((uriInContext == null) || (_contextHandler == null)) {
      return null;
    }
    if (!uriInContext.startsWith("/")) {
      return null;
    }
    try
    {
      String query = null;
      int q;
      if ((q = uriInContext.indexOf('?')) > 0)
      {
        query = uriInContext.substring(q + 1);
        uriInContext = uriInContext.substring(0, q);
      }
      if ((q = uriInContext.indexOf(';')) > 0) {
        uriInContext = uriInContext.substring(0, q);
      }
      String pathInContext = URIUtil.canonicalPath(URIUtil.decodePath(uriInContext));
      String uri = URIUtil.addPaths(_contextHandler.getContextPath(), uriInContext);
      return new Dispatcher(_contextHandler, uri, pathInContext, query);
    }
    catch (Exception e)
    {
      LOG.ignore(e);
    }
    return null;
  }
  
  public ServletContext getServletContext()
  {
    return _servletContext;
  }
  
  public ServletMapping[] getServletMappings()
  {
    return _servletMappings;
  }
  
  public ServletMapping getServletMapping(String pattern)
  {
    if (_servletMappings != null) {
      for (ServletMapping m : _servletMappings)
      {
        String[] paths = m.getPathSpecs();
        if (paths != null) {
          for (String path : paths) {
            if (pattern.equals(path)) {
              return m;
            }
          }
        }
      }
    }
    return null;
  }
  
  public ServletHolder[] getServlets()
  {
    return _servlets;
  }
  
  public ServletHolder getServlet(String name)
  {
    return (ServletHolder)_servletNameMap.get(name);
  }
  
  public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
  {
    String old_servlet_path = baseRequest.getServletPath();
    String old_path_info = baseRequest.getPathInfo();
    
    DispatcherType type = baseRequest.getDispatcherType();
    
    ServletHolder servlet_holder = null;
    UserIdentity.Scope old_scope = null;
    if (target.startsWith("/"))
    {
      PathMap.Entry entry = getHolderEntry(target);
      if (entry != null)
      {
        servlet_holder = (ServletHolder)entry.getValue();
        
        String servlet_path_spec = (String)entry.getKey();
        String servlet_path = entry.getMapped() != null ? entry.getMapped() : PathMap.pathMatch(servlet_path_spec, target);
        String path_info = PathMap.pathInfo(servlet_path_spec, target);
        if (DispatcherType.INCLUDE.equals(type))
        {
          baseRequest.setAttribute("javax.servlet.include.servlet_path", servlet_path);
          baseRequest.setAttribute("javax.servlet.include.path_info", path_info);
        }
        else
        {
          baseRequest.setServletPath(servlet_path);
          baseRequest.setPathInfo(path_info);
        }
      }
    }
    else
    {
      servlet_holder = (ServletHolder)_servletNameMap.get(target);
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("servlet {}|{}|{} -> {}", new Object[] { baseRequest.getContextPath(), baseRequest.getServletPath(), baseRequest.getPathInfo(), servlet_holder });
    }
    try
    {
      old_scope = baseRequest.getUserIdentityScope();
      baseRequest.setUserIdentityScope(servlet_holder);
      if (never()) {
        nextScope(target, baseRequest, request, response);
      } else if (_nextScope != null) {
        _nextScope.doScope(target, baseRequest, request, response);
      } else if (_outerScope != null) {
        _outerScope.doHandle(target, baseRequest, request, response);
      } else {
        doHandle(target, baseRequest, request, response);
      }
    }
    finally
    {
      if (old_scope != null) {
        baseRequest.setUserIdentityScope(old_scope);
      }
      if (!DispatcherType.INCLUDE.equals(type))
      {
        baseRequest.setServletPath(old_servlet_path);
        baseRequest.setPathInfo(old_path_info);
      }
    }
  }
  
  public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
  {
    DispatcherType type = baseRequest.getDispatcherType();
    
    ServletHolder servlet_holder = (ServletHolder)baseRequest.getUserIdentityScope();
    FilterChain chain = null;
    if (target.startsWith("/"))
    {
      if ((servlet_holder != null) && (_filterMappings != null) && (_filterMappings.length > 0)) {
        chain = getFilterChain(baseRequest, target, servlet_holder);
      }
    }
    else if (servlet_holder != null) {
      if ((_filterMappings != null) && (_filterMappings.length > 0)) {
        chain = getFilterChain(baseRequest, null, servlet_holder);
      }
    }
    LOG.debug("chain={}", new Object[] { chain });
    try
    {
      if (servlet_holder == null)
      {
        if (getHandler() == null) {
          notFound(request, response);
        } else {
          nextHandle(target, baseRequest, request, response);
        }
      }
      else
      {
        ServletRequest req = request;
        if ((req instanceof ServletRequestHttpWrapper)) {
          req = ((ServletRequestHttpWrapper)req).getRequest();
        }
        ServletResponse res = response;
        if ((res instanceof ServletResponseHttpWrapper)) {
          res = ((ServletResponseHttpWrapper)res).getResponse();
        }
        if (chain != null) {
          chain.doFilter(req, res);
        } else {
          servlet_holder.handle(baseRequest, req, res);
        }
      }
    }
    catch (EofException e)
    {
      throw e;
    }
    catch (RuntimeIOException e)
    {
      throw e;
    }
    catch (ContinuationThrowable e)
    {
      throw e;
    }
    catch (Exception e)
    {
      if ((!DispatcherType.REQUEST.equals(type)) && (!DispatcherType.ASYNC.equals(type)))
      {
        if ((e instanceof IOException)) {
          throw ((IOException)e);
        }
        if ((e instanceof RuntimeException)) {
          throw ((RuntimeException)e);
        }
        if ((e instanceof ServletException)) {
          throw ((ServletException)e);
        }
      }
      Throwable th = e;
      if ((th instanceof UnavailableException))
      {
        LOG.debug(th);
      }
      else if ((th instanceof ServletException))
      {
        LOG.debug(th);
        Throwable cause = ((ServletException)th).getRootCause();
        if (cause != null) {
          th = cause;
        }
      }
      else if ((th instanceof RuntimeIOException))
      {
        LOG.debug(th);
        Throwable cause = (IOException)((RuntimeIOException)th).getCause();
        if (cause != null) {
          th = cause;
        }
      }
      if ((th instanceof HttpException)) {
        throw ((HttpException)th);
      }
      if ((th instanceof RuntimeIOException)) {
        throw ((RuntimeIOException)th);
      }
      if ((th instanceof EofException)) {
        throw ((EofException)th);
      }
      if (LOG.isDebugEnabled())
      {
        LOG.warn(request.getRequestURI(), th);
        LOG.debug(request.toString(), new Object[0]);
      }
      else if (((th instanceof IOException)) || ((th instanceof UnavailableException)))
      {
        LOG.debug(request.getRequestURI(), th);
      }
      else
      {
        LOG.warn(request.getRequestURI(), th);
      }
      if (!response.isCommitted())
      {
        request.setAttribute("javax.servlet.error.exception_type", th.getClass());
        request.setAttribute("javax.servlet.error.exception", th);
        if ((th instanceof UnavailableException))
        {
          UnavailableException ue = (UnavailableException)th;
          if (ue.isPermanent()) {
            response.sendError(404, th.getMessage());
          } else {
            response.sendError(503, th.getMessage());
          }
        }
        else
        {
          response.sendError(500, th.getMessage());
        }
      }
      else
      {
        LOG.debug("Response already committed for handling " + th, new Object[0]);
      }
    }
    catch (Error e)
    {
      if ((!DispatcherType.REQUEST.equals(type)) && (!DispatcherType.ASYNC.equals(type))) {
        throw e;
      }
      LOG.warn("Error for " + request.getRequestURI(), e);
      if (LOG.isDebugEnabled()) {
        LOG.debug(request.toString(), new Object[0]);
      }
      if (!response.isCommitted())
      {
        request.setAttribute("javax.servlet.error.exception_type", e.getClass());
        request.setAttribute("javax.servlet.error.exception", e);
        response.sendError(500, e.getMessage());
      }
      else
      {
        LOG.debug("Response already committed for handling ", e);
      }
    }
    finally
    {
      baseRequest.setHandled(true);
    }
  }
  
  private FilterChain getFilterChain(Request baseRequest, String pathInContext, ServletHolder servletHolder)
  {
    String key = pathInContext == null ? servletHolder.getName() : pathInContext;
    int dispatch = FilterMapping.dispatch(baseRequest.getDispatcherType());
    if ((_filterChainsCached) && (_chainCache != null))
    {
      FilterChain chain = (FilterChain)_chainCache[dispatch].get(key);
      if (chain != null) {
        return chain;
      }
    }
    Object filters = null;
    if ((pathInContext != null) && (_filterPathMappings != null)) {
      for (int i = 0; i < _filterPathMappings.size(); i++)
      {
        FilterMapping mapping = (FilterMapping)_filterPathMappings.get(i);
        if (mapping.appliesTo(pathInContext, dispatch)) {
          filters = LazyList.add(filters, mapping.getFilterHolder());
        }
      }
    }
    if ((servletHolder != null) && (_filterNameMappings != null) && (_filterNameMappings.size() > 0)) {
      if (_filterNameMappings.size() > 0)
      {
        Object o = _filterNameMappings.get(servletHolder.getName());
        for (int i = 0; i < LazyList.size(o); i++)
        {
          FilterMapping mapping = (FilterMapping)LazyList.get(o, i);
          if (mapping.appliesTo(dispatch)) {
            filters = LazyList.add(filters, mapping.getFilterHolder());
          }
        }
        o = _filterNameMappings.get("*");
        for (int i = 0; i < LazyList.size(o); i++)
        {
          FilterMapping mapping = (FilterMapping)LazyList.get(o, i);
          if (mapping.appliesTo(dispatch)) {
            filters = LazyList.add(filters, mapping.getFilterHolder());
          }
        }
      }
    }
    if (filters == null) {
      return null;
    }
    FilterChain chain = null;
    if (_filterChainsCached)
    {
      if (LazyList.size(filters) > 0) {
        chain = new CachedChain(filters, servletHolder);
      }
      Map<String, FilterChain> cache = _chainCache[dispatch];
      Queue<String> lru = _chainLRU[dispatch];
      while ((_maxFilterChainsCacheSize > 0) && (cache.size() >= _maxFilterChainsCacheSize))
      {
        String k = (String)lru.poll();
        if (k == null)
        {
          cache.clear();
          break;
        }
        cache.remove(k);
      }
      cache.put(key, chain);
      lru.add(key);
    }
    else if (LazyList.size(filters) > 0)
    {
      chain = new Chain(baseRequest, filters, servletHolder);
    }
    return chain;
  }
  
  private void invalidateChainsCache()
  {
    if (_chainLRU[1] != null)
    {
      _chainLRU[1].clear();
      _chainLRU[2].clear();
      _chainLRU[4].clear();
      _chainLRU[8].clear();
      _chainLRU[16].clear();
      
      _chainCache[1].clear();
      _chainCache[2].clear();
      _chainCache[4].clear();
      _chainCache[8].clear();
      _chainCache[16].clear();
    }
  }
  
  public boolean isAvailable()
  {
    if (!isStarted()) {
      return false;
    }
    ServletHolder[] holders = getServlets();
    for (int i = 0; i < holders.length; i++)
    {
      ServletHolder holder = holders[i];
      if ((holder != null) && (!holder.isAvailable())) {
        return false;
      }
    }
    return true;
  }
  
  public void setStartWithUnavailable(boolean start)
  {
    _startWithUnavailable = start;
  }
  
  public boolean isStartWithUnavailable()
  {
    return _startWithUnavailable;
  }
  
  public void initialize()
    throws Exception
  {
    MultiException mx = new MultiException();
    if (_filters != null) {
      for (int i = 0; i < _filters.length; i++) {
        _filters[i].start();
      }
    }
    if (_servlets != null)
    {
      ServletHolder[] servlets = (ServletHolder[])_servlets.clone();
      Arrays.sort(servlets);
      for (int i = 0; i < servlets.length; i++) {
        try
        {
          if ((servlets[i].getClassName() == null) && (servlets[i].getForcedPath() != null))
          {
            ServletHolder forced_holder = (ServletHolder)_servletPathMap.match(servlets[i].getForcedPath());
            if ((forced_holder == null) || (forced_holder.getClassName() == null)) {
              mx.add(new IllegalStateException("No forced path servlet for " + servlets[i].getForcedPath()));
            } else {
              servlets[i].setClassName(forced_holder.getClassName());
            }
          }
          else
          {
            servlets[i].start();
          }
        }
        catch (Throwable e)
        {
          LOG.debug("EXCEPTION ", e);
          mx.add(e);
        }
      }
      mx.ifExceptionThrow();
    }
  }
  
  public boolean isFilterChainsCached()
  {
    return _filterChainsCached;
  }
  
  public ServletHolder newServletHolder(Holder.Source source)
  {
    return new ServletHolder(source);
  }
  
  public ServletHolder addServletWithMapping(String className, String pathSpec)
  {
    ServletHolder holder = newServletHolder(null);
    holder.setName(className + "-" + LazyList.size(_servlets));
    holder.setClassName(className);
    addServletWithMapping(holder, pathSpec);
    return holder;
  }
  
  public ServletHolder addServletWithMapping(Class<? extends Servlet> servlet, String pathSpec)
  {
    ServletHolder holder = newServletHolder(Holder.Source.EMBEDDED);
    holder.setHeldClass(servlet);
    setServlets((ServletHolder[])LazyList.addToArray(getServlets(), holder, ServletHolder.class));
    addServletWithMapping(holder, pathSpec);
    
    return holder;
  }
  
  public void addServletWithMapping(ServletHolder servlet, String pathSpec)
  {
    ServletHolder[] holders = getServlets();
    if (holders != null) {
      holders = (ServletHolder[])holders.clone();
    }
    try
    {
      setServlets((ServletHolder[])LazyList.addToArray(holders, servlet, ServletHolder.class));
      
      ServletMapping mapping = new ServletMapping();
      mapping.setServletName(servlet.getName());
      mapping.setPathSpec(pathSpec);
      setServletMappings((ServletMapping[])LazyList.addToArray(getServletMappings(), mapping, ServletMapping.class));
    }
    catch (Exception e)
    {
      setServlets(holders);
      if ((e instanceof RuntimeException)) {
        throw ((RuntimeException)e);
      }
      throw new RuntimeException(e);
    }
  }
  
  public void addServlet(ServletHolder holder)
  {
    setServlets((ServletHolder[])LazyList.addToArray(getServlets(), holder, ServletHolder.class));
  }
  
  public void addServletMapping(ServletMapping mapping)
  {
    setServletMappings((ServletMapping[])LazyList.addToArray(getServletMappings(), mapping, ServletMapping.class));
  }
  
  public Set<String> setServletSecurity(ServletRegistration.Dynamic registration, ServletSecurityElement servletSecurityElement)
  {
    if (_contextHandler != null) {
      return _contextHandler.setServletSecurity(registration, servletSecurityElement);
    }
    return Collections.emptySet();
  }
  
  public FilterHolder newFilterHolder(Holder.Source source)
  {
    return new FilterHolder(source);
  }
  
  public FilterHolder getFilter(String name)
  {
    return (FilterHolder)_filterNameMap.get(name);
  }
  
  public FilterHolder addFilterWithMapping(Class<? extends Filter> filter, String pathSpec, EnumSet<DispatcherType> dispatches)
  {
    FilterHolder holder = newFilterHolder(Holder.Source.EMBEDDED);
    holder.setHeldClass(filter);
    addFilterWithMapping(holder, pathSpec, dispatches);
    
    return holder;
  }
  
  public FilterHolder addFilterWithMapping(String className, String pathSpec, EnumSet<DispatcherType> dispatches)
  {
    FilterHolder holder = newFilterHolder(Holder.Source.EMBEDDED);
    holder.setName(className + "-" + _filters.length);
    holder.setClassName(className);
    
    addFilterWithMapping(holder, pathSpec, dispatches);
    return holder;
  }
  
  public void addFilterWithMapping(FilterHolder holder, String pathSpec, EnumSet<DispatcherType> dispatches)
  {
    FilterHolder[] holders = getFilters();
    if (holders != null) {
      holders = (FilterHolder[])holders.clone();
    }
    try
    {
      setFilters((FilterHolder[])LazyList.addToArray(holders, holder, FilterHolder.class));
      
      FilterMapping mapping = new FilterMapping();
      mapping.setFilterName(holder.getName());
      mapping.setPathSpec(pathSpec);
      mapping.setDispatcherTypes(dispatches);
      setFilterMappings((FilterMapping[])LazyList.addToArray(getFilterMappings(), mapping, FilterMapping.class));
    }
    catch (RuntimeException e)
    {
      setFilters(holders);
      throw e;
    }
    catch (Error e)
    {
      setFilters(holders);
      throw e;
    }
  }
  
  public FilterHolder addFilterWithMapping(Class<? extends Filter> filter, String pathSpec, int dispatches)
  {
    FilterHolder holder = newFilterHolder(Holder.Source.EMBEDDED);
    holder.setHeldClass(filter);
    addFilterWithMapping(holder, pathSpec, dispatches);
    
    return holder;
  }
  
  public FilterHolder addFilterWithMapping(String className, String pathSpec, int dispatches)
  {
    FilterHolder holder = newFilterHolder(null);
    holder.setName(className + "-" + _filters.length);
    holder.setClassName(className);
    
    addFilterWithMapping(holder, pathSpec, dispatches);
    return holder;
  }
  
  public void addFilterWithMapping(FilterHolder holder, String pathSpec, int dispatches)
  {
    FilterHolder[] holders = getFilters();
    if (holders != null) {
      holders = (FilterHolder[])holders.clone();
    }
    try
    {
      setFilters((FilterHolder[])LazyList.addToArray(holders, holder, FilterHolder.class));
      
      FilterMapping mapping = new FilterMapping();
      mapping.setFilterName(holder.getName());
      mapping.setPathSpec(pathSpec);
      mapping.setDispatches(dispatches);
      setFilterMappings((FilterMapping[])LazyList.addToArray(getFilterMappings(), mapping, FilterMapping.class));
    }
    catch (RuntimeException e)
    {
      setFilters(holders);
      throw e;
    }
    catch (Error e)
    {
      setFilters(holders);
      throw e;
    }
  }
  
  /**
   * @deprecated
   */
  public FilterHolder addFilter(String className, String pathSpec, EnumSet<DispatcherType> dispatches)
  {
    return addFilterWithMapping(className, pathSpec, dispatches);
  }
  
  public void addFilter(FilterHolder filter, FilterMapping filterMapping)
  {
    if (filter != null) {
      setFilters((FilterHolder[])LazyList.addToArray(getFilters(), filter, FilterHolder.class));
    }
    if (filterMapping != null) {
      setFilterMappings((FilterMapping[])LazyList.addToArray(getFilterMappings(), filterMapping, FilterMapping.class));
    }
  }
  
  public void addFilter(FilterHolder filter)
  {
    if (filter != null) {
      setFilters((FilterHolder[])LazyList.addToArray(getFilters(), filter, FilterHolder.class));
    }
  }
  
  public void addFilterMapping(FilterMapping mapping)
  {
    if (mapping != null) {
      setFilterMappings((FilterMapping[])LazyList.addToArray(getFilterMappings(), mapping, FilterMapping.class));
    }
  }
  
  public void prependFilterMapping(FilterMapping mapping)
  {
    if (mapping != null)
    {
      FilterMapping[] mappings = getFilterMappings();
      if ((mappings == null) || (mappings.length == 0))
      {
        setFilterMappings(new FilterMapping[] { mapping });
      }
      else
      {
        FilterMapping[] new_mappings = new FilterMapping[mappings.length + 1];
        System.arraycopy(mappings, 0, new_mappings, 1, mappings.length);
        new_mappings[0] = mapping;
        setFilterMappings(new_mappings);
      }
    }
  }
  
  protected synchronized void updateNameMappings()
  {
    _filterNameMap.clear();
    if (_filters != null) {
      for (int i = 0; i < _filters.length; i++)
      {
        _filterNameMap.put(_filters[i].getName(), _filters[i]);
        _filters[i].setServletHandler(this);
      }
    }
    _servletNameMap.clear();
    if (_servlets != null) {
      for (int i = 0; i < _servlets.length; i++)
      {
        _servletNameMap.put(_servlets[i].getName(), _servlets[i]);
        _servlets[i].setServletHandler(this);
      }
    }
  }
  
  protected synchronized void updateMappings()
  {
    if (_filterMappings == null)
    {
      _filterPathMappings = null;
      _filterNameMappings = null;
    }
    else
    {
      _filterPathMappings = new ArrayList();
      _filterNameMappings = new MultiMap();
      for (int i = 0; i < _filterMappings.length; i++)
      {
        FilterHolder filter_holder = (FilterHolder)_filterNameMap.get(_filterMappings[i].getFilterName());
        if (filter_holder == null) {
          throw new IllegalStateException("No filter named " + _filterMappings[i].getFilterName());
        }
        _filterMappings[i].setFilterHolder(filter_holder);
        if (_filterMappings[i].getPathSpecs() != null) {
          _filterPathMappings.add(_filterMappings[i]);
        }
        if (_filterMappings[i].getServletNames() != null)
        {
          String[] names = _filterMappings[i].getServletNames();
          for (int j = 0; j < names.length; j++) {
            if (names[j] != null) {
              _filterNameMappings.add(names[j], _filterMappings[i]);
            }
          }
        }
      }
    }
    if ((_servletMappings == null) || (_servletNameMap == null))
    {
      _servletPathMap = null;
    }
    else
    {
      PathMap pm = new PathMap();
      for (int i = 0; i < _servletMappings.length; i++)
      {
        ServletHolder servlet_holder = (ServletHolder)_servletNameMap.get(_servletMappings[i].getServletName());
        if (servlet_holder == null) {
          throw new IllegalStateException("No such servlet: " + _servletMappings[i].getServletName());
        }
        if ((servlet_holder.isEnabled()) && (_servletMappings[i].getPathSpecs() != null))
        {
          String[] pathSpecs = _servletMappings[i].getPathSpecs();
          for (int j = 0; j < pathSpecs.length; j++) {
            if (pathSpecs[j] != null) {
              pm.put(pathSpecs[j], servlet_holder);
            }
          }
        }
      }
      _servletPathMap = pm;
    }
    int i;
    if (_chainCache != null) {
      for (i = _chainCache.length; i-- > 0;) {
        if (_chainCache[i] != null) {
          _chainCache[i].clear();
        }
      }
    }
    if (LOG.isDebugEnabled())
    {
      LOG.debug("filterNameMap=" + _filterNameMap, new Object[0]);
      LOG.debug("pathFilters=" + _filterPathMappings, new Object[0]);
      LOG.debug("servletFilterMap=" + _filterNameMappings, new Object[0]);
      LOG.debug("servletPathMap=" + _servletPathMap, new Object[0]);
      LOG.debug("servletNameMap=" + _servletNameMap, new Object[0]);
    }
    try
    {
      if (isStarted()) {
        initialize();
      }
    }
    catch (Exception e)
    {
      throw new RuntimeException(e);
    }
  }
  
  protected void notFound(HttpServletRequest request, HttpServletResponse response)
    throws IOException
  {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Not Found " + request.getRequestURI(), new Object[0]);
    }
    response.sendError(404);
  }
  
  public void setFilterChainsCached(boolean filterChainsCached)
  {
    _filterChainsCached = filterChainsCached;
  }
  
  public void setFilterMappings(FilterMapping[] filterMappings)
  {
    if (getServer() != null) {
      getServer().getContainer().update(this, _filterMappings, filterMappings, "filterMapping", true);
    }
    _filterMappings = filterMappings;
    updateMappings();
    invalidateChainsCache();
  }
  
  public synchronized void setFilters(FilterHolder[] holders)
  {
    if (getServer() != null) {
      getServer().getContainer().update(this, _filters, holders, "filter", true);
    }
    _filters = holders;
    updateNameMappings();
    invalidateChainsCache();
  }
  
  public void setServletMappings(ServletMapping[] servletMappings)
  {
    if (getServer() != null) {
      getServer().getContainer().update(this, _servletMappings, servletMappings, "servletMapping", true);
    }
    _servletMappings = servletMappings;
    updateMappings();
    invalidateChainsCache();
  }
  
  public synchronized void setServlets(ServletHolder[] holders)
  {
    if (getServer() != null) {
      getServer().getContainer().update(this, _servlets, holders, "servlet", true);
    }
    _servlets = holders;
    updateNameMappings();
    invalidateChainsCache();
  }
  
  private class CachedChain
    implements FilterChain
  {
    FilterHolder _filterHolder;
    CachedChain _next;
    ServletHolder _servletHolder;
    
    CachedChain(Object filters, ServletHolder servletHolder)
    {
      if (LazyList.size(filters) > 0)
      {
        _filterHolder = ((FilterHolder)LazyList.get(filters, 0));
        filters = LazyList.remove(filters, 0);
        _next = new CachedChain(ServletHandler.this, filters, servletHolder);
      }
      else
      {
        _servletHolder = servletHolder;
      }
    }
    
    public void doFilter(ServletRequest request, ServletResponse response)
      throws IOException, ServletException
    {
      Request baseRequest = (request instanceof Request) ? (Request)request : AbstractHttpConnection.getCurrentConnection().getRequest();
      if (_filterHolder != null)
      {
        if (ServletHandler.LOG.isDebugEnabled()) {
          ServletHandler.LOG.debug("call filter " + _filterHolder, new Object[0]);
        }
        Filter filter = _filterHolder.getFilter();
        if (_filterHolder.isAsyncSupported())
        {
          filter.doFilter(request, response, _next);
        }
        else
        {
          boolean suspendable = baseRequest.isAsyncSupported();
          if (suspendable) {
            try
            {
              baseRequest.setAsyncSupported(false);
              filter.doFilter(request, response, _next);
            }
            finally
            {
              baseRequest.setAsyncSupported(true);
            }
          } else {
            filter.doFilter(request, response, _next);
          }
        }
        return;
      }
      HttpServletRequest srequest = (HttpServletRequest)request;
      if (_servletHolder != null)
      {
        if (ServletHandler.LOG.isDebugEnabled()) {
          ServletHandler.LOG.debug("call servlet " + _servletHolder, new Object[0]);
        }
        _servletHolder.handle(baseRequest, request, response);
      }
      else if (getHandler() == null)
      {
        notFound(srequest, (HttpServletResponse)response);
      }
      else
      {
        nextHandle(URIUtil.addPaths(srequest.getServletPath(), srequest.getPathInfo()), baseRequest, srequest, (HttpServletResponse)response);
      }
    }
    
    public String toString()
    {
      if (_filterHolder != null) {
        return _filterHolder + "->" + _next.toString();
      }
      if (_servletHolder != null) {
        return _servletHolder.toString();
      }
      return "null";
    }
  }
  
  private class Chain
    implements FilterChain
  {
    final Request _baseRequest;
    final Object _chain;
    final ServletHolder _servletHolder;
    int _filter = 0;
    
    Chain(Request baseRequest, Object filters, ServletHolder servletHolder)
    {
      _baseRequest = baseRequest;
      _chain = filters;
      _servletHolder = servletHolder;
    }
    
    public void doFilter(ServletRequest request, ServletResponse response)
      throws IOException, ServletException
    {
      if (ServletHandler.LOG.isDebugEnabled()) {
        ServletHandler.LOG.debug("doFilter " + _filter, new Object[0]);
      }
      if (_filter < LazyList.size(_chain))
      {
        FilterHolder holder = (FilterHolder)LazyList.get(_chain, _filter++);
        if (ServletHandler.LOG.isDebugEnabled()) {
          ServletHandler.LOG.debug("call filter " + holder, new Object[0]);
        }
        Filter filter = holder.getFilter();
        if ((holder.isAsyncSupported()) || (!_baseRequest.isAsyncSupported())) {
          filter.doFilter(request, response, this);
        } else {
          try
          {
            _baseRequest.setAsyncSupported(false);
            filter.doFilter(request, response, this);
          }
          finally
          {
            _baseRequest.setAsyncSupported(true);
          }
        }
        return;
      }
      HttpServletRequest srequest = (HttpServletRequest)request;
      if (_servletHolder != null)
      {
        if (ServletHandler.LOG.isDebugEnabled()) {
          ServletHandler.LOG.debug("call servlet " + _servletHolder, new Object[0]);
        }
        _servletHolder.handle(_baseRequest, request, response);
      }
      else if (getHandler() == null)
      {
        notFound(srequest, (HttpServletResponse)response);
      }
      else
      {
        Request baseRequest = (request instanceof Request) ? (Request)request : AbstractHttpConnection.getCurrentConnection().getRequest();
        nextHandle(URIUtil.addPaths(srequest.getServletPath(), srequest.getPathInfo()), baseRequest, srequest, (HttpServletResponse)response);
      }
    }
    
    public String toString()
    {
      StringBuilder b = new StringBuilder();
      for (int i = 0; i < LazyList.size(_chain); i++)
      {
        Object o = LazyList.get(_chain, i);
        b.append(o.toString());
        b.append("->");
      }
      b.append(_servletHolder);
      return b.toString();
    }
  }
  
  public int getMaxFilterChainsCacheSize()
  {
    return _maxFilterChainsCacheSize;
  }
  
  public void setMaxFilterChainsCacheSize(int maxFilterChainsCacheSize)
  {
    _maxFilterChainsCacheSize = maxFilterChainsCacheSize;
  }
  
  void destroyServlet(Servlet servlet)
  {
    if (_contextHandler != null) {
      _contextHandler.destroyServlet(servlet);
    }
  }
  
  void destroyFilter(Filter filter)
  {
    if (_contextHandler != null) {
      _contextHandler.destroyFilter(filter);
    }
  }
  
  public void dump(Appendable out, String indent)
    throws IOException
  {
    super.dumpThis(out);
    dump(out, indent, new Collection[] { TypeUtil.asList(getHandlers()), getBeans(), TypeUtil.asList(getFilterMappings()), TypeUtil.asList(getFilters()), TypeUtil.asList(getServletMappings()), TypeUtil.asList(getServlets()) });
  }
}

/* Location:
 * Qualified Name:     org.eclipse.jetty.servlet.ServletHandler
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.eclipse.jetty.servlet;

import java.io.IOException;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import org.eclipse.jetty.http.PathMap;
import org.eclipse.jetty.util.TypeUtil;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;

public class FilterMapping
  implements Dumpable
{
  public static final int DEFAULT = 0;
  public static final int REQUEST = 1;
  public static final int FORWARD = 2;
  public static final int INCLUDE = 4;
  public static final int ERROR = 8;
  public static final int ASYNC = 16;
  public static final int ALL = 31;
  
  public static DispatcherType dispatch(String type)
  {
    if ("request".equalsIgnoreCase(type)) {
      return DispatcherType.REQUEST;
    }
    if ("forward".equalsIgnoreCase(type)) {
      return DispatcherType.FORWARD;
    }
    if ("include".equalsIgnoreCase(type)) {
      return DispatcherType.INCLUDE;
    }
    if ("error".equalsIgnoreCase(type)) {
      return DispatcherType.ERROR;
    }
    if ("async".equalsIgnoreCase(type)) {
      return DispatcherType.ASYNC;
    }
    throw new IllegalArgumentException(type);
  }
  
  public static int dispatch(DispatcherType type)
  {
    switch (type)
    {
    case REQUEST: 
      return 1;
    case ASYNC: 
      return 16;
    case FORWARD: 
      return 2;
    case INCLUDE: 
      return 4;
    case ERROR: 
      return 8;
    }
    throw new IllegalArgumentException(type.toString());
  }
  
  private int _dispatches = 0;
  private String _filterName;
  private transient FilterHolder _holder;
  private String[] _pathSpecs;
  private String[] _servletNames;
  
  boolean appliesTo(String path, int type)
  {
    if (appliesTo(type)) {
      for (int i = 0; i < _pathSpecs.length; i++) {
        if ((_pathSpecs[i] != null) && (PathMap.match(_pathSpecs[i], path, true))) {
          return true;
        }
      }
    }
    return false;
  }
  
  boolean appliesTo(int type)
  {
    if (_dispatches == 0) {
      return (type == 1) || ((type == 16) && (_holder.isAsyncSupported()));
    }
    return (_dispatches & type) != 0;
  }
  
  public String getFilterName()
  {
    return _filterName;
  }
  
  FilterHolder getFilterHolder()
  {
    return _holder;
  }
  
  public String[] getPathSpecs()
  {
    return _path
1 2 3 4 5

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd