OSGi is the dynamic module system for Java. Each module, or bundle as called in OSGi terminology, is packaged as a JAR file and the inbound and outbound dependencies are explicitly defined using the META-INF/MANIFEST.MF in the JAR file. A complex software system may be broken into multiple modules where each module may be exposing a set of services. These services are then consumed by some other "client" OSGi bundles. The beauty of dynamic nature of OSGi is that each bundle can be easily updated without restarting the framework and any reference to the service in the "client" bundles is also updated accordingly. However the client needs to ensure that they are watching out for changes in the lifecycle of "service" bundle.

GlassFish's modular architecture is based upon OSGi. The different capabilities such as Web container, EJB container, and RESTful Web services are provided as OSGi modules. The OSGi framework is available to developers as well so that they can construct their application as OSGi modules and leverage all the goodness.

This Tip Of The Day (TOTD) explains an OSGi design pattern that allows the client to track the dynamic discovery of an OSGi service. This means that client keeps a reference to the service which is automatically refreshed if the bundle providing the service is refreshed. And of course, it uses GlassFish to deploy the bundles :-)

For those, who prefer to see the results directly, download and unzip this zip file:

  1. Give the following command in the root directory: mvn clean install
  2. Copy the generated bundles to "domains/domain1/autodeploy/bundles" directory as:
    cp helloworld-api/target/helloworld-api-1.0-SNAPSHOT.jar \ helloworld-impl/target/helloworld-impl-1.0-SNAPSHOT.jar \ helloworld-client/target/helloworld-client-1.0-SNAPSHOT.jar \ ~/tools/glassfish/v3/final/glassfishv3/glassfish/domains/domain1/autodeploy/bundles
    The following log messages will be displayed in the console:
    [#|2010-04-28T17:03:55.090-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#] [#|2010-04-28T17:03:55.091-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#] [#|2010-04-28T17:03:57.091-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#] [#|2010-04-28T17:03:57.092-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#]
    The log messages from the client bundle invoking the service bundle are highlighted in bold.
  3. Update the service implementation
    1. Edit service implementation in "hello-impl/src/main/java/org/samples/osgi/helloworld/impl/HelloImpl.java" and change the "return" statement from:
      return "Hello " + name; to return "Howdy " + name;
    2. Create the service implementation bundle again by giving the command:
      mvn clean install
      in the "helloworld-impl" directory.
    3. Copy the updated bundle from "helloworld-impl/target/helloworld-impl-1.0-SNAPSHOT.jar" to "glassfishv3/glassfish/domains/domain1/autodeploy/bundles" directory. The following sequence of log messages will be seen:
      [#|2010-04-28T17:04:47.110-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#] [#|2010-04-28T17:04:47.110-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#] [#|2010-04-28T17:04:48.151-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=22;_ThreadName={felix.file install.poll=5000, felix.fileinstall.bundles.new.start=true, service.pid=org.apache.felix.fileinstall.b0b03c1b-5a58-457d-bfde-116be31299f0, felix.fileinstall.dir=/Users/arungupta/tools/glassfish/v3/final/glassfishv3/glassfish/domains/domain1 /autodeploy/bundles/, felix.fileinstall.filename=org.apache.felix.filein stall-autodeploy-bundles.cfg, service.factorypid=org.apache.felix.fileinstall, felix.fileinstall.debug=1};|Updated /Users/arungupta/tools/glassfish/v3/final/glassfishv3/glassfish/domains/domain1/autodeploy/bundles/ helloworld-impl-1.0-SNAPSHOT.jar|#] [#|2010-04-28T17:04:49.110-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#] [#|2010-04-28T17:04:49.111-0700|INFO|glassfishv3.0|javax.enterprise.system.st d.com.sun.enterprise.v3. services.impl|_ThreadID=23;_ThreadName=Thread-23;|Howdy Duke|#]
      As evident from the log messages, "Hello Duke" message is printed first, the service implementation bundle gets refreshed, and then the message from the updated service implementation, i.e. "Howdy Duke" is printed. Notice, only the service implementation got refreshed.
Now some explanation!

The application is split into 3 bundles - API, Impl, and Client. Splitting into 3 bundles allows cleaner separation and other implementations of the service* to show up relying purely upon the API bundle.

The "API" bundle (helloworld-api) has one class with the following interface:

package org.samples.osgi.helloworld.api; public interface Hello { public String sayHello(String name); } This bundle has the following manifest entry:

${pom.groupId}.api
to ensure that the package with the service interface is exported and available for imports by service implementers. The "Impl" bundle (helloworld-impl) has the trivial implementation of this interface as: package org.samples.osgi.helloworld.impl import org.samples.osgi.helloworld.api.Hello; public class HelloImpl implements Hello { public String sayHello(String name) { return "Hello " + name; } } And the bundle's activator registers the service as:

package org.samples.osgi.helloworld.impl; import java.util.Properties; import org.samples.osgi.helloworld.api.Hello; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class App implements BundleActivator { public void start(BundleContext bc) throws Exception { bc.registerService(Hello.class.getName(), new HelloImpl(), new Properties()); } public void stop(BundleContext bc) throws Exception { bc.ungetService(bc.getServiceReference(Hello.class .getName())); } } This bundle defines the dependency on the package exported earlier as:

${pom.groupId} helloworld-api 1.0-SNAPSHOT and also imports the appropriate packages as:

${pom.groupId}.api, org.osgi.framework The "client" bundle's (helloworld-client) activator uses "org.osgi.util.tracker.ServiceTracker" for the dynamic discovery of service. The code looks like:

package org.samples.osgi.helloworld.client; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.samples.osgi.helloworld.api.Hello; public class App implements BundleActivator { BundleContext ctx; public void start(BundleContext context) { this.ctx = context; System.out.println("Starting client bundle"); // Create a service tracker to monitor Hello services. ServiceTracker tracker = new ServiceTracker(context, Hello.class.getName(), null); tracker.open(); new PingService(tracker).start(); } public void stop(BundleContext context) { System.out.println("Stopping client bundle"); } private class PingService extends Thread { ServiceTracker tracker; PingService(ServiceTracker tracker) { this.tracker = tracker; } public void run() { try { while (true) { Thread.sleep(2000); System.out.println("Getting a new service"); Hello hello = (Hello) tracker.getService(); System.out.println(hello.sayHello("Duke")); } } catch (InterruptedException ex) { ex.printStackTrace(); } } } } The ServiceTracker API allows customized service tracking and find services that meet search criteria defined by filters. Basically it listens to different service events and gets/ungets the service accordingly. In this case, a "ServiceTracker" is created to track the service by specifying the class name. The "tracker.open()" starts the service tracking. A new thread is started which pings the service every 2 seconds and prints the received response. Notice, a new service is retrieved from the service tracker as the service bundle might have been refreshed.

Please read through OSGi javadocs for more details on these APIs.

A future blog will show how a Java EE 6 MVC-based application can be split into multiple OSGi bundles using this design pattern.

How are you using dynamic discovery of services in OSGi ?

Technorati: totd osgi modules glassfish v3 felix dynamic discovery



Read More about [TOTD #131: Dynamic OSGi services in GlassFish - Using ServiceTracker...