Monday Jan 10, 2011

TOTD #154: Dynamic OSGi services in GlassFish 3.1 - Using CDI and @OSGiService

TOTD #131 explained how dynamic OSGi services can be easily created and deployed in GlassFish. The dynamism comes from the fact that the client keeps a reference to the service which is automatically refreshed if the bundle providing the service is refreshed. That tip used ServiceTracker API for the dynamic discovery of service which still uses some boilerplate code. In Java EE 6 environment, this can be further simplified by using CDI to inject the service and delegate all the service discovery/bind code to a CDI Qualifier available using CDI extensions in GlassFish 3.1.

Siva provides more details in his blog. But basically GlassFish 3.1 comes with a a standard CDI portable extension (org.glassfish.osgi-cdi) that intercepts deployment of hybrid applications that has components who have expressed dependencies on OSGi services. This CDI extension then takes care of discover, bind, inject, and track the service.

With this new CDI extension, the boilerplate code of dynamically tracking the service changes from:

ServiceTracker tracker = new ServiceTracker(context, Hello.class.getName(), null);;
Hello hello = (Hello) tracker.getService();


@Inject @OSGiService(dynamic=true) Hello hello;

No String-based and completely typesafe resolution of an OSGi service in a web application, how neat!

This will work in a "hybrid application" only, and not in pure web application, as BundleContext is required for dynamically tracking the service. Notice that by default the application is not ready to handle the dynamicity of OSGi environment and so "dynamic=true" need to be set explicitly on @OSGiService.

The complete source code for this application is available here. This project consists of 4 Maven modules:

  • helloworld-api
  • helloworld-impl
  • helloworld-client
  • helloworld-cdiclient

The first three modules are explained in detail at TOTD #131. Lets create "helloworld-cdiclient" module!

  1. In the parent directory of TOTD #131 zip file, create a new Maven module as:
    mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=org.samples.osgi.helloworld -DartifactId=helloworld-webclient

    Make sure to change the all the references from "totd131" to "totd154".
  2. The updated directory structure looks like:
    1. "index.jsp" is generated by the Maven archetype
    2. "beans.xml" is a newly added file to enable CDI injection
    3. "" is a newly added file and is used to read the metadata for OSGi hybrid application
    4. "" is a Servlet that invokes the service
  3. The "" file looks like:
    This makes sure that the hybrid application is accessible at "/helloworld-cdiclient" context root.
  4. The updated "pom.xml" looks like:
    <?xml version="1.0" encoding="UTF-8"?>
    <project xsi:schemaLocation=" 
                    <!-- Read all OSGi configuration info from this optional file -->
                    <!-- By default, we don't export anything -->
                    <Export-Package>!\*.impl.\*, \*</Export-Package>
              <plugin> <!-- Need to use this plugin to build war files -->
                <!-- Use version 2.1-beta-1, as it supports the new property failOnMissingWebXml -->
                    <!-- add bundle plugin generated manifest to the war -->
                    <!-- For some reason, adding Bundle-ClassPath in maven-bundle-plugin
                         confuses that plugin and it generates wrong Import-Package, etc.
                         So, we generate it here.
                  <!-- We don't have a web.xml -->

    Screencast #32 provide a detailed explanation of this "pom.xml". A basic introduction to "hybrid applications" is given here.
  5. The updated "" looks like:
    package org.samples.osgi.helloworld;
    import javax.inject.Inject;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.glassfish.osgicdi.OSGiService;
    import org.samples.osgi.helloworld.api.Hello;
     \* Hello world!
    @WebServlet(urlPatterns = {"/HelloWebClient"})
    public class App extends HttpServlet {
        @Inject @OSGiService(dynamic=true) Hello hello;
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            PrintWriter out = response.getWriter();

    This is a "web.xml"-free servlet using @WebServlet. "@OSGiService" is used to dynamically discover, bind, inject, and track the service. So if the backend service changes then the service reference is automatically updated without any additional effort.
  6. Build and Deploy this project as:
    mvn clean install
    asadmin deploy --type=osgi  target/helloworld-cdiclient-1.0-SNAPSHOT.war
    Optionally you can also drop this generated WAR file to "glassfish/domains/domain1/autodeploy/bundles" directory as well.
  7. Run the app
    1. Make sure helloworld-api-\* and helloworld-impl-\* bundles are already deployed as explained in TOTD #131.
    2. Invoking "curl http://localhost:8080/helloworld-cdiclient/HelloWebClient" shows the result as "Hello Duke".
    3. Change "org.samples.osgi.helloworld.impl.HelloImpl" to use "Howdy" string instead of "Hello", build the bundle again (mvn clean install), and copy it to the "glassfish/domains/domain1/autodeploy/bundles" directory.
    4. Invoking "curl http://localhost:8080/helloworld-cdiclient/HelloWebClient" now shows the result as "Howdy Duke". This ensures that the service changes are dynamically tracked.

I tried this with GlassFish 3.1 build 35 Web Profile.

Read the latest about GlassFish and OSGi integration on this wiki.

Where are you deploying your OSGi applications ?

Technorati: totd osgi javaee6 glassfish dynamic discovery

Wednesday Apr 28, 2010

TOTD #131: Dynamic OSGi services in GlassFish - Using ServiceTracker

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 \\

    The following log messages will be displayed in the console:
    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#]
    services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
    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/" and change the "return" statement from:
      return "Hello " + name;
      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:
      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Hello Duke|#]
      /autodeploy/bundles/, felix.fileinstall.filename=org.apache.felix.fileinstall-autodeploy-bundles.cfg, 
      service.factorypid=org.apache.felix.fileinstall, felix.fileinstall.debug=1};|Updated 
      services.impl|_ThreadID=23;_ThreadName=Thread-23;|Getting a new service|#]
      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:


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 {

This bundle defines the dependency on the package exported earlier as:


and also imports the appropriate packages as:

<Import-Package>${pom.groupId}.api, org.osgi.framework</Import-Package>

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;
    ServiceTracker tracker;

    public void start(BundleContext context) {
        System.out.println("Starting client bundle");

        this.ctx = context;        

        // Create a service tracker to monitor Hello services.
        tracker = new ServiceTracker(context, Hello.class.getName(), null);;

        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) {
                    System.out.println("Getting a new service");
                    Hello hello = (Hello) tracker.getService();
                    if (hello == null)
                        System.out.println("No service found!"); 
            } catch (InterruptedException ex) {

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 "" 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


profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.

Java EE 7 Samples

Stay Connected


« July 2016