fr.velossity.sample.device.impl.Consumer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ConsumerAP Show documentation
Show all versions of ConsumerAP Show documentation
Sample of consumer looking for a producer and getting new measures
The newest version!
package fr.velossity.sample.device.impl;
import java.util.Collection;
import java.util.Iterator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import fr.velossity.sample.device.Device;
import fr.velossity.sample.device.Measurement;
/**
* A simple consumer displaying a device measurements.
* @author C. Saint-Marcel
*
*/
public class Consumer implements Runnable {
/**
* Thread.
*/
private Thread measureGetter;
/**
* The bundle context.
*/
private BundleContext myContext;
/**
*/
public void activate(BundleContext context) throws Exception {
myContext = context;
if(measureGetter == null) {
measureGetter = new Thread(this);
measureGetter.start();
}
}
/**
*/
public void deactivate(BundleContext context) throws Exception {
measureGetter = null;
}
/**
* @see Runnable#run()
*/
public void run() {
Thread mg = measureGetter;
while (measureGetter == mg) {
try {
// REQUESTS Device with name "producer1"
Collection> sr = myContext.getServiceReferences(Device.class, "(identifier=producer1*)");
if (sr != null) {
Iterator> it = sr.iterator();
if (it.hasNext()) {
// BINDS to the device
Device myDevice = myContext.getService(it.next());
// INVOKES the service
newMeasure(myDevice.getLastMeasure());
}
}
} catch (InvalidSyntaxException e) {
e.printStackTrace();
}
try {
synchronized (this) {
wait(10000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Just echoing the measurement to the console.
*/
private void newMeasure(final Measurement measurement) {
if(measurement != null) { // It can be null if the Producer service is declared before setting the measurement
System.out.println("New measure [" + measurement.getSource().getIdentifier() + "]= " + measurement.getValue() + " " + measurement.getUnit());
}
}
}