OSGi Hello World with NetBeans 6.9

Since version 6.9, NetBeans offers the possibility to work with OSGi bundles. The creation of the project is relatively simple. You just need to go to new Project > Maven > Maven OSGi Bundle like this :

The generated pom.xml begins this way:

<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/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <groupId>net.stephou.osgi</groupId>
 <artifactId>HelloWorld</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>bundle</packaging>
 <name>OSGiTest OSGi Bundle</name>

 <dependencies>
  <dependency>
   <groupId>org.apache.felix</groupId>
   <artifactId>org.osgi.core</artifactId>
   <version>1.4.0</version>
  </dependency>
 </dependencies>
...

We notice there is only one dependency to the OSGi core and that the packaging is “bundle”. The rest of the pom is the run-on-felix profile configuration for NetBeans.

To display a HelloWorld in Apache Felix console, we need to add a HelloWorld java class. So, right-click on the source package and go to New > Other > OSGI > Bundle Activator like this :

Here is the code for the class after adding something for the console :

package net.stephou.osgi;

import org.osgi.framework.BundleActivator;

import org.osgi.framework.BundleContext;

/**

*

* @author Stephou

*/

public class HelloWorld implements BundleActivator {

   public void start(BundleContext context) throws Exception {

     System.out.println("Hello OSGi World");

   }

   public void stop(BundleContext context) throws Exception { 

     System.out.println("Goodbye OSGi World");

   }
}

In the pom.xml, you can see the Bundle-Activator line has been added for the maven-bundle-plugin :

<plugin>
 <groupId>org.apache.felix</groupId>
 <artifactId>maven-bundle-plugin</artifactId>
 <version>2.0.1</version>
 <extensions>true</extensions>
 <configuration>
 <instructions>
   <Bundle-Activator>net.stephou.osgi.helloworld.HelloWorldActivator</Bundle-Activator>
 </instructions>
 </configuration>
 </plugin>

Just Build and Run your project in NetBeans and you’ll see the following in the console :

Welcome to Felix
================

Hello OSGi World

Congratulation 😉

Advertisements