View Javadoc

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   * @author gommma
11   * @author Last changed by: $Author: gommma $
12   * @version $Revision: 3 $ $Date: 2008-08-20 22:22:44 +0200 (Mi, 20 Aug 2008) $
13   * @since 1.0
14   */
15  public class ResourceLoader {
16  
17  	private static CallerResolver callerResolver = new CallerResolver();
18      private static final int CALL_CONTEXT_OFFSET = 2; // may need to change if this class is redesigned
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  //		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
32  //		ClassLoader classLoader = classContext.getClassLoader();
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       * A helper class to get the call context. It subclasses SecurityManager
57       * to make getClassContext() accessible. An instance of CallerResolver
58       * only needs to be created, not installed as an actual security
59       * manager.
60       */
61      private static final class CallerResolver extends SecurityManager
62      {
63          @Override
64  		protected Class<?> [] getClassContext()
65          {
66              return super.getClassContext();
67          }
68          
69      } // End of nested class 
70  	
71  }