View Javadoc

1   // ========================================================================
2   // Copyright (c) 1999-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at 
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses. 
12  // ========================================================================
13  
14  package org.eclipse.jetty.servlet;
15  
16  import java.io.IOException;
17  import java.util.Collections;
18  import java.util.HashMap;
19  import java.util.Map;
20  import java.util.Stack;
21  
22  import javax.servlet.Servlet;
23  import javax.servlet.ServletConfig;
24  import javax.servlet.ServletException;
25  import javax.servlet.ServletRequest;
26  import javax.servlet.ServletResponse;
27  import javax.servlet.SingleThreadModel;
28  import javax.servlet.UnavailableException;
29  
30  import org.eclipse.jetty.security.IdentityService;
31  import org.eclipse.jetty.security.RunAsToken;
32  import org.eclipse.jetty.server.Request;
33  import org.eclipse.jetty.server.UserIdentity;
34  import org.eclipse.jetty.util.log.Log;
35  
36  
37  
38  
39  /* --------------------------------------------------------------------- */
40  /** Servlet Instance and Context Holder.
41   * Holds the name, params and some state of a javax.servlet.Servlet
42   * instance. It implements the ServletConfig interface.
43   * This class will organise the loading of the servlet when needed or
44   * requested.
45   *
46   * 
47   */
48  public class ServletHolder extends Holder implements UserIdentity.Scope, Comparable
49  {
50      /* ---------------------------------------------------------------- */
51      private int _initOrder;
52      private boolean _initOnStartup=false;
53      private Map<String, String> _roleMap;
54      private String _forcedPath;
55      private String _runAsRole;
56      private RunAsToken _runAsToken;
57      private IdentityService _identityService;
58      
59      
60      private transient Servlet _servlet;
61      private transient Config _config;
62      private transient long _unavailable;
63      private transient UnavailableException _unavailableEx;
64      public static final Map<String,String> NO_MAPPED_ROLES = Collections.emptyMap();
65  
66      /* ---------------------------------------------------------------- */
67      /** Constructor .
68       */
69      public ServletHolder()
70      {}
71      
72      /* ---------------------------------------------------------------- */
73      /** Constructor for existing servlet.
74       */
75      public ServletHolder(Servlet servlet)
76      {
77          setServlet(servlet);
78      }
79  
80      /* ---------------------------------------------------------------- */
81      /** Constructor for existing servlet.
82       */
83      public ServletHolder(Class servlet)
84      {
85          super(servlet);
86      }
87  
88      /* ---------------------------------------------------------------- */
89      /**
90       * @return The unavailable exception or null if not unavailable
91       */
92      public UnavailableException getUnavailableException()
93      {
94          return _unavailableEx;
95      }
96      
97      /* ------------------------------------------------------------ */
98      public synchronized void setServlet(Servlet servlet)
99      {
100         if (servlet==null || servlet instanceof SingleThreadModel)
101             throw new IllegalArgumentException();
102 
103         _extInstance=true;
104         _servlet=servlet;
105         setHeldClass(servlet.getClass());
106         if (getName()==null)
107             setName(servlet.getClass().getName()+"-"+super.hashCode());
108     }
109     
110     /* ------------------------------------------------------------ */
111     public int getInitOrder()
112     {
113         return _initOrder;
114     }
115 
116     /* ------------------------------------------------------------ */
117     /** Set the initialize order.
118      * Holders with order<0, are initialized on use. Those with
119      * order>=0 are initialized in increasing order when the handler
120      * is started.
121      */
122     public void setInitOrder(int order)
123     {
124         _initOnStartup=true;
125         _initOrder = order;
126     }
127 
128     /* ------------------------------------------------------------ */
129     /** Comparitor by init order.
130      */
131     public int compareTo(Object o)
132     {
133         if (o instanceof ServletHolder)
134         {
135             ServletHolder sh= (ServletHolder)o;
136             if (sh==this)
137                 return 0;
138             if (sh._initOrder<_initOrder)
139                 return 1;
140             if (sh._initOrder>_initOrder)
141                 return -1;
142             
143             int c=(_className!=null && sh._className!=null)?_className.compareTo(sh._className):0;
144             if (c==0)
145                 c=_name.compareTo(sh._name);
146             if (c==0)
147                 c=this.hashCode()>o.hashCode()?1:-1;
148             return c;
149         }
150         return 1;
151     }
152 
153     /* ------------------------------------------------------------ */
154     public boolean equals(Object o)
155     {
156         return compareTo(o)==0;
157     }
158 
159     /* ------------------------------------------------------------ */
160     public int hashCode()
161     {
162         return _name==null?System.identityHashCode(this):_name.hashCode();
163     }
164 
165     /* ------------------------------------------------------------ */
166     /** Link a user role.
167      * Translate the role name used by a servlet, to the link name
168      * used by the container.
169      * @param name The role name as used by the servlet
170      * @param link The role name as used by the container.
171      */
172     public synchronized void setUserRoleLink(String name,String link)
173     {
174         if (_roleMap==null)
175             _roleMap=new HashMap<String, String>();
176         _roleMap.put(name,link);
177     }
178     
179     /* ------------------------------------------------------------ */
180     /** get a user role link.
181      * @param name The name of the role
182      * @return The name as translated by the link. If no link exists,
183      * the name is returned.
184      */
185     public String getUserRoleLink(String name)
186     {
187         if (_roleMap==null)
188             return name;
189         String link= _roleMap.get(name);
190         return (link==null)?name:link;
191     }
192 
193     /* ------------------------------------------------------------ */
194     public Map<String, String> getRoleMap()
195     {
196         return _roleMap == null? NO_MAPPED_ROLES : _roleMap;
197     }
198     
199     /* ------------------------------------------------------------ */
200     /**
201      * @return Returns the forcedPath.
202      */
203     public String getForcedPath()
204     {
205         return _forcedPath;
206     }
207     
208     /* ------------------------------------------------------------ */
209     /**
210      * @param forcedPath The forcedPath to set.
211      */
212     public void setForcedPath(String forcedPath)
213     {
214         _forcedPath = forcedPath;
215     }
216     
217     /* ------------------------------------------------------------ */
218     public void doStart()
219     throws Exception
220     {
221         _unavailable=0;
222         try
223         {
224             super.doStart();
225             checkServletType();
226         }
227         catch (UnavailableException ue)
228         {
229             makeUnavailable(ue);
230         }
231 
232         _identityService = _servletHandler.getIdentityService();
233         if (_identityService!=null && _runAsRole!=null)
234             _runAsToken=_identityService.newRunAsToken(_runAsRole);
235         
236         _config=new Config();
237 
238         if (_class!=null && javax.servlet.SingleThreadModel.class.isAssignableFrom(_class))
239             _servlet = new SingleThreadedWrapper();
240 
241         if (_extInstance || _initOnStartup)
242         {
243             try
244             {
245                 initServlet();
246             }
247             catch(Exception e)
248             {
249                 if (_servletHandler.isStartWithUnavailable())
250                     Log.ignore(e);
251                 else
252                     throw e;
253             }
254         }  
255     }
256 
257     /* ------------------------------------------------------------ */
258     public void doStop()
259     {
260         Object old_run_as = null;
261         if (_servlet!=null)
262         {       
263             try
264             {
265                 if (_identityService!=null && _runAsToken!=null)
266                     old_run_as=_identityService.setRunAs(_identityService.getSystemUserIdentity(),_runAsToken);
267 
268                 destroyInstance(_servlet);
269             }
270             catch (Exception e)
271             {
272                 Log.warn(e);
273             }
274             finally
275             {
276                 if (_identityService!=null && _runAsToken!=null)
277                     _identityService.unsetRunAs(old_run_as);
278             }
279         }
280 
281         if (!_extInstance)
282             _servlet=null;
283 
284         _config=null;
285     }
286 
287     /* ------------------------------------------------------------ */
288     public void destroyInstance (Object o)
289     throws Exception
290     {
291         if (o==null)
292             return;
293         Servlet servlet =  ((Servlet)o);
294         servlet.destroy();
295         getServletHandler().customizeServletDestroy(servlet);
296     }
297 
298     /* ------------------------------------------------------------ */
299     /** Get the servlet.
300      * @return The servlet
301      */
302     public synchronized Servlet getServlet()
303         throws ServletException
304     {
305         // Handle previous unavailability
306         if (_unavailable!=0)
307         {
308             if (_unavailable<0 || _unavailable>0 && System.currentTimeMillis()<_unavailable)
309                 throw _unavailableEx;
310             _unavailable=0;
311             _unavailableEx=null;
312         }
313 
314         if (_servlet==null)
315             initServlet();
316         return _servlet;
317     }
318 
319     /* ------------------------------------------------------------ */
320     /**
321      * Check to ensure class of servlet is acceptable.
322      * @throws UnavailableException
323      */
324     public void checkServletType ()
325         throws UnavailableException
326     {
327         if (_class==null || !javax.servlet.Servlet.class.isAssignableFrom(_class))
328         {
329             throw new UnavailableException("Servlet "+_class+" is not a javax.servlet.Servlet");
330         }
331     }
332 
333     /* ------------------------------------------------------------ */
334     /** 
335      * @return true if the holder is started and is not unavailable
336      */
337     public boolean isAvailable()
338     {
339         if (isStarted()&& _unavailable==0)
340             return true;
341         try 
342         {
343             getServlet();
344         }
345         catch(Exception e)
346         {
347             Log.ignore(e);
348         }
349 
350         return isStarted()&& _unavailable==0;
351     }
352     
353     /* ------------------------------------------------------------ */
354     private void makeUnavailable(UnavailableException e)
355     {
356         if (_unavailableEx==e && _unavailable!=0)
357             return;
358 
359         _servletHandler.getServletContext().log("unavailable",e);
360 
361         _unavailableEx=e;
362         _unavailable=-1;
363         if (e.isPermanent())   
364             _unavailable=-1;
365         else
366         {
367             if (_unavailableEx.getUnavailableSeconds()>0)
368                 _unavailable=System.currentTimeMillis()+1000*_unavailableEx.getUnavailableSeconds();
369             else
370                 _unavailable=System.currentTimeMillis()+5000; // TODO configure
371         }
372     }
373     
374 
375     /* ------------------------------------------------------------ */
376 
377     private void makeUnavailable(Throwable e)
378     {
379         if (e instanceof UnavailableException)
380             makeUnavailable((UnavailableException)e);
381         else
382         {
383             _servletHandler.getServletContext().log("unavailable",e);
384             _unavailableEx=new UnavailableException(e.toString(),-1);
385             _unavailable=-1;
386         }
387     }
388 
389     /* ------------------------------------------------------------ */
390     private void initServlet()
391     	throws ServletException
392     {
393         Object old_run_as = null;
394         try
395         {
396             if (_servlet==null)
397                 _servlet=(Servlet)newInstance();
398             if (_config==null)
399                 _config=new Config();
400 
401             //handle any cusomizations of the servlet, such as @postConstruct
402             if (!(_servlet instanceof SingleThreadedWrapper))
403                 _servlet = getServletHandler().customizeServlet(_servlet);
404             
405             // Handle run as
406             if (_identityService!=null && _runAsToken!=null)
407             {
408                 old_run_as=_identityService.setRunAs(_identityService.getSystemUserIdentity(),_runAsToken);
409             }
410 
411             _servlet.init(_config);
412         }
413         catch (UnavailableException e)
414         {
415             makeUnavailable(e);
416             _servlet=null;
417             _config=null;
418             throw e;
419         }
420         catch (ServletException e)
421         {
422             makeUnavailable(e.getCause()==null?e:e.getCause());
423             _servlet=null;
424             _config=null;
425             throw e;
426         }
427         catch (Exception e)
428         {
429             makeUnavailable(e);
430             _servlet=null;
431             _config=null;
432             throw new ServletException(this.toString(),e);
433         }
434         finally
435         {
436             // pop run-as role
437             if (_identityService!=null && _runAsToken!=null)
438                 _identityService.unsetRunAs(old_run_as);
439         }
440     }
441     
442     
443     /* ------------------------------------------------------------ */
444     /**
445      * @see org.eclipse.jetty.server.UserIdentity.Scope#getContextPath()
446      */
447     public String getContextPath()
448     {
449         return _config.getServletContext().getContextPath();
450     }
451 
452     /* ------------------------------------------------------------ */
453     /**
454      * @see org.eclipse.jetty.server.UserIdentity.Scope#getRoleRefMap()
455      */
456     public Map<String, String> getRoleRefMap()
457     {
458         return _roleMap;
459     }
460 
461     /* ------------------------------------------------------------ */
462     /**
463      * @see org.eclipse.jetty.server.UserIdentity.Scope#getRunAsRole()
464      */
465     public String getRunAsRole()
466     {
467         return _runAsRole;
468     }
469 
470     /* ------------------------------------------------------------ */
471     /**
472      * Set the run-as role for this servlet
473      * @param role run-as role for this servlet
474      */
475     public void setRunAsRole(String role)
476     {
477         _runAsRole=role;
478     }
479 
480     /* ------------------------------------------------------------ */
481     /** Service a request with this servlet.
482      */
483     public void handle(Request baseRequest,
484                        ServletRequest request,
485                        ServletResponse response)
486         throws ServletException,
487                UnavailableException,
488                IOException
489     {
490         if (_class==null)
491             throw new UnavailableException("Servlet Not Initialized");
492         
493         Servlet servlet=_servlet;
494         synchronized(this)
495         {
496             if (_unavailable!=0 || !_initOnStartup)
497                 servlet=getServlet();
498             if (servlet==null)
499                 throw new UnavailableException("Could not instantiate "+_class);
500         }
501         
502         // Service the request
503         boolean servlet_error=true;
504         Object old_run_as = null;
505         boolean suspendable = baseRequest.isAsyncSupported();
506         try
507         {
508             // Handle aliased path
509             if (_forcedPath!=null)
510                 // TODO complain about poor naming to the Jasper folks
511                 request.setAttribute("org.apache.catalina.jsp_file",_forcedPath);
512 
513             // Handle run as
514             if (_identityService!=null && _runAsToken!=null)
515                 old_run_as=_identityService.setRunAs(baseRequest.getUserIdentity(),_runAsToken);
516             
517             if (!isAsyncSupported())
518                 baseRequest.setAsyncSupported(false);
519             
520             servlet.service(request,response);
521             servlet_error=false;
522         }
523         catch(UnavailableException e)
524         {
525             makeUnavailable(e);
526             throw _unavailableEx;
527         }
528         finally
529         {
530             baseRequest.setAsyncSupported(suspendable);
531             
532             // pop run-as role
533             if (_identityService!=null && _runAsToken!=null)
534                 _identityService.unsetRunAs(old_run_as);
535 
536             // Handle error params.
537             if (servlet_error)
538                 request.setAttribute("javax.servlet.error.servlet_name",getName());
539         }
540     }
541 
542  
543     /* ------------------------------------------------------------ */
544     /* ------------------------------------------------------------ */
545     /* ------------------------------------------------------------ */
546     protected class Config extends HolderConfig implements ServletConfig
547     {   
548         /* -------------------------------------------------------- */
549         public String getServletName()
550         {
551             return getName();
552         }
553         
554     }
555 
556     /* -------------------------------------------------------- */
557     /* -------------------------------------------------------- */
558     /* -------------------------------------------------------- */
559     private class SingleThreadedWrapper implements Servlet
560     {
561         Stack _stack=new Stack();
562         
563         public void destroy()
564         {
565             synchronized(this)
566             {
567                 while(_stack.size()>0)
568                     try { ((Servlet)_stack.pop()).destroy(); } catch (Exception e) { Log.warn(e); }
569             }
570         }
571 
572         public ServletConfig getServletConfig()
573         {
574             return _config;
575         }
576 
577         public String getServletInfo()
578         {
579             return null;
580         }
581 
582         public void init(ServletConfig config) throws ServletException
583         {
584             synchronized(this)
585             {
586                 if(_stack.size()==0)
587                 {
588                     try
589                     {
590                         Servlet s = (Servlet) newInstance();
591                         s = getServletHandler().customizeServlet(s);
592                         s.init(config);
593                         _stack.push(s);
594                     }
595                     catch (ServletException e)
596                     {
597                         throw e;
598                     }
599                     catch (Exception e)
600                     {
601                         throw new ServletException(e);
602                     }
603                 }
604             }
605         }
606 
607         public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
608         {
609             Servlet s;
610             synchronized(this)
611             {
612                 if(_stack.size()>0)
613                     s=(Servlet)_stack.pop();
614                 else
615                 {
616                     try
617                     {
618                         s = (Servlet) newInstance();
619                         s = getServletHandler().customizeServlet(s);
620                         s.init(_config);
621                     }
622                     catch (ServletException e)
623                     {
624                         throw e;
625                     }
626                     catch (IOException e)
627                     {
628                         throw e;
629                     }
630                     catch (Exception e)
631                     {
632                         throw new ServletException(e);
633                     }
634                 }
635             }
636             
637             try
638             {
639                 s.service(req,res);
640             }
641             finally
642             {
643                 synchronized(this)
644                 {
645                     _stack.push(s);
646                 }
647             }
648         }
649         
650     }
651 }
652 
653 
654 
655 
656