View Javadoc

1   package com.atlassian.plugin.osgi.loader;
2   
3   import org.osgi.framework.Bundle;
4   import org.apache.log4j.Logger;
5   import org.apache.commons.collections.iterators.IteratorEnumeration;
6   
7   import java.net.URL;
8   import java.util.Enumeration;
9   import java.util.Arrays;
10  import java.io.IOException;
11  import java.io.InputStream;
12  
13  /**
14   * Utility methods for accessing a bundle as if it was a classloader.
15   */
16  class BundleClassLoaderAccessor
17  {
18      private static final Logger log = Logger.getLogger(BundleClassLoaderAccessor.class);
19  
20      static ClassLoader getClassLoader(Bundle bundle) {
21          return new BundleClassLoader(bundle);
22      }
23  
24      static Class loadClass(Bundle bundle, String name, Class callingClass) throws ClassNotFoundException
25      {
26          return bundle.loadClass(name);
27      }
28  
29      static URL getResource(Bundle bundle, String name)
30      {
31          return bundle.getResource(name);
32      }
33  
34      static InputStream getResourceAsStream(Bundle bundle, String name)
35      {
36          URL url = getResource(bundle, name);
37          if (url != null) {
38              try
39              {
40                  return url.openStream();
41              } catch (IOException e)
42              {
43                  log.debug("Unable to load resource from bundle: "+bundle.getSymbolicName(), e);
44              }
45          }
46  
47          return null;
48      }
49  
50      ///CLOVER:OFF
51      /**
52       * Fake classloader that delegates to a bundle
53       */
54      private static class BundleClassLoader extends ClassLoader
55      {
56          private Bundle bundle;
57  
58          public BundleClassLoader(Bundle bundle)
59          {
60              this.bundle = bundle;
61          }
62  
63          @Override
64          public Class findClass(String name) throws ClassNotFoundException
65          {
66              return bundle.loadClass(name);
67          }
68  
69          @Override
70          public Enumeration<URL> findResources(String name) throws IOException
71          {
72              Enumeration<URL> e = bundle.getResources(name);
73  
74              // For some reason, getResources() sometimes returns nothing, yet getResource() will return one.  This code
75              // handles that strange case
76              if (!e.hasMoreElements()) {
77                  URL resource = findResource(name);
78                  if (resource != null)
79                      e = new IteratorEnumeration(Arrays.asList(resource).iterator());
80              }
81              return e;
82          }
83  
84          @Override
85          public URL findResource(String name)
86          {
87              return bundle.getResource(name);
88          }
89      }
90  
91  
92  }