You are viewing outdated content for BUG. If you have a BUG Y.T. edition or 2.0 series device, please visit our updated wiki: http://wiki.buglabs.net



Create an application that publishes an OSGi service

From BUG Wiki

Jump to: navigation, search

Overview

This page exersizes the OSGi service registry. By creating two OSGi bundles, a producer and a consumer, service creating and binding are demonstrated.

Publisher Bundle

Create basic application for BUG that prints message to system output console.

  1. If necessary, switch Perspectives to the Dragonfly perspective.
  2. Go to File > New > Project
    Or, click the New BUG Project icon in the toolbar.
  3. In the New Project wizard, click the arrow to open the Dragonfly node.
  4. Select BUG Application, then click Next.
  5. In the New BUG Project window, add these values:
    In the Name field, type: Publish example
  6. Click Finish.
  7. In left-side Project Explorer view, expand the Publish example > publishexample node and double-click on Activator.java to edit it.
  8. Replace the displayed code with this code:
package publishexample;

import java.util.Random; 

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

public class Activator implements BundleActivator, ExampleServiceInterface {  

	private ServiceRegistration serviceRegistration;

	public void start(BundleContext context) throws Exception {
		serviceRegistration = context.registerService(ExampleServiceInterface.class.getName(), this, null);
		
		ServiceConsumer consumer = new ServiceConsumer(context);
	} 

	public void stop(BundleContext context) throws Exception {
		serviceRegistration.unregister();
	}

	public int getSpecialValue() {
		Random r = new Random();
		return r.nextInt();
	}
	
	private class ServiceConsumer {

		public ServiceConsumer(BundleContext context) {
			ServiceReference sr = context.getServiceReference(ExampleServiceInterface.class.getName());
			ExampleServiceInterface esi = (ExampleServiceInterface) context.getService(sr);
			
			System.out.println("Example service value: " + esi.getSpecialValue());
		}
		
	}
}
  1. Save the Activator.java file.
  2. Go to File > New > Other ... > Interface
  3. In the Name field, type ExampleServiceInterface
  4. Click Finish.
  5. Replace the generated contents with this:
package publishexample;

public interface ExampleServiceInterface {
	public int getSpecialValue();
}
  1. Save files.
  2. Click the Launch Virtual BUG icon to run the Virtual BUG.
  3. Type services from (: prompt.
    publish_example.ExampleServiceInterface is returned.
  • Example code can be found at svn://bugblade.com/trunk/com.buglabs.usecases/sdk/publish_example