Search code examples
javatomcateclipse-pluginosgiequinox

Using an OSGi Bundle from a Java Web Application in Tomcat


I am trying to invoke a method of an OSGi bundle from a Java Web Application. Both are supposed to run on Tomcat 7.

I already wrote a normal Java application that invokes methods from the OSGi bundle, as described on this site: http://drupal.osgibook.org/node/37.

To get the context of the Equinox environment I started it from the application and installed the bundles from within. Furthermore the context was used to retrieve a service reference of the running bundle and getting its service.

The runEquinox method of the EquinoxRunner class:

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

public BundleContext runEquinox([...]) throws Exception {
    [...]

    BundleContext bundleContext = EclipseStarter.startup(new String[]{"-console"}, null);
    bundleContext.installBundle("file:C:/.../plugins/myosgiclass.interface_1.0.0.201108301327.jar");
    Bundle bundleTranslationImpl =  bundleContext.installBundle("file:C:/.../plugins/myosgiclass.impl_1.0.0.201108301327.jar");
    bundleTranslationImpl.start();

    [...]
    return bundleContext;
}

and the invokeMethod of the ServiceRunner class:

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

[...]

public Object invokeMethod(BundleContext bundleContext, Object value, [...]){
    ServiceReference serviceReference = bundleContext.getServiceReference(MyOSGiClass.class.getName());
    Object result = null;
    if (serviceReference != null) {
        MyOSGiClass myOSGiClass = (MyOSGiClass) bundleContext.getService(serviceReference);
        if (myOSGiClass != null) result = myOSGiClass.method(value);
        bundleContext.ungetService(serviceReference);
    }
    return result;
}

Now, on Tomcat using the eclipse bridge, I don't know how to retrieve the right context of the Equinox environment. When I try running it on Tomcat with Equinox I get NoClassDefFound Exceptions. I would appreciate any advice on how to solve this problem.

Thanks a lot in advance. Cheers, Nic


Solution

  • When you embeds an OSGi framework like that and then want to access an OSGi service from the outer environment, you need to be sure that the service interface are the same inside and outside of OSGi.

    So, configure your OSGi container to export the package of your service interface from Tomcat to OSGi. To achieve this, configure your OSGi framework with the 'FRAMEWORK_SYSTEMPACKAGES_EXTRA' property.

    More info on http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html#ApacheFelixFrameworkLaunchingandEmbedding-hostservices (even if it's for Apache Felix, the embedding API is standardized).