`
classtwo5367
  • 浏览: 37505 次
  • 性别: Icon_minigender_1
  • 来自: Cork
最近访客 更多访客>>
社区版块
存档分类
最新评论

Getting Started with OSGi: Consuming a Service

阅读更多
In our last part we looked at how to register a service. Now we need to work out how to lookup and use that service from another bundle.

We will put the problem in the context of our requirements, which as before are inspired by Martin Fowler's paper on dependency injection. We have built a MovieFinder as a service and registered it with the service registry. Now we want to build a MovieLister that uses the MovieFinder to search for movies directed by a specific director. Our assumption is that the MovieLister itself will be a service to be consumed by some other bundle, e.g. a GUI application. The trouble is, OSGi services are dynamic... they come and they go. That means sometimes we want to call the MovieFinder service but it just isn't available!

So, what should the MovieLister do if the MovieFinder service is not present? Clearly the call to the MovieFinder is a critical part of the work done by MovieLister , so there only a few choices available to us:

   1. Produce an error, e.g. return null or throw an exception.
   2. Wait.
   3. Don't be there in the first place.


In this article we're going to look at the first two options, as they are quite simple. The third option may not even make any sense to you yet, but hopefully it will after we look at some of the implications of the first two.

The first thing we need to do is define the interface for the MovieLister service. Copy the following into osgitut/movies/MovieLister.java :
package osgitut.movies;
 
import java.util.List;
 
public interface MovieLister {
    List listByDirector(String name);
}


Now create the file osgitut/movies/impl/MovieListerImpl.java :
package osgitut.movies.impl;
 
import java.util.*;
import osgitut.movies.*;
import org.osgi.framework.*;
import org.osgi.util.tracker.ServiceTracker;
 
public class MovieListerImpl implements MovieLister {
    private final ServiceTracker finderTrack;
 
    public MovieListerImpl(ServiceTracker finderTrack) {
        this.finderTrack = finderTrack;
    }
 
    public List listByDirector(String name) {
        MovieFinder finder = (MovieFinder) finderTrack.getService();
        if(finder == null) {
            return null;
        } else {
            return doSearch(name, finder);
        }
    }
 
    private List doSearch(String name, MovieFinder finder) {
        Movie[] movies = finder.findAll();
        List result = new LinkedList();
        for (int i = 0; i < movies.length; i++) {
            if(movies[i].getDirector().indexOf(name) > -1) {
                result.add(movies[i]);
            }
        }
 
        return result;
    }
}



This is probably our longest code sample so far! So what's going on here? Firstly you notice that the logic of actually searching for movies is separated into a doSearch(String,MovieFinder) method, to help us isolate the OSGi-specific code. Incidentally, the way we're performing the search is pretty stupid and inefficient, but that's not really important for the purposes of the tutorial. We only have two movies in our database anyway!

The interesting part is in the listByDirector(String name) method, which uses a ServiceTracker object to obtain a MovieFinder from the service registry. ServiceTracker is a very useful class which abstracts away a lot of unpleasant detail in the lowest levels of the OSGi API. However we still have to check whether the service was actually present. We assume that the ServiceTracker will be passed to us in our constructor.

Note that you may have seen elsewhere code that retrieves a service from the registry without using ServiceTracker . For example, it is possible to use the getServiceReference and getService calls on BundleContext . However the code you have to write is quite complex and it has to be careful to clear up after itself. In my opinion, there is very little benefit in dropping down to the low level API, and lots of problems with it. It's better to use ServiceTracker almost exclusively.

A good place to create a ServiceTracker is in the bundle activator. Copy this code into osgitut/movies/impl/MovieListerActivator.java :
package osgitut.movies.impl;
 
import java.util.*;
import org.osgi.framework.*;
import org.osgi.util.tracker.ServiceTracker;
import osgitut.movies.*;
 
public class MovieListerActivator implements BundleActivator {
 
    private ServiceTracker finderTracker;
    private ServiceRegistration listerReg;
 
    public void start(BundleContext context) throws Exception {
        // Create and open the MovieFinder ServiceTracker
        finderTracker = new ServiceTracker(context, MovieFinder.class.getName(), null);
        finderTracker.open();
 
        // Create the MovieLister and register as a service
        MovieLister lister = new MovieListerImpl(finderTracker);
        listerReg = context.registerService(MovieLister.class.getName(), lister, null);
 
        // Execute the sample search
        doSampleSearch(lister);
    }
 
    public void stop(BundleContext context) throws Exception {
        // Unregister the MovieLister service
        listerReg.unregister();
        
        // Close the MovieFinder ServiceTracker
        finderTracker.close();
    }
 
    private void doSampleSearch(MovieLister lister) {
        List movies = lister.listByDirector("Miyazaki");
        if(movies == null) {
            System.err.println("Could not retrieve movie list");
        } else {
            for (Iterator it = movies.iterator(); it.hasNext();) {
                Movie movie = (Movie) it.next();
                System.out.println("Title: " + movie.getTitle());
            }
        }
    }
}



Now this activator is starting to look interesting. Firstly in the start method it creates a ServiceTracker object, which is used by the MovieLister we just wrote. It then "opens" the ServiceTracker which tells it to start tracking instances of the MovieFinder service in the registry. Then it creates our MovieListerImpl object and registers it in the service registry under the interface name "MovieLister" . Finally, just for the sake of being able to see something interesting when we start the bundle, the activator runs a simple search against the MovieLister and prints the result.

We need to build and install this bundle. I'm not going to give full instructions this time -- you should be able to refer back to the previous installments and work it out. Remember you also need to create a manifest file, and it has to refer to the osgitut.movies.impl.MovieListerActivator class as its Bundle-Activator . Also your Import-Package line needs to include the three packages that we're importing from other bundles, namely org.osgi.framework , org.osgi.util.tracker and osgitut.movies .

Once you have installed MovieLister.jar into the Equinox runtime, you can start it. At that point you will see one of two messages, depending on whether the BasicMovieFinder bundle is still running from last time. If it's not running you will see:

osgi> start 2
Could not retrieve movie list


However if it is running you will see following:

osgi> start 2
Title: Spirited Away


By stopping and starting each bundle, you should be able to get either message to appear at will. And that is almost all for this installment, except remember I said that one of the things you can do when a service is not available is to wait for it? With the code we already have, this is actually trivial: simply change line 16 of MovieListerImpl to call waitForService(5000) on the ServiceTracker instead of getService() , and add a try/catch block for the InterruptedException .

This will cause the listByDirector() method to hang for up to 5000 milliseconds waiting for the MovieFinder service to appear. If a MovieFinder service is installed in that time -- or, of course, if it was already there -- then we will immediately get it an be able to use it.

Generally though I would advise against suspending threads like this. Particularly in this case, it could be dangerous because the listByDirector() method is actually called from the start method of our bundle activator, which was called from a framework thread. Activators are meant to return quickly, because a number of other things need to happen when a bundle is activated. In fact in the worst case we could cause a deadlock, because we are effectively entering a synchronized block on an object owned by the framework, which might already by locked by something else. The general guideline is never perform any long-running or blocking operations in a bundle activator start method, or in any code called directly from the framework.

In the next installment we will take a look at the mysterious third option for dealing with absent dependencies: "Don't exist in the first place". Stay tuned!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics