getResourceAsStream() fails for binding added from inbox after its discovered

The following fails if the binding is added from the inbox after it was discovered from a static initialization block:

InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("msg_definitions.xml");

If I shut down OH and start it again. It works as expected. Doing some investigation with the following code:

for (ClassLoader c = Thread.currentThread().getContextClassLoader(); c != null; c = c.getParent()) {"{} {}", c.getClass().getName(), c.getResource("msg_definitions.xml"));

It returns the following when added from the inbox:

 org.ops4j.pax.web.service.spi.util.ResourceDelegatingBundleClassLoader null
 org.ops4j.pax.swissbox.core.BundleClassLoader null

And it returns the following when OH is stopped and restarted:

org.eclipse.osgi.internal.framework.ContextFinder bundleresource://235.fwk11729952/msg_definitions.xml
sun.misc.Launcher$AppClassLoader null
sun.misc.Launcher$ExtClassLoader null

I’ve tried multiple ways to get the class loader such as:

new Object().getClass().getClassLoader().getResourceAsStream("msg_definitions.xml");

And I got the same results.

Under osgi context class loader is quite unreliable way of loading resources. You can use org.osgi.freamework.BundleContext to fetch resources. Since you mentioned discovery it is most likely declarative service component where you can inject context directly.

1 Like