KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > resource > ClasspathResourceHandler


1 package org.sapia.resource;
2
3 import java.io.IOException JavaDoc;
4 import java.io.InputStream JavaDoc;
5 import java.net.URL JavaDoc;
6
7 import com.sun.org.apache.xerces.internal.util.URI;
8
9 /**
10  * Handles resources on the classpath.
11  *
12  * <pre>
13  *
14  * ClassPathResourceHandler handler = new ClassPathResourceHandler();
15  * URL url = new URL(handler.getResourceObject(&quot;some/resource/path&quot;).getURI());
16  * ...
17  *
18  * </pre>
19  *
20  * @author Yanick Duchesne
21  */

22 public class ClasspathResourceHandler implements ResourceHandler, Schemes {
23
24   public ClasspathResourceHandler() {
25     super();
26   }
27
28   public Resource getResourceObject(String JavaDoc uri) throws IOException JavaDoc {
29     URI uriObj = null;
30     if(Utils.hasScheme(uri)){
31       uriObj = new URI(uri);
32     }
33     else{
34       uriObj = new URI(Schemes.SCHEME_RESOURCE+":"+uri);
35     }
36     
37     String JavaDoc path = uriObj.getPath();
38
39     if(path.charAt(0) == '/') {
40       path = path.substring(1);
41     }
42
43     URL JavaDoc url = null;
44
45     url = getClass().getClassLoader().getResource(path);
46
47     if(url == null) {
48       url = Thread.currentThread().getContextClassLoader().getResource(path);
49     }
50
51     if(url == null) {
52       url = ClassLoader.getSystemResource(path);
53     }
54
55     if(url == null) {
56       throw new ResourceNotFoundException(path);
57     }
58
59     return new UrlResource(url);
60   }
61
62   public InputStream JavaDoc getResource(String JavaDoc uri) throws IOException JavaDoc {
63     return getResourceObject(uri).getInputStream();
64   }
65
66   public boolean accepts(String JavaDoc uri) {
67     return doAccepts(Utils.getScheme(uri));
68   }
69   
70   public boolean accepts(java.net.URI JavaDoc uri) {
71     return doAccepts(uri.getScheme());
72   }
73   
74   private boolean doAccepts(String JavaDoc scheme){
75     if(scheme == null || scheme.length() == 0 || scheme.equals(SCHEME_RESOURCE)) {
76       return true;
77     }
78     return false;
79   }
80
81 }
82
Popular Tags