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
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.
- If necessary, switch Perspectives to the Dragonfly perspective.
- Go to File > New > Project
Or, click the New BUG Project icon in the toolbar. - In the New Project wizard, click the arrow to open the Dragonfly node.
- Select BUG Application, then click Next.
- In the New BUG Project window, add these values:
In the Name field, type: Publish example - Click Finish.
- In left-side Project Explorer view, expand the Publish example > publishexample node and double-click on Activator.java to edit it.
- 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());
}
}
}
- Save the Activator.java file.
- Go to File > New > Other ... > Interface
- In the Name field, type ExampleServiceInterface
- Click Finish.
- Replace the generated contents with this:
package publishexample;
public interface ExampleServiceInterface {
public int getSpecialValue();
}
- Save files.
- Click the Launch Virtual BUG icon to run the Virtual BUG.
- 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
