Sérgio Lopes Sakabatō, the reversed blog!

Adding JARs to OSGi bundles, with maven30 Apr 2014

I’ve been developing a middleware system for smart houses (or at least to enable easier sensor node communication) that I chose to make OSGi based. Now, OSGi is nice and all, (rant: I don’t really mind all the 100 pages every book on OSGi has just to market the virtues of OSGi and why it comes to save the world, but it does drive me a bit crazy that there isn’t a set of instructions for those that want to develop using OSGi, not develop an OSGi container, and only need to get the differences to the “non-OSGi way” that we’re already familiar with) but getting a JAR to be part of one of my bundles has been harder than expected.

First, I’m not using Eclipse IDE, so all the tips to use the IDE’s wizards won’t work, second, I know that I only need to add the Bundle-Classpath to the MANIFEST.MF file but I’m using Maven and all my bundles are developed using the OSGi Maven plugin, so I needed to find how to do it with Maven. If you happen to have the same requirements as me you’ll find that it is a very easy task, with one or two caveats.

Maven’s plugin offers an instruction called Embed-Dependency that you need to use to specify the list of JAR files that you want to bundle into the final bundle. So find you’re pom.xml file, add the dependency and take note of the artifactId value. In the OSGi plugin’s instructions section add the Embed-Dependency element with the artifactId for each of the dependencies you want to include.

As an example, including LuaJ:

<dependencies>

    ...

    <dependency>
        <groupId>org.luaj</groupId>
        <artifactId>luaj-jse</artifactId>
        <version>3.0-beta2</version>
    </dependency>

    <dependency>
        <groupId>org.apache.bcel</groupId>
        <artifactId>bcel</artifactId>
        <version>5.2</version>
    </dependency>

    ...

    <configuration>
        <instructions>
            ...
            <Embed-Dependency>luaj-jse,bcel</Embed-Dependency>
        </instructions>
    <configuration>

    ...

</dependencies>

What about the caveat? Notice the bcel entries? That is the result of a dependency declared inside the LuaJ JAR/code that Maven will extract into other sections of the MANIFEST.MF file and, given that the JAR for BCEL (Apache BCEL) is not available in OSGi containers, running the bundle will fail if you don’t add the Apache BCEL JAR as a declared dependency.

So, if the JAR you’re trying to include inside your bundle is completely self-contained you only need to include it as a dependency and then add its artifactId in the Embed-Dependency entry. If your bundle fails to run due to missing dependencies after you add a JAR to it, most likely you need to add extra dependencies to the project and update the Embed-Dependency entry.