About Baptiste Wicht

Baptiste Wicht is a swiss computer science student. He's very interested in Java, C++, Assembly, Compiler Theory, ... He also is the developer of the EDDI programming language.

OSGI and Spring Dynamic Modules – Simple Hello World

In this pose st, we’ll take the first implementation we made using OSGi and use Spring Dynamic Modules to improve the application.

Spring Dynamic Modules (Spring Dm) makes the development of OSGi-based applications a lot more easier. With that, the deployment of services is a lot easier. You can inject services like any other Spring beans.

So let’s start with Spring dm.

First of all, you need to download the Spring Dm Distribution. For this article, I used the distributions with dependencies and I will only use this libraries :

com.springsource.net.sf.cglib-2.1.3.jar
com.springsource.org.aopalliance-1.0.0.jar
log4j.osgi-1.2.15-SNAPSHOT.jar
com.springsource.slf4j.api-1.5.0.jar
com.springsource.slf4j.log4j-1.5.0.jar
com.springsource.slf4j.org.apache.commons.logging-1.5.0.jar
org.springframework.aop-2.5.6.SEC01.jar
org.springframework.beans-2.5.6.SEC01.jar
org.springframework.context-2.5.6.SEC01.jar
org.springframework.core-2.5.6.SEC01.jar
spring-osgi-core-1.2.1.jar
spring-osgi-extender-1.2.1.jar
spring-osgi-io-1.2.1.jar

Of course, you can replace the Spring 2.5.6 libraries with the Spring 3.0 libraries. But for this article, Spring 2.5.6 will be enough.

So, start with the service bundle. If we recall, this bundle exported a single service :

package com.bw.osgi.provider.able;
 
public interface HelloWorldService {
    void hello();
}
package com.bw.osgi.provider.impl;
 
import com.bw.osgi.provider.able.HelloWorldService;
 
public class HelloWorldServiceImpl implements HelloWorldService {
    @Override
    public void hello(){
        System.out.println("Hello World !");
    }
}

There is no changes to do here. Now, we can see the activator :

package com.bw.osgi.provider;
 
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
 
import com.bw.osgi.provider.able.HelloWorldService;
import com.bw.osgi.provider.impl.HelloWorldServiceImpl;
 
public class ProviderActivator implements BundleActivator {
    private ServiceRegistration registration;
 
    @Override
    public void start(BundleContext bundleContext) throws Exception {
        registration = bundleContext.registerService(
                HelloWorldService.class.getName(),
                new HelloWorldServiceImpl(),
                null);
    }
 
    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        registration.unregister();
    }
}

So, here, we’ll make simple. Let’s delete this class, this is not useful anymore with Spring Dm.

We’ll let Spring Dm export the bundle for us. We’ll create a Spring context for this bundle. We just have to create a file provider-context.xml in the folder META-INF/spring. This is a simple context in XML file but we use a new namespace to register service, “http://www.springframework.org/schema/osgi“. So let’s start :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="

http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/osgi

            http://www.springframework.org/schema/osgi/spring-osgi.xsd">
 
    <bean id="helloWorldService" class="com.bw.osgi.provider.impl.HelloWorldServiceImpl"/>
 
    <osgi:service ref="helloWorldService" interface="com.bw.osgi.provider.able.HelloWorldService"/>
</beans>

The only thing specific to OSGi is the osgi:service declaration. This line indicates that we register the helloWorldService as an OSGi service using the interface HelloWorldService as the name of the service.

If you put the context file in the META-INF/spring folder, it will be automatically detected by the Spring Extender and an application context will be created.

We can now go to the consumer bundle. In the first phase, we created that consumer :

package com.bw.osgi.consumer;
 
import javax.swing.Timer;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import com.bw.osgi.provider.able.HelloWorldService;
 
public class HelloWorldConsumer implements ActionListener {
    private final HelloWorldService service;
    private final Timer timer;
 
    public HelloWorldConsumer(HelloWorldService service) {
        super();
 
        this.service = service;
 
        timer = new Timer(1000, this);
    }
 
    public void startTimer(){
        timer.start();
    }
 
    public void stopTimer() {
        timer.stop();
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        service.hello();
    }
}

At this time, there is no changes to do here. Instead of the injection with constructor we could have used an @Resource annotation, but this doesn’t work in Spring 2.5.6 and Spring Dm (but works well with Spring 3.0).

And now the activator :

package com.bw.osgi.consumer;
 
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
 
import com.bw.osgi.provider.able.HelloWorldService;
 
public class HelloWorldActivator implements BundleActivator {
    private HelloWorldConsumer consumer;
 
    @Override
    public void start(BundleContext bundleContext) throws Exception {
        ServiceReference reference = bundleContext.getServiceReference(HelloWorldService.class.getName());
 
        consumer = new HelloWorldConsumer((HelloWorldService) bundleContext.getService(reference));
        consumer.startTimer();
    }
 
    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        consumer.stopTimer();
    }
}

The injection is not necessary anymore. We can keep the start of the timer here, but once again, we can use the features of the framework to start and stop the timer. So let’s delete the activator and create an application context to create the consumer and start it automatically and put in the META-INF/spring folder :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:osgi="http://www.springframework.org/schema/osgi"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="

http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/osgi

            http://www.springframework.org/schema/osgi/spring-osgi.xsd">
 
    <bean id="consumer" class="com.bw.osgi.consumer.HelloWorldConsumer" init-method="startTimer" destroy-method="stopTimer"
          lazy-init="false" >
        <constructor-arg ref="eventService"/>
    </bean>
 
    <osgi:reference id="eventService" interface="com.bw.osgi.provider.able.HelloWorldService"/>
</beans>

We used the init-method and destroy-method attributes to start and stop the time with the framework and we use the constructor-arg to inject to reference to the service. The reference to the service is obtained using osgi:reference field and using the interface as a key to the service.

That’s all we have to do with this bundle. A lot more simple than the first version isn’t it ? And more than the simplification, you can see that the sources aren’t depending of either OSGi or Spring Framework, this is plain Java and this is a great advantage.

The Maven POMs are the same than in the first phase except that we can cut the dependency to osgi.

The provider :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>OSGiDmHelloWorldProvider</groupId>
    <artifactId>OSGiDmHelloWorldProvider</artifactId>
    <version>1.0</version>
    <packaging>bundle</packaging>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
 
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>OSGiDmHelloWorldProvider</Bundle-SymbolicName>
                        <Export-Package>com.bw.osgi.provider.able</Export-Package>
                        <Bundle-Vendor>Baptiste Wicht</Bundle-Vendor>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build> 
</project>

The consumer :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>OSGiDmHelloWorldConsumer</groupId>
    <artifactId>OSGiDmHelloWorldConsumer</artifactId>
    <version>1.0</version>
    <packaging>bundle</packaging>
 
    <dependencies>
        <dependency>
            <groupId>OSGiDmHelloWorldProvider</groupId>
            <artifactId>OSGiDmHelloWorldProvider</artifactId>
            <version>1.0</version>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
 
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>OSGiDmHelloWorldConsumer</Bundle-SymbolicName>
                        <Bundle-Vendor>Baptiste Wicht</Bundle-Vendor>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

And we can build the two bundles using maven install. So let’s test our stuff in Felix :

wichtounet@Linux-Desktop:~/Desktop/osgi/felix$ java -jar bin/felix.jar
_______________
Welcome to Apache Felix Gogo

g! install file:../com.springsource.slf4j.org.apache.commons.logging-1.5.0.jar
Bundle ID: 5
g! install file:../com.springsource.slf4j.log4j-1.5.0.jar
Bundle ID: 6
g! install file:../com.springsource.slf4j.api-1.5.0.jar
Bundle ID: 7
g! install file:../log4j.osgi-1.2.15-SNAPSHOT.jar
Bundle ID: 8
g! install file:../com.springsource.net.sf.cglib-2.1.3.jar
Bundle ID: 9
g! install file:../com.springsource.org.aopalliance-1.0.0.jar
Bundle ID: 10
g! install file:../org.springframework.core-2.5.6.SEC01.jar
Bundle ID: 11
g! install file:../org.springframework.context-2.5.6.SEC01.jar
Bundle ID: 12
g! install file:../org.springframework.beans-2.5.6.SEC01.jar
Bundle ID: 13
g! install file:../org.springframework.aop-2.5.6.SEC01.jar
Bundle ID: 14
g! install file:../spring-osgi-extender-1.2.1.jar
Bundle ID: 15
g! install file:../spring-osgi-core-1.2.1.jar
Bundle ID: 16
g! install file:../spring-osgi-io-1.2.1.jar
Bundle ID: 17
g! start 5 7 8 9 10 11 12 13 14 15 16 17
log4j:WARN No appenders could be found for logger (org.springframework.osgi.extender.internal.activator.ContextLoaderListener).
log4j:WARN Please initialize the log4j system properly.
g! install file:../OSGiDmHelloWorldProvider-1.0.jar
Bundle ID: 18
g! install file:../OSGiDmHelloWorldConsumer-1.0.jar
Bundle ID: 19
g! start 18
g! start 19
g! Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
stop 19
g! 

As you can see, it works perfectly !

In conclusion, Spring Dm really makes easier the development with OSGi. With Spring Dm you can also start bundles. It also allows you to make web bundles and to use easily the services of the OSGi compendium.

Here are the sources of the two projects :

Here are directly the two buildeds Jars :

And here are the complete folder including Felix and Spring Dm : osgi-hello-world.tar.gz

Reference: OSGI and Spring Dynamic Modules – Simple Hello World from our JCG partner Baptiste Wicht at @Blog(“Baptiste Wicht”).

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


5 × one =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close