Search code examples
javaosgi

Put resource on classpath at runtime


I need to create an instance of org.apache.camel.guice.Main in my application. For reasons I don't want to get into, I cannot package a jndi.properties file in my jar/bundle, which will be used by org.apache.camel.guice.Main.run() to bootstrap the app. I also cannot write anything to the file system.

I do have the properties that would normally go into jndi.properties available at runtime as a java object, map of strings, whatver. Can I write these out to a "dynamic" jndi.properties and put it on the classpath (or add it to a classloader as a "resource")? Something like:

this.getClass().putResourceAsStream(properties);

So that 3rd party frameworks that do need to load via getResource() or getResourceAsStream() can do it?


Solution

  • I was able to get this to work by doing 4 things:

    1. Using the constructor in InitialContext that takes java.util.Properties as an argument to create the context
    2. Using a hack in Activator to make sure my application bundle is using bundle context classloader, not the thread context classloader
    3. Use require bundle in addition to package-imports in the header.
    4. Using org.apache.camel.guice.Main.run() to start camel

    Big thanks to Thorbjorn Andersen in the comments, that made me go back and take a closer look at the InitialContext api.