1 package net.sf.jpkgmk.util;
2
3 import java.net.URL;
4
5 import org.apache.commons.logging.Log;
6 import org.apache.commons.logging.LogFactory;
7
8
9
10
11
12
13
14
15 public class ResourceLoader {
16
17 private static CallerResolver callerResolver = new CallerResolver();
18 private static final int CALL_CONTEXT_OFFSET = 2;
19 private static Log log = LogFactory.getLog(ResourceLoader.class);
20
21
22 public static URL getResource(Class<?> baseClass, String resourceName)
23 {
24 String pkgPath = baseClass.getPackage().getName().replaceAll("\\.", "/");
25 String filePath = "/" + pkgPath + "/" + resourceName;
26 return baseClass.getResource(filePath);
27 }
28
29 public static URL getResource(String resourceName)
30 {
31
32
33 ClassLoader classLoader = callerResolver.getClassContext() [CALL_CONTEXT_OFFSET].getClassLoader();
34 URL resource = classLoader.getResource(resourceName);
35 if(resource == null) {
36 if(resourceName.startsWith("/")) {
37 String relPath = resourceName.substring(1);
38 log.info("Did not find resource at path '" + resourceName + "'. Trying '" + relPath + "'...");
39 resource = classLoader.getResource(relPath);
40 }
41 else {
42 String absPath = "/" + resourceName;
43 log.info("Did not find resource at path '" + resourceName + "'. Trying '" + absPath + "'...");
44 resource = classLoader.getResource(absPath);
45 }
46 }
47
48
49 if(resource == null) {
50 throw new NullPointerException("Did not find resource '" + resourceName + "'");
51 }
52 return resource;
53 }
54
55
56
57
58
59
60
61 private static final class CallerResolver extends SecurityManager
62 {
63 @Override
64 protected Class<?> [] getClassContext()
65 {
66 return super.getClassContext();
67 }
68
69 }
70
71 }