Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 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.servlet;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
 
 
 
 
 /* --------------------------------------------------------------------- */
Servlet Instance and Context Holder. Holds the name, params and some state of a javax.servlet.Servlet instance. It implements the ServletConfig interface. This class will organise the loading of the servlet when needed or requested.
 
 public class ServletHolder extends Holder<Servletimplements UserIdentity.ScopeComparable
 {
     private static final Logger LOG = Log.getLogger(ServletHolder.class);
 
     /* ---------------------------------------------------------------- */
     private int _initOrder;
     private boolean _initOnStartup=false;
     private Map<StringString_roleMap;
     private String _forcedPath;
     private String _runAsRole;
     private RunAsToken _runAsToken;
     private IdentityService _identityService;
     
     
     private transient Servlet _servlet;
     private transient Config _config;
     private transient long _unavailable;
     private transient boolean _enabled = true;
     private transient UnavailableException _unavailableEx;
     public static final Map<String,StringNO_MAPPED_ROLES = Collections.emptyMap();
 
     /* ---------------------------------------------------------------- */
    
Constructor .
 
     public ServletHolder()
     {
         super (.);
     }
     
     /* ---------------------------------------------------------------- */
    
Constructor .
 
     public ServletHolder(Holder.Source creator)
    {
        super (creator);
    }
    
    /* ---------------------------------------------------------------- */
    
Constructor for existing servlet.
    public ServletHolder(Servlet servlet)
    {
        super (.);
        setServlet(servlet);
    }
    /* ---------------------------------------------------------------- */
    
Constructor for servlet class.
    public ServletHolder(String nameClass<? extends Servletservlet)
    {
        super (.);
        setName(name);
        setHeldClass(servlet);
    }
    
    /* ---------------------------------------------------------------- */
    
Constructor for servlet class.
    public ServletHolder(String nameServlet servlet)
    {
        super (.);
        setName(name);
        setServlet(servlet);
    }
    
    /* ---------------------------------------------------------------- */
    
Constructor for servlet class.
    public ServletHolder(Class<? extends Servletservlet)
    {
        super (.);
        setHeldClass(servlet);
    }
    /* ---------------------------------------------------------------- */
    

Returns:
The unavailable exception or null if not unavailable
    {
        return ;
    }
    
    /* ------------------------------------------------------------ */
    public synchronized void setServlet(Servlet servlet)
    {
        if (servlet==null || servlet instanceof SingleThreadModel)
            throw new IllegalArgumentException();
        =true;
        =servlet;
        setHeldClass(servlet.getClass());
        if (getName()==null)
            setName(servlet.getClass().getName()+"-"+super.hashCode());
    }
    
    /* ------------------------------------------------------------ */
    public int getInitOrder()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the initialize order. Holders with order<0, are initialized on use. Those with order>=0 are initialized in increasing order when the handler is started.
    public void setInitOrder(int order)
    {
        =true;
         = order;
    }
    
    public boolean isSetInitOrder()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Comparitor by init order.
    public int compareTo(Object o)
    {
        if (o instanceof ServletHolder)
        {
            ServletHolder sh= (ServletHolder)o;
            if (sh==this)
                return 0;
            if (sh._initOrder<)
                return 1;
            if (sh._initOrder>)
                return -1;
            
            int c=(!=null && sh._className!=null)?.compareTo(sh._className):0;
            if (c==0)
                c=.compareTo(sh._name);
            if (c==0)
                c=this.hashCode()>o.hashCode()?1:-1;
            return c;
        }
        return 1;
    }
    /* ------------------------------------------------------------ */
    public boolean equals(Object o)
    {
        return compareTo(o)==0;
    }
    /* ------------------------------------------------------------ */
    public int hashCode()
    {
        return ==null?System.identityHashCode(this):.hashCode();
    }
    /* ------------------------------------------------------------ */
    
Link a user role. Translate the role name used by a servlet, to the link name used by the container.

Parameters:
name The role name as used by the servlet
link The role name as used by the container.
    public synchronized void setUserRoleLink(String name,String link)
    {
        if (==null)
            =new HashMap<StringString>();
        .put(name,link);
    }
    
    /* ------------------------------------------------------------ */
    
get a user role link.

Parameters:
name The name of the role
Returns:
The name as translated by the link. If no link exists, the name is returned.
    public String getUserRoleLink(String name)
    {
        if (==null)
            return name;
        String link.get(name);
        return (link==null)?name:link;
    }
    /* ------------------------------------------------------------ */
    public Map<StringStringgetRoleMap()
    {
        return  == null : ;
    }
    
    /* ------------------------------------------------------------ */
    

Returns:
Returns the forcedPath.
    public String getForcedPath()
    {
        return ;
    }
    
    /* ------------------------------------------------------------ */
    

Parameters:
forcedPath The forcedPath to set.
    public void setForcedPath(String forcedPath)
    {
         = forcedPath;
    }
    
    public boolean isEnabled()
    {
        return ;
    }
    public void setEnabled(boolean enabled)
    {
         = enabled;
    }
    /* ------------------------------------------------------------ */
    public void doStart()
        throws Exception
    {
        =0;
        if (!)
            return;
        //check servlet has a class (ie is not a preliminary registration). If preliminary, fail startup.
        try
        {
            super.doStart();
        } 
        catch (UnavailableException ue)
        {
            makeUnavailable(ue);
            throw ue;
        }
        
        try
        {
            checkServletType();
        }
        catch (UnavailableException ue)
        {
            makeUnavailable(ue);
            if (!.isStartWithUnavailable())
                throw ue//servlet is not an instance of javax.servlet.Servlet
        }
        
        if (!=null && !=null)
        
        =new Config();
        if (!=null && javax.servlet.SingleThreadModel.class.isAssignableFrom())
             = new SingleThreadedWrapper();
        if ( || )
        {
            try
            {
                initServlet();
            }
            catch(Exception e)
            {
                if (.isStartWithUnavailable())
                    .ignore(e);
                else
                    throw e;
            }
        }  
    }
    /* ------------------------------------------------------------ */
    public void doStop()
        throws Exception
    {
        Object old_run_as = null;
        if (!=null)
        {       
            try
            {
                if (!=null)
                    old_run_as=.setRunAs(.getSystemUserIdentity(),);
                destroyInstance();
            }
            catch (Exception e)
            {
                .warn(e);
            }
            finally
            {
                if (!=null)
                    .unsetRunAs(old_run_as);
            }
        }
        if (!)
            =null;
        =null;
    }
    /* ------------------------------------------------------------ */
    public void destroyInstance (Object o)
    throws Exception
    {
        if (o==null)
            return;
        Servlet servlet =  ((Servlet)o);
        servlet.destroy();
        getServletHandler().destroyServlet(servlet);
    }
    /* ------------------------------------------------------------ */
    
Get the servlet.

Returns:
The servlet
    public synchronized Servlet getServlet()
        throws ServletException
    {
        // Handle previous unavailability
        if (!=0)
        {
            if (<0 || >0 && System.currentTimeMillis()<)
                throw ;
            =0;
            =null;
        }
        if (==null)
            initServlet();
        return ;
    }
    /* ------------------------------------------------------------ */
    
Get the servlet instance (no initialization done).

Returns:
The servlet or null
    public Servlet getServletInstance()
    {
        return ;
    }
        
    /* ------------------------------------------------------------ */
    
Check to ensure class of servlet is acceptable.

    public void checkServletType ()
        throws UnavailableException
    {
        if (==null || !javax.servlet.Servlet.class.isAssignableFrom())
        {
            throw new UnavailableException("Servlet "++" is not a javax.servlet.Servlet");
        }
    }
    /* ------------------------------------------------------------ */
    

Returns:
true if the holder is started and is not unavailable
    public boolean isAvailable()
    {
        if (isStarted()&& ==0)
            return true;
        try 
        {
            getServlet();
        }
        catch(Exception e)
        {
            .ignore(e);
        }
        return isStarted()&& ==0;
    }
    
    /* ------------------------------------------------------------ */
    private void makeUnavailable(UnavailableException e)
    {
        if (==e && !=0)
            return;
        .getServletContext().log("unavailable",e);
        =e;
        =-1;
        if (e.isPermanent())   
            =-1;
        else
        {
            if (.getUnavailableSeconds()>0)
                =System.currentTimeMillis()+1000*.getUnavailableSeconds();
            else
                =System.currentTimeMillis()+5000; // TODO configure
        }
    }
    /* ------------------------------------------------------------ */
    private void makeUnavailable(final Throwable e)
    {
        if (e instanceof UnavailableException)
            makeUnavailable((UnavailableException)e);
        else
        {
            ServletContext ctx = .getServletContext();
            if (ctx==null)
                .info("unavailable",e);
            else
                ctx.log("unavailable",e);
            =new UnavailableException(String.valueOf(e),-1)
            {
                {
                    initCause(e);
                }
            };
            =-1;
        }
    }
    /* ------------------------------------------------------------ */
    private void initServlet()
    	throws ServletException
    {
        Object old_run_as = null;
        try
        {
            if (==null)
                =newInstance();
            if (==null)
                =new Config();
            
            // Handle run as
            if (!=null)
            {
                old_run_as=.setRunAs(.getSystemUserIdentity(),);
            }
            
            // Handle configuring servlets that implement org.apache.jasper.servlet.JspServlet
            if (isJspServlet())
            {
                initJspServlet();
            }
            initMultiPart();
            
            .init();
        }
        catch (UnavailableException e)
        {
            makeUnavailable(e);
            =null;
            =null;
            throw e;
        }
        catch (ServletException e)
        {
            makeUnavailable(e.getCause()==null?e:e.getCause());
            =null;
            =null;
            throw e;
        }
        catch (Exception e)
        {
            makeUnavailable(e);
            =null;
            =null;
            throw new ServletException(this.toString(),e);
        }
        finally
        {
            // pop run-as role
            if (!=null)
                .unsetRunAs(old_run_as);
        }
    }
    
    
    /* ------------------------------------------------------------ */
    
    protected void initJspServlet () throws Exception
    {
        
        /* Set the webapp's classpath for Jasper */
        ch.setAttribute("org.apache.catalina.jsp_classpath"ch.getClassPath());
        /* Set the system classpath for Jasper */
        setInitParameter("com.sun.appserv.jsp.classpath", Loader.getClassPath(ch.getClassLoader().getParent())); 
        
        /* Set up other classpath attribute */
        if ("?".equals(getInitParameter("classpath")))
        {
            String classpath = ch.getClassPath();
            .debug("classpath=" + classpath);
            if (classpath != null
                setInitParameter("classpath"classpath);
        }
    }
    
    /* ------------------------------------------------------------ */
    
Register a ServletRequestListener that will ensure tmp multipart files are deleted when the request goes out of scope.

    protected void initMultiPart () throws Exception
    {
        //if this servlet can handle multipart requests, ensure tmp files will be
        //cleaned up correctly
        if (((Registration)getRegistration()).getMultipartConfig() != null)
        {
            //Register a listener to delete tmp files that are created as a result of this
            //servlet calling Request.getPart() or Request.getParts()
            ch.addEventListener(new Request.MultiPartCleanerListener());
        }
    }
    
    /* ------------------------------------------------------------ */
    
    public String getContextPath()
    {
        return .getServletContext().getContextPath();
    }
    /* ------------------------------------------------------------ */
    
    public Map<StringStringgetRoleRefMap()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    public String getRunAsRole() 
    {
        return ;
    }
    
    /* ------------------------------------------------------------ */
    public void setRunAsRole(String role
    {
         = role;
    }
    
    /* ------------------------------------------------------------ */
    
Service a request with this servlet.
    public void handle(Request baseRequest,
                       ServletRequest request,
                       ServletResponse response)
        throws ServletException,
               UnavailableException,
               IOException
    {
        if (==null)
            throw new UnavailableException("Servlet Not Initialized");
        
        Servlet servlet=;
        synchronized(this)
        {
            if (!=0 || !)
                servlet=getServlet();
            if (servlet==null)
                throw new UnavailableException("Could not instantiate "+);
        }
        
        // Service the request
        boolean servlet_error=true;
        Object old_run_as = null;
        boolean suspendable = baseRequest.isAsyncSupported();
        try
        {
            // Handle aliased path
            if (!=null)
                // TODO complain about poor naming to the Jasper folks
                request.setAttribute("org.apache.catalina.jsp_file",);
            // Handle run as
            if (!=null)
                old_run_as=.setRunAs(baseRequest.getResolvedUserIdentity(),);
            if (!isAsyncSupported())
                baseRequest.setAsyncSupported(false);
            if (mpce != null)
                request.setAttribute(.mpce);
            servlet.service(request,response);
            servlet_error=false;
        }
        catch(UnavailableException e)
        {
            makeUnavailable(e);
            throw ;
        }
        finally
        {
            baseRequest.setAsyncSupported(suspendable);
            
            // pop run-as role
            if (!=null)
                .unsetRunAs(old_run_as);
            // Handle error params.
            if (servlet_error)
                request.setAttribute("javax.servlet.error.servlet_name",getName());
        }
    }
    
    
    /* ------------------------------------------------------------ */
    private boolean isJspServlet ()
    {
        if ( == null)
            return false;
        
        Class c = .getClass();
        
        boolean result = false;
        while (c != null && !result)
        {
            result = isJspServlet(c.getName());
            c = c.getSuperclass();
        }
        
        return result;
    }
    
    
    /* ------------------------------------------------------------ */
    private boolean isJspServlet (String classname)
    {
        if (classname == null)
            return false;
        return ("org.apache.jasper.servlet.JspServlet".equals(classname));
    }
 
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    protected class Config extends HolderConfig implements ServletConfig
    {   
        /* -------------------------------------------------------- */
        public String getServletName()
        {
            return getName();
        }
        
    }
    /* -------------------------------------------------------- */
    /* -------------------------------------------------------- */
    /* -------------------------------------------------------- */
    public class Registration extends HolderRegistration implements ServletRegistration.Dynamic
    {
        protected MultipartConfigElement _multipartConfig;       
        
        public Set<StringaddMapping(String... urlPatterns)
        {
            illegalStateIfContextStarted();
            Set<Stringclash=null;
            for (String pattern : urlPatterns)
            {
                ServletMapping mapping = .getServletMapping(pattern);
                if (mapping!=null)
                {
                    //if the servlet mapping was from a default descriptor, then allow it to be overridden
                    if (!mapping.isDefault())
                    {
                        if (clash==null)
                            clash=new HashSet<String>();
                        clash.add(pattern);
                    }
                }
            }
            
            //if there were any clashes amongst the urls, return them
            if (clash!=null)
                return clash;
            
            //otherwise apply all of them
            ServletMapping mapping = new ServletMapping();
            mapping.setServletName(ServletHolder.this.getName());
            mapping.setPathSpecs(urlPatterns);
            .addServletMapping(mapping);
            
            return Collections.emptySet();
        }
        public Collection<StringgetMappings()
        {
            ServletMapping[] mappings =.getServletMappings();
            List<Stringpatterns=new ArrayList<String>();
            if (mappings!=null)
            {
                for (ServletMapping mapping : mappings)
                {
                    if (!mapping.getServletName().equals(getName()))
                        continue;
                    String[] specs=mapping.getPathSpecs();
                    if (specs!=null && specs.length>0)
                        patterns.addAll(Arrays.asList(specs));
                }
            }
            return patterns;
        }
        @Override
        public String getRunAsRole() 
        {
            return ;
        }
        @Override
        public void setLoadOnStartup(int loadOnStartup)
        {
            illegalStateIfContextStarted();
            ServletHolder.this.setInitOrder(loadOnStartup);
        }
        
        public int getInitOrder()
        {
            return ServletHolder.this.getInitOrder();
        }
        @Override
        public void setMultipartConfig(MultipartConfigElement element
        {
             = element;
        }
        
        {
            return ;
        }
        @Override
        public void setRunAsRole(String role
        {
             = role;
        }
        @Override
        public Set<StringsetServletSecurity(ServletSecurityElement securityElement
        {
            return .setServletSecurity(thissecurityElement);
        }
    }
    
    {
        if ( == null)
             = new Registration();
        return ;
    }
    
    /* -------------------------------------------------------- */
    /* -------------------------------------------------------- */
    /* -------------------------------------------------------- */
    private class SingleThreadedWrapper implements Servlet
    {
        Stack<Servlet_stack=new Stack<Servlet>();
        
        public void destroy()
        {
            synchronized(this)
            {
                while(.size()>0)
                    try { (.pop()).destroy(); } catch (Exception e) { .warn(e); }
            }
        }
        public ServletConfig getServletConfig()
        {
            return ;
        }
        public String getServletInfo()
        {
            return null;
        }
        public void init(ServletConfig configthrows ServletException
        {
            synchronized(this)
            {
                if(.size()==0)
                {
                    try
                    {
                        Servlet s = newInstance();
                        s.init(config);
                        .push(s);
                    }
                    catch (ServletException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw new ServletException(e);
                    }
                }
            }
        }
        public void service(ServletRequest reqServletResponse resthrows ServletExceptionIOException
        {
            Servlet s;
            synchronized(this)
            {
                if(.size()>0)
                    s=(Servlet).pop();
                else
                {
                    try
                    {
                        s = newInstance();
                        s.init();
                    }
                    catch (ServletException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw new ServletException(e);
                    }
                }
            }
            
            try
            {
                s.service(req,res);
            }
            finally
            {
                synchronized(this)
                {
                    .push(s);
                }
            }
        }
    }
    
    /* ------------------------------------------------------------ */
    
    {
        try
        {
            ServletContext ctx = getServletHandler().getServletContext();
            if (ctx==null)
                return getHeldClass().newInstance();
            return ((ServletContextHandler.Context)ctx).createServlet(getHeldClass());
        }
        catch (ServletException se)
        {
            Throwable cause = se.getRootCause();
            if (cause instanceof InstantiationException)
                throw (InstantiationException)cause;
            if (cause instanceof IllegalAccessException)
                throw (IllegalAccessException)cause;
            throw se;
        }
    }
New to GrepCode? Check out our FAQ X