Previous Topic

Next Topic

Book Contents

Book Index

Creating a Consumer Service

A document on creating a consumer service.

A consumer service must implement and register the org.osgi.service.wireadmin.Consumer interface. It must have the following list of registration properties:

The updated(Wire, Object) method of the consumer is responsible for actualizing the received data. It is called by the connected wires whenever new data is available. The producersConnected(Wire[]) method updates the list of connected wires if new wires are available, or already known wires are updated/removed.

A consumer service will be able to receive data only if there is at least one connected wire with a producer

The following simple example creates a consumer service ready to accept any data types. Its service PID is consumer.all.

Listing 1. Creating a simple consumer.

                    mport java.util.Hashtable;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.BundleException;
import org.osgi.service.wireadmin.*;

public class ConsumerImpl implements Consumer, BundleActivator {                
  private ServiceRegistration reg;

  public void start(BundleContext bc) throws BundleException {
    Hashtable prop = new Hashtable();
    //this property shows that the consumer will accept any data types
    prop.put(WireConstants.WIREADMIN_CONSUMER_FLAVORS, new Class[] {Object.class});
    //the identifier property of the consumer  
    prop.put("service.pid", "consumer.all");
    //registering the service on the framework
    reg = bc.registerService(Consumer.class.getName(), this, prop);    
  }
  
  public void stop(BundleContext bc) throws BundleException {
    reg.unregister();
  }
  
  /** Watches the list of wires*/
  public void producersConnected(Wire[] wires) {
    if (wires == null) {
      System.out.println("Not connected to any wires");
    } else {
      System.out.println("Connected to " + wires.length + " wires");
    }
  }
  
  /** Receives the new data whenever such are available */
  public void updated(Wire wire, Object value) {
    System.out.println("Updated " + wire + " with value " + value);
  }
  
}