KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > web > ServletContextResourceLoader


1 package jfun.yan.web;
2
3 import java.io.InputStream JavaDoc;
4 import java.net.MalformedURLException JavaDoc;
5 import java.net.URL JavaDoc;
6
7 import javax.servlet.ServletContext JavaDoc;
8
9 import jfun.yan.util.resource.ResourceLoader;
10
11 /**
12  * This class loads resource from either ServletContext (when the url
13  * starts with "/"), or another ResourceLoader.
14  * <p>
15  * @author Ben Yu
16  * Jan 16, 2006 4:42:00 PM
17  */

18 public class ServletContextResourceLoader implements ResourceLoader {
19   private final ServletContext JavaDoc ctxt;
20   private final ResourceLoader loader;
21   private static final String JavaDoc WEB_RESOURCE_PREFIX = "/";
22   public ServletContextResourceLoader(ServletContext JavaDoc ctxt,
23       ResourceLoader loader) {
24     this.loader = loader;
25     this.ctxt = ctxt;
26   }
27
28   public URL JavaDoc getResource(String JavaDoc path) {
29     if(isWebResource(path)){
30       try{
31         return ctxt.getResource(path);
32       }
33       catch(MalformedURLException JavaDoc e){
34         return null;
35       }
36     }
37     else{
38       return loader.getResource(path);
39     }
40   }
41
42   public InputStream JavaDoc getResourceAsStream(String JavaDoc path) {
43     if(isWebResource(path)){
44       return ctxt.getResourceAsStream(path);
45     }
46     else{
47       return loader.getResourceAsStream(path);
48     }
49   }
50   private static boolean isWebResource(String JavaDoc path){
51     return path!=null && path.trim().startsWith(WEB_RESOURCE_PREFIX);
52   }
53   /**
54    * To get the ServletContext object.
55    */

56   public ServletContext JavaDoc getServletContext(){
57     return ctxt;
58   }
59   /**
60    * To get the ResourceLoader object.
61    */

62   public ResourceLoader getResourceLoader(){
63     return loader;
64   }
65
66   public boolean equals(Object JavaDoc obj) {
67     if(obj instanceof ServletContextResourceLoader){
68       final ServletContextResourceLoader other = (ServletContextResourceLoader)obj;
69       return ctxt.equals(other.ctxt) && loader.equals(other.loader);
70     }
71     else return false;
72   }
73
74   public int hashCode() {
75     return ctxt.hashCode()*31+loader.hashCode();
76   }
77
78   public String JavaDoc toString() {
79     return getClass().getName();
80   }
81   
82 }
83
Popular Tags