Previous Topic

Next Topic

Book Contents

Book Index

Creating a Producer Service

A document on creating composite a producer service

A producer service must implement and register the org.osgi.service.wireadmin.Producer interface. Its polled(Wire) method should return the data output sent across the wires. The consumersConnected(Wire[]) method actualizes the list of connected wires.

Each producer must be registered with the following properties:

The following example creates a producer for String output. This is indicated by the value of the org.osgi.service.wireadmin.WireConstants.WIREADMIN_PRODUCER_FLAVORS registration property. The service is also registered with the producer.all PID. The only output it sends is a single String. It will be received by consumers connected with wires to this producer.

Listing 1. Creating a simple producer.

import org.osgi.service.wireadmin.*;
import org.osgi.framework.*;
import java.util.Hashtable;


public class ProducerTest implements Producer, BundleActivator {
  private ServiceRegistration reg;
  Object output;
  
  public void start (BundleContext bc) throws BundleException {
    Hashtable props = new Hashtable();
    //the producer will be sending String data (flavors)
    Class[] flavors = new Class[] {String.class};
    props.put(WireConstants.WIREADMIN_PRODUCER_FLAVORS, flavors);
    //the producer PID property
    props.put("service.pid", "producer.all");
    reg = bc.registerService(Producer.class.getName(), this, props);    
  }
  
  public void stop (BundleContext bc) throws BundleException {
    reg.unregister();    
  }
  
  /** If there are connected wires, updates them with the produced values */
  public void consumersConnected(Wire[] wires) {
    if (wires != null) {
      for (int i = 0; i < wires.length; i++) {
        wires[i].update(polled(wires[i]));
      }
    }    
  }

  /** This method is responsible for creating the output */
  public Object polled(Wire wire) {
    String output = "Hello there! This is the producer speaking!";
    return output;    
  }
}