KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mortbay > jetty > servlet > ServletHandler


1 // ========================================================================
2
// $Id: ServletHandler.java,v 1.133 2006/03/15 14:43:00 gregwilkins Exp $
3
// Copyright 199-2004 Mort Bay Consulting Pty. Ltd.
4
// ------------------------------------------------------------------------
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
// ========================================================================
15

16 package org.mortbay.jetty.servlet;
17
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.OutputStream JavaDoc;
23 import java.net.MalformedURLException JavaDoc;
24 import java.net.URL JavaDoc;
25 import java.util.Collections JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.HashSet JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32
33 import javax.servlet.RequestDispatcher JavaDoc;
34 import javax.servlet.Servlet JavaDoc;
35 import javax.servlet.ServletContext JavaDoc;
36 import javax.servlet.ServletException JavaDoc;
37 import javax.servlet.UnavailableException JavaDoc;
38 import javax.servlet.http.HttpServletRequest JavaDoc;
39 import javax.servlet.http.HttpServletResponse JavaDoc;
40 import javax.servlet.http.HttpSession JavaDoc;
41
42 import org.apache.commons.logging.Log;
43 import org.mortbay.log.LogFactory;
44 import org.mortbay.http.EOFException;
45 import org.mortbay.http.HttpContext;
46 import org.mortbay.http.HttpException;
47 import org.mortbay.http.HttpFields;
48 import org.mortbay.http.HttpHandler;
49 import org.mortbay.http.HttpRequest;
50 import org.mortbay.http.HttpResponse;
51 import org.mortbay.http.PathMap;
52 import org.mortbay.http.Version;
53 import org.mortbay.util.ByteArrayISO8859Writer;
54 import org.mortbay.util.Container;
55 import org.mortbay.util.LogSupport;
56 import org.mortbay.util.MultiException;
57 import org.mortbay.util.Resource;
58 import org.mortbay.util.URI;
59
60
61 /* --------------------------------------------------------------------- */
62 /** Servlet HttpHandler.
63  * This handler maps requests to servlets that implement the
64  * javax.servlet.http.HttpServlet API.
65  * <P>
66  * This handler does not implement the full J2EE features and is intended to
67  * be used when a full web application is not required. Specifically filters
68  * and request wrapping are not supported.
69  * <P>
70  * If a SessionManager is not added to the handler before it is
71  * initialized, then a HashSessionManager with a standard
72  * java.util.Random generator is created.
73  * <P>
74  * @see org.mortbay.jetty.servlet.WebApplicationHandler
75  * @version $Id: ServletHandler.java,v 1.133 2006/03/15 14:43:00 gregwilkins Exp $
76  * @author Greg Wilkins
77  */

78 public class ServletHandler extends Container implements HttpHandler
79 {
80     private static Log log = LogFactory.getLog(ServletHandler.class);
81
82     /* ------------------------------------------------------------ */
83     public static final String JavaDoc __DEFAULT_SERVLET="default";
84     public static final String JavaDoc __J_S_CONTEXT_TEMPDIR="javax.servlet.context.tempdir";
85     public static final String JavaDoc __J_S_ERROR_EXCEPTION="javax.servlet.error.exception";
86     public static final String JavaDoc __J_S_ERROR_EXCEPTION_TYPE="javax.servlet.error.exception_type";
87     public static final String JavaDoc __J_S_ERROR_MESSAGE="javax.servlet.error.message";
88     public static final String JavaDoc __J_S_ERROR_REQUEST_URI="javax.servlet.error.request_uri";
89     public static final String JavaDoc __J_S_ERROR_SERVLET_NAME="javax.servlet.error.servlet_name";
90     public static final String JavaDoc __J_S_ERROR_STATUS_CODE="javax.servlet.error.status_code";
91     
92     /* ------------------------------------------------------------ */
93     private static final boolean __Slosh2Slash=File.separatorChar=='\\';
94     private static String JavaDoc __AllowString="GET, HEAD, POST, OPTIONS, TRACE";
95
96     
97     /* ------------------------------------------------------------ */
98     private boolean _usingCookies=true;
99     private boolean _autoInitializeServlets=true;
100     private String JavaDoc _name;
101     
102     /* ------------------------------------------------------------ */
103     protected PathMap _servletMap=new PathMap();
104     protected Map JavaDoc _nameMap=new HashMap JavaDoc();
105     protected Map JavaDoc _attributes=new HashMap JavaDoc(3);
106     protected String JavaDoc _formLoginPage;
107     protected String JavaDoc _formErrorPage;
108     protected SessionManager _sessionManager;
109
110     protected transient Context JavaDoc _context;
111     protected transient ClassLoader JavaDoc _loader;
112     protected transient Log _contextLog;
113     protected transient HttpContext _httpContext;
114
115     /* ------------------------------------------------------------ */
116     /** Constructor.
117      */

118     public ServletHandler()
119     {
120         _context=new Context JavaDoc();
121     }
122
123     /* ------------------------------------------------------------ */
124     public void setName(String JavaDoc name)
125     {
126         _name=name;
127     }
128     
129     /* ------------------------------------------------------------ */
130     public String JavaDoc getName()
131     {
132         if (_name==null)
133         {
134             _name=this.getClass().getName();
135             if (!log.isDebugEnabled())
136                 _name=_name.substring(_name.lastIndexOf('.')+1);
137         }
138         return _name;
139     }
140     
141     /* ------------------------------------------------------------ */
142     public HttpContext getHttpContext()
143     {
144         return _httpContext;
145     }
146     
147     /* ------------------------------------------------------------ */
148     public void initialize(HttpContext context)
149     {
150         SessionManager sessionManager=getSessionManager();
151         
152
153         if (_httpContext!=null&& _httpContext!=context)
154             throw new IllegalStateException JavaDoc("Can't initialize handler for different context");
155         _httpContext=context;
156         
157         sessionManager.initialize(this);
158     }
159
160     /* ------------------------------------------------------------ */
161     public void formAuthInit(String JavaDoc formLoginPage,
162                              String JavaDoc formErrorPage)
163     {
164         _formLoginPage=formLoginPage;
165         _formErrorPage=formErrorPage;
166     }
167     
168     /* ------------------------------------------------------------ */
169     public void setSessionManager(SessionManager sm)
170     {
171         if (isStarted())
172             throw new IllegalStateException JavaDoc("Started");
173
174         int mii=0;
175         boolean setMii=false;
176  
177         if ( _sessionManager!=null)
178         {
179             mii=_sessionManager.getMaxInactiveInterval();
180             setMii=true;
181             if (getHttpContext()!=null)
182                 _sessionManager.initialize(null);
183             removeComponent(_sessionManager);
184         }
185
186         _sessionManager=sm;
187
188         if (_sessionManager!=null)
189         {
190             if (getHttpContext()!=null)
191                 _sessionManager.initialize(this);
192             if (setMii)
193                 _sessionManager.setMaxInactiveInterval(mii);
194             addComponent(_sessionManager);
195         }
196         
197         _sessionManager=sm;
198     }
199     
200     /* ------------------------------------------------------------ */
201     public SessionManager getSessionManager()
202     {
203         if (_sessionManager==null)
204         {
205             _sessionManager = new HashSessionManager();
206             addComponent(_sessionManager);
207         }
208         return _sessionManager;
209     }
210     
211     /* ------------------------------------------------------------ */
212     public ServletContext JavaDoc getServletContext() { return _context; }
213
214     /* ------------------------------------------------------------ */
215     public PathMap getServletMap() { return _servletMap; }
216     
217     /* ------------------------------------------------------------ */
218     public boolean isUsingCookies() { return _usingCookies; }
219     
220     /* ------------------------------------------------------------ */
221     /** Set the dynamic servlet path.
222      * @deprecated Use org.mortbay.jetty.servlet.Invoker
223      */

224     public void setDynamicServletPathSpec(String JavaDoc dynamicServletPathSpec)
225     {
226         log.warn("setDynamicServletPathSpec is Deprecated.");
227     }
228     
229     /* ------------------------------------------------------------ */
230     /** Set dynamic servlet initial parameters.
231      * @deprecated Use org.mortbay.jetty.servlet.Invoker
232      */

233     public void setDynamicInitParams(Map JavaDoc initParams)
234     {
235         log.warn("setDynamicInitParams is Deprecated.");
236     }
237
238     /* ------------------------------------------------------------ */
239     /** Set serving dynamic system servlets.
240      * @deprecated Use org.mortbay.jetty.servlet.Invoker
241      */

242     public void setServeDynamicSystemServlets(boolean b)
243     {
244         log.warn("setServeDynamicSystemServlets is Deprecated.");
245     }
246     
247     /* ------------------------------------------------------------ */
248     public ClassLoader JavaDoc getClassLoader()
249     {
250         return _loader;
251     }
252
253     /* ------------------------------------------------------------ */
254     /**
255      * @param uc If true, cookies are used for sessions
256      */

257     public void setUsingCookies(boolean uc)
258     {
259         _usingCookies=uc;
260     }
261
262     /* ------------------------------------------------------------ */
263     public ServletHolder newServletHolder(String JavaDoc name,
264                                           String JavaDoc servletClass,
265                                           String JavaDoc forcedPath)
266     {
267         if (_nameMap.containsKey(name))
268             throw new IllegalArgumentException JavaDoc("Named servlet already exists: "+name);
269         
270         ServletHolder holder = new ServletHolder(this,name,servletClass,forcedPath);
271         addServletHolder(holder);
272         
273         return holder;
274     }
275
276     /* ------------------------------------------------------------ */
277     public ServletHolder newServletHolder(String JavaDoc name,
278                                           String JavaDoc servletClass)
279     {
280         return newServletHolder(name,servletClass,null);
281     }
282     
283     /* ------------------------------------------------------------ */
284     public ServletHolder getServletHolder(String JavaDoc name)
285     {
286         return (ServletHolder)_nameMap.get(name);
287     }
288
289     /* ------------------------------------------------------------ */
290     /**
291      * Map a servlet to a pathSpec
292      * @param pathSpec The pathspec to map
293      * @param servletName The name of the servlet, which must have already been added.
294      * @return The servlet holder of the mapped servlet.
295      */

296     public ServletHolder mapPathToServlet(String JavaDoc pathSpec,
297                                           String JavaDoc servletName)
298     {
299         ServletHolder holder =(ServletHolder)_nameMap.get(servletName);
300
301         if (!pathSpec.startsWith("/") && !pathSpec.startsWith("*"))
302         {
303             log.warn("pathSpec should start with '/' or '*' : "+pathSpec);
304             pathSpec="/"+pathSpec;
305         }
306         
307         if (holder==null)
308             throw new IllegalArgumentException JavaDoc("Unknown servlet: "+servletName);
309         _servletMap.put(pathSpec,holder);
310         return holder;
311     }
312     
313     /* ------------------------------------------------------------ */
314     /** Add a servlet.
315      * @param name The servlet name.
316      * @param pathSpec A path specification to map this servlet to.
317      * @param servletClass The class name of the servlet.
318      * @param forcedPath If non null, the request attribute
319      * javax.servlet.include.servlet_path will be set to this path before
320      * service is called.
321      * @return The ServletHolder for the servlet.
322      */

323     public ServletHolder addServlet(String JavaDoc name,
324                                     String JavaDoc pathSpec,
325                                     String JavaDoc servletClass,
326                                     String JavaDoc forcedPath)
327     {
328         ServletHolder holder = getServletHolder(name);
329         if (holder==null)
330             holder = newServletHolder(name,servletClass,forcedPath);
331         mapPathToServlet(pathSpec,name);
332         if (isStarted() && !holder.isStarted())
333         {
334             try{holder.start();}
335             catch(Exception JavaDoc e){log.warn(LogSupport.EXCEPTION,e);}
336         }
337         return holder;
338     }
339     
340     /* ------------------------------------------------------------ */
341     /** Add a servlet.
342      * @param name The servlet name.
343      * @param pathSpec A path specification to map this servlet to.
344      * @param servletClass The class name of the servlet.
345      * @return The ServletHolder for the servlet.
346      */

347     public ServletHolder addServlet(String JavaDoc name,
348                                     String JavaDoc pathSpec,
349                                     String JavaDoc servletClass)
350     {
351         return addServlet(name,pathSpec,servletClass,null);
352     }
353
354     
355     /* ------------------------------------------------------------ */
356     /**
357      * Add a servlet instance to this handler and map it to a pathspec.
358      * @param pathSpec The pathmapping
359      * @param servletClass The class of the servlet
360      * @return The created ServletHolder
361      */

362     public ServletHolder addServlet(String JavaDoc pathSpec,
363                                     String JavaDoc servletClass)
364     {
365         return addServlet(servletClass,pathSpec,servletClass,null);
366     }
367     
368     /* ------------------------------------------------------------ */
369     /**
370      * Register an existing ServletHolder with this handler.
371      * @param holder the ServletHolder to register.
372      */

373     public void addServletHolder(ServletHolder holder)
374     {
375         ServletHolder existing = (ServletHolder)
376         _nameMap.get(holder.getName());
377         if (existing==null)
378             _nameMap.put(holder.getName(),holder);
379         else if (existing!=holder)
380             throw new IllegalArgumentException JavaDoc("Holder already exists for name: "+holder.getName());
381         addComponent(holder);
382     }
383     
384     /* ------------------------------------------------------------ */
385     public boolean isAutoInitializeServlets()
386     {
387         return _autoInitializeServlets;
388     }
389
390     /* ------------------------------------------------------------ */
391     public void setAutoInitializeServlets(boolean b)
392     {
393         _autoInitializeServlets=b;
394     }
395     
396     /* ----------------------------------------------------------------- */
397     protected synchronized void doStart()
398         throws Exception JavaDoc
399     {
400         if (isStarted())
401             return;
402         
403         _contextLog = LogFactory.getLog("org.mortbay.jetty.context."+getHttpContext().getHttpContextName());
404         
405         if (_contextLog==null)
406             _contextLog=log;
407         
408         if (_sessionManager!=null)
409             _sessionManager.start();
410         
411         // Initialize classloader
412
_loader=getHttpContext().getClassLoader();
413
414         if (_autoInitializeServlets)
415             initializeServlets();
416     }
417     
418     /* ------------------------------------------------------------ */
419     /** Get Servlets.
420      * @return Array of defined servlets
421      */

422     public ServletHolder[] getServlets()
423     {
424         // Sort and Initialize servlets
425
HashSet JavaDoc holder_set = new HashSet JavaDoc(_nameMap.size());
426         holder_set.addAll(_nameMap.values());
427         ServletHolder holders [] = (ServletHolder [])
428             holder_set.toArray(new ServletHolder [holder_set.size()]);
429         java.util.Arrays.sort (holders);
430         return holders;
431     }
432     
433     /* ------------------------------------------------------------ */
434     /** Initialize load-on-startup servlets.
435      * Called automatically from start if autoInitializeServlet is true.
436      */

437     public void initializeServlets()
438         throws Exception JavaDoc
439     {
440         MultiException mx = new MultiException();
441         
442         // Sort and Initialize servlets
443
ServletHolder[] holders = getServlets();
444         for (int i=0; i<holders.length; i++)
445         {
446             try{holders[i].start();}
447             catch(Exception JavaDoc e)
448             {
449                 log.debug(LogSupport.EXCEPTION,e);
450                 mx.add(e);
451             }
452         }
453         mx.ifExceptionThrow();
454     }
455     
456     /* ----------------------------------------------------------------- */
457     protected synchronized void doStop()
458         throws Exception JavaDoc
459     {
460         // Sort and Initialize servlets
461
ServletHolder[] holders = getServlets();
462         
463         // Stop servlets
464
for (int i=holders.length; i-->0;)
465         {
466             try
467             {
468                 if (holders[i].isStarted())
469                     holders[i].stop();
470             }
471             catch(Exception JavaDoc e){log.warn(LogSupport.EXCEPTION,e);}
472         }
473         
474         // Stop the session manager
475
_sessionManager.stop();
476         _attributes.clear();
477         _loader=null;
478     }
479
480     /* ------------------------------------------------------------ */
481     public HttpSession JavaDoc getHttpSession(String JavaDoc id)
482     {
483         return _sessionManager.getHttpSession(id);
484     }
485     
486     /* ------------------------------------------------------------ */
487     public HttpSession JavaDoc newHttpSession(HttpServletRequest JavaDoc request)
488     {
489         return _sessionManager.newHttpSession(request);
490     }
491
492     /* ------------------------------------------------------------ */
493     /**
494      * Set the session timeout interval in seconds.
495      * @param seconds the length of the session timeout interval in seconds.
496      */

497     public void setSessionInactiveInterval(int seconds)
498     {
499         _sessionManager.setMaxInactiveInterval(seconds);
500     }
501
502     /* ----------------------------------------------------------------- */
503     /** Handle request.
504      * @param pathInContext
505      * @param pathParams
506      * @param httpRequest
507      * @param httpResponse
508      * @exception IOException
509      */

510     public void handle(String JavaDoc pathInContext,
511                        String JavaDoc pathParams,
512                        HttpRequest httpRequest,
513                        HttpResponse httpResponse)
514          throws IOException JavaDoc
515     {
516         if (!isStarted())
517             return;
518         
519         // Handle TRACE
520
if (HttpRequest.__TRACE.equals(httpRequest.getMethod()))
521         {
522             handleTrace(httpRequest,httpResponse);
523             return;
524         }
525
526         // Look for existing request/response objects (from enterScope call)
527
ServletHttpRequest request = (ServletHttpRequest) httpRequest.getWrapper();
528         ServletHttpResponse response = (ServletHttpResponse) httpResponse.getWrapper();
529         if (request==null)
530         {
531             // Not in ServletHttpContext, but bumble on anyway
532
request = new ServletHttpRequest(this,pathInContext,httpRequest);
533             response = new ServletHttpResponse(request,httpResponse);
534             httpRequest.setWrapper(request);
535             httpResponse.setWrapper(response);
536         }
537         else
538         {
539             request.recycle(this,pathInContext);
540             response.recycle();
541         }
542         
543         // Look for the servlet
544
Map.Entry JavaDoc servlet=getHolderEntry(pathInContext);
545         ServletHolder servletHolder=servlet==null?null:(ServletHolder)servlet.getValue();
546         if(log.isDebugEnabled())log.debug("servlet="+servlet);
547             
548         try
549         {
550             // Adjust request paths
551
if (servlet!=null)
552             {
553                 String JavaDoc servletPathSpec=(String JavaDoc)servlet.getKey();
554                 request.setServletPaths(PathMap.pathMatch(servletPathSpec,pathInContext),
555                                         PathMap.pathInfo(servletPathSpec,pathInContext),
556                                         servletHolder);
557             }
558             
559             // Handle the session ID
560
request.setRequestedSessionId(pathParams);
561             HttpSession JavaDoc session=request.getSession(false);
562             if (session!=null)
563                 ((SessionManager.Session)session).access();
564             if(log.isDebugEnabled())log.debug("session="+session);
565             
566             // Do that funky filter and servlet thang!
567
if (servletHolder!=null)
568                 dispatch(pathInContext,request,response,servletHolder, Dispatcher.__REQUEST);
569         }
570         catch(Exception JavaDoc e)
571         {
572             log.debug(LogSupport.EXCEPTION,e);
573             
574             Throwable JavaDoc th=e;
575             while (th instanceof ServletException JavaDoc)
576             {
577                 log.warn(LogSupport.EXCEPTION, th);
578                 Throwable JavaDoc cause=((ServletException JavaDoc)th).getRootCause();
579                 if (cause==th || cause==null)
580                     break;
581                 th=cause;
582             }
583             
584             if (th instanceof HttpException)
585                 throw (HttpException)th;
586             if (th instanceof EOFException)
587                 throw (IOException JavaDoc)th;
588             else if (log.isDebugEnabled() || !( th instanceof java.io.IOException JavaDoc))
589             {
590                 if (_contextLog!=null)
591                 {
592                     if (th instanceof RuntimeException JavaDoc)
593                         _contextLog.error(httpRequest.getURI()+": ",th);
594                     else
595                         _contextLog.warn(httpRequest.getURI()+": ",th);
596                 }
597                 
598                 if(log.isDebugEnabled())
599                 {
600                     if (th instanceof RuntimeException JavaDoc)
601                         log.error(httpRequest.getURI()+": ",th);
602                     else
603                         log.warn(httpRequest.getURI()+": ",th);
604                     log.debug(httpRequest);
605                 }
606             }
607             
608             httpResponse.getHttpConnection().forceClose();
609             if (!httpResponse.isCommitted())
610             {
611                 request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
612                 request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
613                 if (th instanceof UnavailableException JavaDoc)
614                 {
615                     UnavailableException JavaDoc ue = (UnavailableException JavaDoc)th;
616                     if (ue.isPermanent())
617                         response.sendError(HttpResponse.__404_Not_Found,e.getMessage());
618                     else
619                         response.sendError(HttpResponse.__503_Service_Unavailable,e.getMessage());
620                 }
621                 else
622                     response.sendError(HttpResponse.__500_Internal_Server_Error,e.getMessage());
623             }
624             else
625                 if(log.isDebugEnabled())log.debug("Response already committed for handling "+th);
626         }
627         catch(Error JavaDoc e)
628         {
629             log.warn("Error for "+httpRequest.getURI(),e);
630             if(log.isDebugEnabled())log.debug(httpRequest);
631             
632             httpResponse.getHttpConnection().forceClose();
633             if (!httpResponse.isCommitted())
634             {
635                 request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
636                 request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
637                 response.sendError(HttpResponse.__500_Internal_Server_Error,
638                                    e.getMessage());
639             }
640             else
641                 if(log.isDebugEnabled())log.debug("Response already committed for handling ",e);
642         }
643         finally
644         {
645             if (servletHolder!=null && response!=null)
646             {
647                 response.complete();
648             }
649         }
650     }
651
652     /* ------------------------------------------------------------ */
653     /** Dispatch to a servletHolder.
654      * This method may be specialized to insert extra handling in the
655      * dispatch of a request to a specific servlet. This is used by
656      * WebApplicatonHandler to implement dispatched filters.
657      * The default implementation simply calls
658      * ServletHolder.handle(request,response)
659      * @param pathInContext The path used to select the servlet holder.
660      * @param request
661      * @param response
662      * @param servletHolder
663      * @param type the type of dispatch as defined in the Dispatcher class.
664      * @exception ServletException
665      * @exception UnavailableException
666      * @exception IOException
667      */

668     protected void dispatch(String JavaDoc pathInContext,
669                             HttpServletRequest JavaDoc request,
670                             HttpServletResponse JavaDoc response,
671                             ServletHolder servletHolder,
672                             int type)
673         throws ServletException JavaDoc,
674                UnavailableException JavaDoc,
675                IOException JavaDoc
676     {
677         servletHolder.handle(request,response);
678     }
679     
680     
681     /* ------------------------------------------------------------ */
682     /** ServletHolder matching path.
683      * @param pathInContext Path within context.
684      * @return PathMap Entries pathspec to ServletHolder
685      */

686     public Map.Entry JavaDoc getHolderEntry(String JavaDoc pathInContext)
687     {
688         return _servletMap.getMatch(pathInContext);
689     }
690     
691
692     /* ------------------------------------------------------------ */
693     public Set JavaDoc getResourcePaths(String JavaDoc uriInContext)
694     {
695         try
696         {
697             uriInContext=URI.canonicalPath(uriInContext);
698             if (uriInContext==null)
699                 return Collections.EMPTY_SET;
700             Resource resource=getHttpContext().getResource(uriInContext);
701             if (resource==null || !resource.isDirectory())
702                 return Collections.EMPTY_SET;
703             String JavaDoc[] contents=resource.list();
704             if (contents==null || contents.length==0)
705                 return Collections.EMPTY_SET;
706             HashSet JavaDoc set = new HashSet JavaDoc(contents.length*2);
707             for (int i=0;i<contents.length;i++)
708                 set.add(URI.addPaths(uriInContext,contents[i]));
709             return set;
710         }
711         catch(Exception JavaDoc e)
712         {
713             e.printStackTrace();
714             LogSupport.ignore(log,e);
715         }
716         
717         return Collections.EMPTY_SET;
718     }
719     
720
721     /* ------------------------------------------------------------ */
722     /** Get a Resource.
723      * If no resource is found, resource aliases are tried.
724      * @param uriInContext
725      * @return URL of the resource.
726      * @exception MalformedURLException
727      */

728     public URL JavaDoc getResource(String JavaDoc uriInContext)
729         throws MalformedURLException JavaDoc
730     {
731         if (uriInContext==null || !uriInContext.startsWith("/"))
732             throw new MalformedURLException JavaDoc(uriInContext);
733         
734         try{
735             Resource resource = getHttpContext().getResource(uriInContext);
736             if (resource!=null && resource.exists())
737                 return resource.getURL();
738         }
739         catch(IllegalArgumentException JavaDoc e)
740         {
741             LogSupport.ignore(log,e);
742         }
743         catch(MalformedURLException JavaDoc e)
744         {
745             throw e;
746         }
747         catch(IOException JavaDoc e)
748         {
749             log.warn(LogSupport.EXCEPTION,e);
750         }
751         return null;
752     }
753
754     /* ------------------------------------------------------------ */
755     public InputStream JavaDoc getResourceAsStream(String JavaDoc uriInContext)
756     {
757         if (uriInContext==null || !uriInContext.startsWith("/"))
758             return null;
759         try
760         {
761             Resource resource = getHttpContext().getResource(uriInContext);
762             if (resource!=null)
763                 return resource.getInputStream();
764             
765             uriInContext=URI.canonicalPath(uriInContext);
766             URL JavaDoc url = getResource(uriInContext);
767             if (url!=null)
768                 return url.openStream();
769         }
770         catch(IOException JavaDoc e) {LogSupport.ignore(log,e);}
771         return null;
772     }
773
774     /* ------------------------------------------------------------ */
775     public String JavaDoc getRealPath(String JavaDoc path)
776     {
777         if(log.isDebugEnabled())log.debug("getRealPath of "+path+" in "+this);
778
779         if (__Slosh2Slash)
780             path=path.replace('\\','/');
781         path=URI.canonicalPath(path);
782         if (path==null)
783             return null;
784
785         Resource baseResource=getHttpContext().getBaseResource();
786         if (baseResource==null )
787             return null;
788
789         try{
790             Resource resource = baseResource.addPath(path);
791             File JavaDoc file = resource.getFile();
792
793             return (file==null)?null:(file.getAbsolutePath());
794         }
795         catch(IOException JavaDoc e)
796         {
797             log.warn(LogSupport.EXCEPTION,e);
798             return null;
799         }
800     }
801
802     /* ------------------------------------------------------------ */
803     public RequestDispatcher JavaDoc getRequestDispatcher(String JavaDoc uriInContext)
804     {
805         if (uriInContext == null)
806             return null;
807
808         if (!uriInContext.startsWith("/"))
809             return null;
810         
811         try
812         {
813             String JavaDoc query=null;
814             int q=0;
815             if ((q=uriInContext.indexOf('?'))>0)
816             {
817                 query=uriInContext.substring(q+1);
818                 uriInContext=uriInContext.substring(0,q);
819             }
820             if ((q=uriInContext.indexOf(';'))>0)
821                 uriInContext=uriInContext.substring(0,q);
822
823             String JavaDoc pathInContext=URI.canonicalPath(URI.decodePath(uriInContext));
824             Map.Entry JavaDoc entry=getHolderEntry(pathInContext);
825             if (entry!=null)
826                 return new Dispatcher(ServletHandler.this,
827                                       uriInContext,
828                                       pathInContext,
829                                       query,
830                                       entry);
831         }
832         catch(Exception JavaDoc e)
833         {
834             LogSupport.ignore(log,e);
835         }
836         return null;
837     }
838
839     /* ------------------------------------------------------------ */
840     /** Get Named dispatcher.
841      * @param name The name of the servlet. If null or empty string, the
842      * containers default servlet is returned.
843      * @return Request dispatcher for the named servlet.
844      */

845     public RequestDispatcher JavaDoc getNamedDispatcher(String JavaDoc name)
846     {
847         if (name == null || name.length()==0)
848             name=__DEFAULT_SERVLET;
849
850         try { return new Dispatcher(ServletHandler.this,name); }
851         catch(Exception JavaDoc e) {LogSupport.ignore(log,e);}
852         
853         return null;
854     }
855
856
857     
858     /* ------------------------------------------------------------ */
859     protected void notFound(HttpServletRequest JavaDoc request,
860                   HttpServletResponse JavaDoc response)
861         throws IOException JavaDoc
862     {
863         if(log.isDebugEnabled())log.debug("Not Found "+request.getRequestURI());
864         String JavaDoc method=request.getMethod();
865             
866         // Not found special requests.
867
if (method.equals(HttpRequest.__GET) ||
868             method.equals(HttpRequest.__HEAD) ||
869             method.equals(HttpRequest.__POST))
870         {
871             response.sendError(HttpResponse.__404_Not_Found);
872         }
873         else if (method.equals(HttpRequest.__TRACE))
874             handleTrace(request,response);
875         else if (method.equals(HttpRequest.__OPTIONS))
876             handleOptions(request,response);
877         else
878         {
879             // Unknown METHOD
880
response.setHeader(HttpFields.__Allow,__AllowString);
881             response.sendError(HttpResponse.__405_Method_Not_Allowed);
882         }
883     }
884     
885     /* ------------------------------------------------------------ */
886     protected void handleTrace(HttpServletRequest JavaDoc request,
887                             HttpServletResponse JavaDoc response)
888         throws IOException JavaDoc
889     {
890         response.setHeader(HttpFields.__ContentType,
891                            HttpFields.__MessageHttp);
892         OutputStream JavaDoc out = response.getOutputStream();
893         ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
894         writer.write(request.toString());
895         writer.flush();
896         response.setIntHeader(HttpFields.__ContentLength,writer.size());
897         writer.writeTo(out);
898         out.flush();
899     }
900     
901     /* ------------------------------------------------------------ */
902     protected void handleOptions(HttpServletRequest JavaDoc request,
903                               HttpServletResponse JavaDoc response)
904         throws IOException JavaDoc
905     {
906         // Handle OPTIONS request for entire server
907
if ("*".equals(request.getRequestURI()))
908         {
909             // 9.2
910
response.setIntHeader(HttpFields.__ContentLength,0);
911             response.setHeader(HttpFields.__Allow,__AllowString);
912             response.flushBuffer();
913         }
914         else
915             response.sendError(HttpResponse.__404_Not_Found);
916     }
917
918     /* ------------------------------------------------------------ */
919     public String JavaDoc getErrorPage(int status,ServletHttpRequest request)
920     {
921         return null;
922     }
923     
924     /* ------------------------------------------------------------ */
925     /** Get context attribute.
926      * Tries ServletHandler attributes and then delegated to HttpContext.
927      * @param name attribute name.
928      * @return attribute
929      */

930     protected Object JavaDoc getContextAttribute(String JavaDoc name)
931     {
932         if (ServletHandler.__J_S_CONTEXT_TEMPDIR.equals(name))
933         {
934             // Initialize temporary directory
935
Object JavaDoc t = getHttpContext().getAttribute(ServletHandler.__J_S_CONTEXT_TEMPDIR);
936
937             if (t instanceof File JavaDoc)
938                 return (File JavaDoc)t;
939             
940             return getHttpContext().getTempDirectory();
941         }
942
943         if (_attributes.containsKey(name))
944             return _attributes.get(name);
945         return getHttpContext().getAttribute(name);
946     }
947
948     /* ------------------------------------------------------------ */
949     /** Get context attribute names.
950      * Combines ServletHandler and HttpContext attributes.
951      */

952     protected Enumeration JavaDoc getContextAttributeNames()
953     {
954         if (_attributes.size()==0)
955             return getHttpContext().getAttributeNames();
956         HashSet JavaDoc set=new HashSet JavaDoc(_attributes.keySet());
957         Enumeration JavaDoc e=getHttpContext().getAttributeNames();
958         while(e.hasMoreElements())
959             set.add(e.nextElement());
960         return Collections.enumeration(set);
961     }
962
963     /* ------------------------------------------------------------ */
964     /* Set a Servlet context attribute.
965      * Servlet Context attributes may hide HttpContext attributes.
966      */

967     protected void setContextAttribute(String JavaDoc name, Object JavaDoc value)
968     {
969         _attributes.put(name,value);
970     }
971     
972     /* ------------------------------------------------------------ */
973     /* Remove a Servlet context attribute.
974      * Servlet Context attributes may hide HttpContext attributes.
975      */

976     protected void removeContextAttribute(String JavaDoc name)
977     {
978         _attributes.remove(name);
979     }
980     
981
982     /* ----------------------------------------------------------------- */
983     public void handleTrace(HttpRequest request,
984                             HttpResponse response)
985         throws IOException JavaDoc
986     {
987         boolean trace=getHttpContext().getHttpServer().getTrace();
988         
989         // Handle TRACE by returning request header
990
response.setField(HttpFields.__ContentType,
991                           HttpFields.__MessageHttp);
992         if (trace)
993         {
994             OutputStream JavaDoc out = response.getOutputStream();
995             ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
996             writer.write(request.toString());
997             writer.flush();
998             response.setIntField(HttpFields.__ContentLength,writer.size());
999             writer.writeTo(out);
1000            out.flush();
1001        }
1002        request.setHandled(true);
1003    }
1004    
1005    /* ----------------------------------------------------------------- */
1006    public void destroy()
1007    {
1008        Iterator JavaDoc iter = _nameMap.values().iterator();
1009        while (iter.hasNext())
1010        {
1011            Object JavaDoc sh=iter.next();
1012            iter.remove();
1013            removeComponent(sh);
1014        }
1015        
1016        if (_sessionManager!=null)
1017            removeComponent(_sessionManager);
1018        _sessionManager=null;
1019        _context=null;
1020        super.destroy();
1021    }
1022    
1023    /* ----------------------------------------------------------------- */
1024    protected void finalize() throws Throwable JavaDoc
1025    {
1026        destroy();
1027    }
1028    
1029    /* ------------------------------------------------------------ */
1030    /* ------------------------------------------------------------ */
1031    /* ------------------------------------------------------------ */
1032    class Context implements ServletContext JavaDoc
1033    {
1034        
1035        /* -------------------------------------------------------- */
1036        ServletHandler getServletHandler()
1037        {
1038            return ServletHandler.this;
1039        }
1040        
1041        /* -------------------------------------------------------- */
1042        public ServletContext JavaDoc getContext(String JavaDoc uri)
1043        {
1044            ServletHandler handler= (ServletHandler)
1045                getHttpContext().getHttpServer()
1046                .findHandler(org.mortbay.jetty.servlet.ServletHandler.class,
1047                             uri,
1048                             getHttpContext().getVirtualHosts());
1049            if (handler!=null)
1050                return handler.getServletContext();
1051            return null;
1052        }
1053
1054        /* ------------------------------------------------------------ */
1055        public int getMajorVersion()
1056        {
1057            return 2;
1058        }
1059
1060        /* ------------------------------------------------------------ */
1061        public int getMinorVersion()
1062        {
1063            return 4;
1064        }
1065
1066        /* ------------------------------------------------------------ */
1067        public String JavaDoc getMimeType(String JavaDoc file)
1068        {
1069            return getHttpContext().getMimeByExtension(file);
1070        }
1071
1072        /* ------------------------------------------------------------ */
1073        public Set JavaDoc getResourcePaths(String JavaDoc uriInContext)
1074        {
1075            return ServletHandler.this.getResourcePaths(uriInContext);
1076        }
1077
1078        /* ------------------------------------------------------------ */
1079        public URL JavaDoc getResource(String JavaDoc uriInContext)
1080            throws MalformedURLException JavaDoc
1081        {
1082            return ServletHandler.this.getResource(uriInContext);
1083        }
1084
1085        /* ------------------------------------------------------------ */
1086        public InputStream JavaDoc getResourceAsStream(String JavaDoc uriInContext)
1087        {
1088            return ServletHandler.this.getResourceAsStream(uriInContext);
1089        }
1090
1091        /* ------------------------------------------------------------ */
1092        public String JavaDoc getRealPath(String JavaDoc path)
1093        {
1094            return ServletHandler.this.getRealPath(path);
1095        }
1096
1097        /* ------------------------------------------------------------ */
1098        public RequestDispatcher JavaDoc getRequestDispatcher(String JavaDoc uriInContext)
1099        {
1100            return ServletHandler.this.getRequestDispatcher(uriInContext);
1101        }
1102
1103        /* ------------------------------------------------------------ */
1104        public RequestDispatcher JavaDoc getNamedDispatcher(String JavaDoc name)
1105        {
1106            return ServletHandler.this.getNamedDispatcher(name);
1107        }
1108    
1109        /* ------------------------------------------------------------ */
1110        /**
1111         * @deprecated
1112         */

1113        public Servlet JavaDoc getServlet(String JavaDoc name)
1114        {
1115            return null;
1116        }
1117
1118        /* ------------------------------------------------------------ */
1119        /**
1120         * @deprecated
1121         */

1122        public Enumeration JavaDoc getServlets()
1123        {
1124            return Collections.enumeration(Collections.EMPTY_LIST);
1125        }
1126
1127        /* ------------------------------------------------------------ */
1128        /**
1129         * @deprecated
1130         */

1131        public Enumeration JavaDoc getServletNames()
1132        {
1133            return Collections.enumeration(Collections.EMPTY_LIST);
1134        }
1135    
1136        /* ------------------------------------------------------------ */
1137        /** Servlet Log.
1138         * Log message to servlet log. Use either the system log or a
1139         * LogSinkset via the context attribute
1140         * org.mortbay.jetty.servlet.Context.LogSink
1141         * @param msg
1142         */

1143        public void log(String JavaDoc msg)
1144        {
1145            _contextLog.info(msg);
1146        }
1147
1148        /* ------------------------------------------------------------ */
1149        /**
1150         * @deprecated As of Java Servlet API 2.1, use
1151         * {@link #log(String message, Throwable throwable)}
1152         * instead.
1153         */

1154        public void log(Exception JavaDoc e, String JavaDoc msg)
1155        {
1156            _contextLog.warn(msg,e);
1157        }
1158
1159        /* ------------------------------------------------------------ */
1160        public void log(String JavaDoc msg, Throwable JavaDoc th)
1161        {
1162            _contextLog.warn(msg,th);
1163        }
1164
1165        /* ------------------------------------------------------------ */
1166        public String JavaDoc getServerInfo()
1167        {
1168            return Version.getImplVersion();
1169        }
1170
1171
1172        /* ------------------------------------------------------------ */
1173        /** Get context init parameter.
1174         * Delegated to HttpContext.
1175         * @param param param name
1176         * @return param value or null
1177         */

1178        public String JavaDoc getInitParameter(String JavaDoc param)
1179        {
1180            return getHttpContext().getInitParameter(param);
1181        }
1182
1183        /* ------------------------------------------------------------ */
1184        /** Get context init parameter names.
1185         * Delegated to HttpContext.
1186         * @return Enumeration of names
1187         */

1188        public Enumeration JavaDoc getInitParameterNames()
1189        {
1190            return getHttpContext().getInitParameterNames();
1191        }
1192
1193    
1194        /* ------------------------------------------------------------ */
1195        /** Get context attribute.
1196         * Tries ServletHandler attributes and then delegated to HttpContext.
1197         * @param name attribute name.
1198         * @return attribute
1199         */

1200        public Object JavaDoc getAttribute(String JavaDoc name)
1201        {
1202            return getContextAttribute(name);
1203        }
1204
1205        /* ------------------------------------------------------------ */
1206        /** Get context attribute names.
1207         * Combines ServletHandler and HttpContext attributes.
1208         */

1209        public Enumeration JavaDoc getAttributeNames()
1210        {
1211            return getContextAttributeNames();
1212        }
1213
1214        /* ------------------------------------------------------------ */
1215        /** Set context attribute names.
1216         * Sets the ServletHandler attributes and may hide HttpContext attributes.
1217         * @param name attribute name.
1218         * @param value attribute value
1219         */

1220        public void setAttribute(String JavaDoc name, Object JavaDoc value)
1221        {
1222            setContextAttribute(name, value);
1223        }
1224
1225        /* ------------------------------------------------------------ */
1226        /** Remove context attribute.
1227         * Puts a null into the ServletHandler attributes and may hide a HttpContext attribute.
1228         * @param name attribute name.
1229         */

1230        public void removeAttribute(String JavaDoc name)
1231        {
1232            removeContextAttribute(name);
1233        }
1234    
1235        /* ------------------------------------------------------------ */
1236        public String JavaDoc getServletContextName()
1237        {
1238            if (getHttpContext() instanceof WebApplicationContext)
1239                return ((WebApplicationContext)getHttpContext()).getDisplayName();
1240            return null;
1241        }
1242
1243        /* ------------------------------------------------------------ */
1244        public String JavaDoc toString()
1245        {
1246            return "ServletContext["+getHttpContext()+"]";
1247        }
1248    }
1249}
1250
Popular Tags