How to start Felix OSGI container with Java code

In the previous article http://marjavamitjava.com/write-simple-karaf-osgi-bundles-which-interact-with-each-other-in-eclipse-in-10-minutes/ we showed how to create multiple bundles and start/stop them using Karaf. But what if you dont want to use a console like Karaf and want to start/stop felix container as well as bundles using Java code.

Here is how we can achieve the same :

import java.util.HashMap;
import java.util.Map;

import org.apache.felix.framework.Felix;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

public class FelixStart {

	public static void main(String[] args) {

		final Map configMap = new HashMap();
			Felix m_framework = new Felix(configMap);
		try {
			m_framework.init();
			final BundleContext context = m_framework.getBundleContext();

		
			Bundle provider = context.installBundle("file:C:\\Users\\uogra\\eclipse-workspace\\simpleBundleTest\\target\\Bundle1-0.0.1-SNAPSHOT.jar");
			System.out.println("Starting.......");
			provider.start();
			
			//Bundle client = context.installBundle("file:c:/felixDemo2.jar");
			//client.start();
			
			Bundle client = context.installBundle("file:C:\\Users\\uogra\\eclipse-workspace\\simpleBundleTest2\\target\\Bundle2-0.0.1-SNAPSHOT.jar");
			System.out.println("Starting.......");
			client.start();
			
			
			m_framework.start();
			
		} catch (BundleException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				m_framework.stop();
			} catch (BundleException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	}
}

You should be knowing the path of the bundles you would have created. After that we can use APIs present in felix.jar to start felix container as well as those bundles.

You can download felix.jar from https://felix.apache.org/downloads.cgi

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *