2
edits
Changes
no edit summary
----------
<h4>3. Define the Bundle Service Consumer</h4>
The service ''bookfinder'' could be used only if there is a bundle that requests its service. The bundle ''cs.ecl.osgi.simple.bookfindconsumer'' by the time is activated ''BundleActivator'' looks for the service in the registry. This bundle will be called 'service consumer'.
<h5>3.1 Define the Activator class for the service consumer</h5>
<source lang="java">
package cs.ecl.osgi.simple.bookfinderconsumer.bookfinderconsumer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import cs.ecl.osgi.simple.bookfinder.BookFinder;
import cs.ecl.osgi.simple.bookfinder.BookNotFoundException;
public class Activator implements BundleActivator {
private static BundleContext context;
private BookFinder finderService;
static BundleContext getContext() {
return context;
}
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
ServiceReference reference = context
.getServiceReference(BookFinder.class.getName());
if (reference != null) {
finderService = (BookFinder) context.getService(reference);
if (finderService != null) {
printBook(finderService);
context.ungetService(reference);
} else
System.err.println("the service cannot be used !!!");
} else
System.err.println("the service cannot be found !!!");
}
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
System.err.println("consumer bundle stopped");
}
public void printBook(BookFinder finderService) {
try {
String s = finderService.findBook(1234).getTitle();
System.out.print("Book found: " + s + " !!!");
} catch (BookNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
}
</source>