1
2
3
4
5
6
7 package org.backsource.utils.resource;
8
9 import java.net.URL;
10 import java.net.MalformedURLException;
11 /***
12 * <p>An URL factory which translates the URI into a resource available in the classpath.
13 *
14 * <p>This might be registered to lookup URI:s as resources in the classpath. Currently the URI.getPath() is used to get at the resource name.
15 *
16 * <p>Resources is looked up in the current context class loader.
17 *
18 *
19 * @author Peter Antman
20 * @version $Revision: 1.1.1.1 $
21 */
22
23 public class ClassContextURLFactory implements URLFactory {
24
25 public ClassContextURLFactory() {
26
27 }
28 /***
29 * Construct an URL from URI by looking it up in the ContextClassLoader.
30 */
31 public URL getURL(URI uri) throws MalformedURLException {
32
33 String resUri = getResURI(uri);
34 URL url = Thread.currentThread().getContextClassLoader().getResource(resUri);
35 if (url == null)
36 throw new MalformedURLException("Could not find resource: " + resUri);
37 return url;
38 }
39
40 protected String getResURI(URI uri) {
41
42
43
44 String path = uri.getPath();
45 if ( path != null && path.indexOf("/") == 0) {
46 path = path.substring( path.indexOf("/") +1);
47 }
48
49 return path;
50 }
51 }