All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fr.velossity.sample.device.impl.Activator Maven / Gradle / Ivy

There is a newer version: 1.0.14
Show newest version
package fr.velossity.sample.device.impl;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;

import fr.velossity.sample.device.Device;
import fr.velossity.sample.device.DeviceHandler;

/**
 * 
 * @author C. Saint-Marcel
 * 
 */
public class Activator implements BundleActivator, ServiceListener {
	
	/**
	 * Keeps a reference on the bundle context.
	 */
	private BundleContext myContext;
	
	private Device myDevice = new MockDeviceImpl("mock1");

	/**
	 * @see BundleActivator#start(BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		
		myContext = context;

		// Service class name
		String clazz = DeviceHandler.class.getName();

		// Adds itself as a Registry listener for OSGi services
		context.addServiceListener(this, "(" + Constants.OBJECTCLASS + "=" + clazz + ")");
						
		// REQUESTS a service implementing a DeviceHandler service 
		ServiceReference sr[] = context.getAllServiceReferences(clazz, null);
		if(sr != null) {
			
			for (int i = 0; i < sr.length; i++) {
				// BINDS to the service requester
				DeviceHandler myDeviceHandler = (DeviceHandler) context.getService(sr[i]);
				myDeviceHandler.handle(myDevice);
			}		
		} else {
			System.out.println("I found no device listener at that time");
		}

	}

	/**
	 * Notify to all requesters that the device is disappearing.
	 * @see BundleActivator#stop(BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		// Service class name
		String clazz = DeviceHandler.class.getName();

		ServiceReference sr[] = context.getAllServiceReferences(clazz, null);
		if(sr != null) {
			
			for (int i = 0; i < sr.length; i++) {
				// BINDS to the service requester
				DeviceHandler myDeviceHandler = (DeviceHandler) context.getService(sr[i]);
				myDeviceHandler.free(myDevice);
			}		
		}
	}

	/**
	 * NOTIFICATION for device handler services.
	 * OSGi callback to be notified of requesters arrival and departure.
	 * @see ServiceListener#serviceChanged(ServiceEvent)
	 */
	public void serviceChanged(ServiceEvent event) {		
		ServiceReference sr = event.getServiceReference();
		// BINDS to the service provider
		DeviceHandler myDeviceHandler = (DeviceHandler) myContext.getService(sr);

		if(event.getType() == ServiceEvent.REGISTERED) {
			// INVOKES the service
			myDeviceHandler.handle(myDevice);
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy