Recently I ran in to an interesting little problem with “resolution:=optional” OSGi directive. Basically what “resolution:=optional” says is that the even though the package imported with this directive is not present in the system bundle would be resolved at run time. This is logical in case of compile time dependencies of the bundle not being needed at runtime. Or is it?..
I had to ponder a little while before putting down that last statement until I got how it can be so. Usually bundle needs compile time dependencies at run time as well to function correctly. But what if we have an execution path which never gets called at runtime inside our bundle. If that execution path contains imports then these import dependencies will not be needed at run time.
Typically Maven Bundle Plugin is used to incorporate bundle creation at build time. So in this case the general practice I used to follow was to explicitly import obvious dependencies and use a “resolution:=optional” directive with “*” wild card as a catch all mechanism for all other imports. Even if we include some imports which are not needed at runtime we can get away with optional directive since bundle will resolve without them, right?
This is all good and rosy until p2 come in to the picture. Apparently p2 installs bundles exporting optional imports too if it can find them during provisioning. So you end up installing bundles that may not required at runtime along side the feature. Though generally not disastrous this is a concern if you want to keep your feature installation lean.
In my case the issue was some unwanted bundle getting mysteriously installed with my feature even though it’s packages are not explicitly imported in any of bundle’s sources. As it turned out I had included a dependency required for tests without specifying it should be in the test scope. So naturally with “*;resolution:=optional” in place the Bundle Plugin dutifully did it job by placing an import in the manifest which led to this particular bundle installation at provisioning time.
Solution was trivial. Place the dependency in test scope and Bundle Plugin did not include an import since test scoped dependencies will not be imported in the manifest at all. Alternatively I could have explicitly unimported the offending packages or make requires.greedy instruction false at feature p2.inf to stop P2 greedily installing optional dependencies [1] though these solutions are hacky which do not deal with the root cause directly in my case. But it’s always to good to have alternatives isn’t it?. :).
[1] http://ekkescorner.wordpress.com/2010/04/26/p2-is-my-friend-again/