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.Map;
 
 
 
 /* ------------------------------------------------------------ */
Dynamic Servlet Invoker. This servlet invokes anonymous servlets that have not been defined in the web.xml or by other means. The first element of the pathInfo of a request passed to the envoker is treated as a servlet name for an existing servlet, or as a class name of a new servlet. This servlet is normally mapped to /servlet/* This servlet support the following initParams:
                                                                     
  nonContextServlets       If false, the invoker can only load        
                           servlets from the contexts classloader.    
                           This is false by default and setting this  
                           to true may have security implications.    
                                                                      
  verbose                  If true, log dynamic loads                 
                                                                      
  *                        All other parameters are copied to the     
                           each dynamic servlet as init parameters    
 

Version:
$Id: Invoker.java 4780 2009-03-17 15:36:08Z jesse $
 
 public class Invoker extends HttpServlet
 {
     private static final Logger LOG = Log.getLogger(Invoker.class);
 
 
     private ContextHandler _contextHandler;
     private ServletHandler _servletHandler;
     private Map.Entry _invokerEntry;
     private Map _parameters;
     private boolean _nonContextServlets;
     private boolean _verbose;
         
     /* ------------------------------------------------------------ */
     public void init()
     {
         ServletContext config=getServletContext();
 
         Handler handler=.getHandler();
         while (handler!=null && !(handler instanceof ServletHandler) && (handler instanceof HandlerWrapper))
             handler=((HandlerWrapper)handler).getHandler();
          = (ServletHandler)handler;
         Enumeration e = getInitParameterNames();
         while(e.hasMoreElements())
         {
             String param=(String)e.nextElement();
             String value=getInitParameter(param);
             String lvalue=value.toLowerCase(.);
             if ("nonContextServlets".equals(param))
             {
                 =value.length()>0 && lvalue.startsWith("t");
             }
            if ("verbose".equals(param))
            {
                =value.length()>0 && lvalue.startsWith("t");
            }
            else
            {
                if (==null)
                    =new HashMap();
                .put(param,value);
            }
        }
    }
    
    /* ------------------------------------------------------------ */
    protected void service(HttpServletRequest requestHttpServletResponse response)
    {
        // Get the requested path and info
        boolean included=false;
        String servlet_path=(String)request.getAttribute(.);
        if (servlet_path==null)
            servlet_path=request.getServletPath();
        else
            included=true;
        String path_info = (String)request.getAttribute(.);
        if (path_info==null)
            path_info=request.getPathInfo();
        
        // Get the servlet class
        String servlet = path_info;
        if (servlet==null || servlet.length()<=1 )
        {
            response.sendError(404);
            return;
        }
        
        
        int i0=servlet.charAt(0)=='/'?1:0;
        int i1=servlet.indexOf('/',i0);
        servlet=i1<0?servlet.substring(i0):servlet.substring(i0,i1);
        // look for a named holder
        ServletHolder[] holders = .getServlets();
        ServletHolder holder = getHolder (holdersservlet);
       
        if (holder!=null)
        {
            // Found a named servlet (from a user's web.xml file) so
            // now we add a mapping for it
            if (.isDebugEnabled())
                .debug("Adding servlet mapping for named servlet:"+servlet+":"+URIUtil.addPaths(servlet_path,servlet)+"/*");
            ServletMapping mapping = new ServletMapping();
            mapping.setServletName(servlet);
            mapping.setPathSpec(URIUtil.addPaths(servlet_path,servlet)+"/*");
        }
        else
        {
            // look for a class mapping
            if (servlet.endsWith(".class"))
                servlet=servlet.substring(0,servlet.length()-6);
            if (servlet==null || servlet.length()==0)
            {
                response.sendError(404);
                return;
            }   
        
            synchronized()
            {
                // find the entry for the invoker (me)
                 =.getHolderEntry(servlet_path);
            
                // Check for existing mapping (avoid threaded race).
                String path=URIUtil.addPaths(servlet_path,servlet);
                Map.Entry entry = .getHolderEntry(path);
               
                if (entry!=null && !entry.equals())
                {
                    // Use the holder
                    holder=(ServletHolder)entry.getValue();
                }
                else
                {
                    // Make a holder
                    if (.isDebugEnabled())
                        .debug("Making new servlet="+servlet+" with path="+path+"/*");
                    holder=.addServletWithMapping(servletpath+"/*");
                    
                    if (!=null)
                        holder.setInitParameters();
                    
                    try {holder.start();}
                    catch (Exception e)
                    {
                        .debug(e);
                        throw new UnavailableException(e.toString());
                    }
                    
                    // Check it is from an allowable classloader
                    if (!)
                    {
                        Object s=holder.getServlet();
                        
                        if (.getClassLoader()!=
                            s.getClass().getClassLoader())
                        {
                            try 
                            {
                                holder.stop();
                            } 
                            catch (Exception e
                            {
                                .ignore(e);
                            }
                            
                            .warn("Dynamic servlet "+s+
                                         " not loaded from context "+
                                         request.getContextPath());
                            throw new UnavailableException("Not in context");
                        }
                    }
                    if ( && .isDebugEnabled())
                        .debug("Dynamic load '"+servlet+"' at "+path);
                }
            }
        }
        
        if (holder!=null)
        {
            final Request baseRequest=(request instanceof Request)?((Request)request):AbstractHttpConnection.getCurrentConnection().getRequest();
            holder.handle(baseRequest,
                    new InvokedRequest(request,included,servlet,servlet_path,path_info),
                          response);
        }
        else
        {
            .info("Can't find holder for servlet: "+servlet);
            response.sendError(404);
        }
            
        
    }
    /* ------------------------------------------------------------ */
    {
        String _servletPath;
        String _pathInfo;
        boolean _included;
        
        /* ------------------------------------------------------------ */
        InvokedRequest(HttpServletRequest request,
                boolean included,
                String name,
                String servletPath,
                String pathInfo)
        {
            super(request);
            =included;
            =URIUtil.addPaths(servletPath,name);
            =pathInfo.substring(name.length()+1);
            if (.length()==0)
                =null;
        }
        
        /* ------------------------------------------------------------ */
        public String getServletPath()
        {
            if ()
                return super.getServletPath();
            return ;
        }
        
        /* ------------------------------------------------------------ */
        public String getPathInfo()
        {
            if ()
                return super.getPathInfo();
            return ;
        }
        
        /* ------------------------------------------------------------ */
        public Object getAttribute(String name)
        {
            if ()
            {
                if (name.equals(.))
                    return URIUtil.addPaths(URIUtil.addPaths(getContextPath(),),);
                if (name.equals(.))
                    return ;
                if (name.equals(.))
                    return ;
            }
            return super.getAttribute(name);
        }
    }
    
    
    private ServletHolder getHolder(ServletHolder[] holdersString servlet)
    {
        if (holders == null)
            return null;
       
        ServletHolder holder = null;
        for (int i=0; holder==null && i<holders.lengthi++)
        {
            if (holders[i].getName().equals(servlet))
            {
                holder = holders[i];
            }
        }
        return holder;
    }
New to GrepCode? Check out our FAQ X