01: // Copyright (c) 2007 Per M.A. Bothner.
02: // This is free software; for terms and warranty disclaimer see ../../COPYING.
03:
04: package gnu.text;
05:
06: import java.io.*;
07: import java.net.*;
08:
09: /** Handler for {@code "class-resource:"} URLs.
10: * These are "indirect URLs" implemented using ClassLoader.getResource().
11: * Their syntax is: either:
12: * {@code class-resource:/PACKAGE/CLASS} or
13: * {@code class-resource:/CLASS} or
14: * {@code class-resource:/PACKAGE/RESOURCE} or
15: * {@code class-resource:/RESOURCE}.
16: * The former two are "base URLs" which need to be resolved.
17: * The latter two are resolved resource names.
18: */
19:
20: public class ResourceStreamHandler extends URLStreamHandler {
21: /** A special URI-scheme for accessing resources relative to a ClassLoader.
22: * The resource is found using ClassLoader's getResource method.
23: * The actual ClassLoader is found using getClassLoaderForURI. */
24: public static final String CLASS_RESOURCE_URI_PREFIX = "class-resource:/";
25:
26: /** The length of CLASS_RESOURCE_URI_PREFIX, including ":/". */
27: public static final int CLASS_RESOURCE_URI_PREFIX_LENGTH = 16;
28:
29: ClassLoader cloader;
30:
31: public ResourceStreamHandler(ClassLoader cloader) {
32: this .cloader = cloader;
33: }
34:
35: public static URL makeURL(Class clas)
36: throws java.net.MalformedURLException {
37: String cname = clas.getName();
38: int dot = cname.lastIndexOf('.');
39: /* #ifdef JAVA5 */
40: // StringBuilder sbuf = new StringBuilder();
41: /* #else */
42: StringBuffer sbuf = new StringBuffer();
43: /* #endif */
44: sbuf.append(CLASS_RESOURCE_URI_PREFIX);
45: if (dot >= 0) {
46: sbuf.append(cname.substring(0, dot));
47: sbuf.append('/');
48: cname = cname.substring(dot + 1);
49: }
50: sbuf.append(cname);
51: String str = sbuf.toString();
52: ClassLoader loader = clas.getClassLoader();
53: return new URL(null, str, new ResourceStreamHandler(loader));
54: }
55:
56: public URLConnection openConnection(URL u) throws IOException {
57: String ustr = u.toString();
58: String rstr = ustr.substring(CLASS_RESOURCE_URI_PREFIX_LENGTH);
59: int sl = rstr.indexOf('/');
60: if (sl > 0)
61: rstr = rstr.substring(0, sl).replace('.', '/')
62: + rstr.substring(sl);
63: URL url = cloader.getResource(rstr);
64: if (url == null)
65: throw new FileNotFoundException(ustr);
66: return url.openConnection();
67: }
68: }
|