`
classtwo5367
  • 浏览: 38709 次
  • 性别: 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!
分享到:
评论

相关推荐

    Getting Started with OSGi_ Part1

    在标题“Getting Started with OSGi Part1”中,指明了这是一个关于OSGi入门的系列文章中的第一部分。描述部分虽然为“NULL”,但可以从给定的内容中提取出文章的重点信息。标签“源码工具”可能意味着在文章的系列...

    OSGi Technology 教程

    "Getting Started with OSGi 5 Consuming a Service.doc"紧接着讲解如何消费这些注册的服务。开发者将学习如何使用服务跟踪器来动态地发现和使用服务,这对于响应服务的添加、修改和移除至关重要。 "Getting ...

    深入理解OSGi:Equinox原理、应用与最佳实践.pdf

    OSGi(Open Service Gateway Initiative)是一个定义了Java应用程序如何组织和模块化以及如何动态发现、启动、停止、更新这些模块化组件的规范。Equinox是OSGi规范的一个实现,它是由Eclipse基金会开发的。本文将...

    Getting Started with OSGi_ Part3

    在OSGi(Open Service Gateway Initiative)框架中,理解并管理模块间的依赖关系是至关重要的。本篇教程将深入探讨这一主题,帮助开发者们更好地掌握OSGi环境下的程序设计。 一、OSGi概述 OSGi是一种动态模块系统,...

    Getting Started with OSGi_ Part2

    OSGi(Open Services Gateway initiative)是一种Java框架,它定义了服务加载和模块化应用的标准方式。OSGi技术广泛应用于企业级应用开发中,尤其是在Eclipse插件开发和Java EE应用服务器中。OSGi规范定义了如何在...

    深入理解OSGi:Equinox原理、应用与最佳实践源代码+equinox-SDK-3.8源代码

    本资源包括两部分:《深入理解OSGi:Equinox原理、应用与最佳实践》的源代码和equinox-SDK-3.8的源代码。 深入理解OSGi这本书提供了对OSGi,特别是Equinox实现的全面洞察。书中可能涵盖以下几个知识点: 1. **OSGi...

    深入理解OSGi:Equinox原理、应用与最佳实践

    ### 深入理解OSGi:Equinox原理、应用与最佳实践 #### OSGi概述 OSGi(Open Service Gateway Initiative)是一种模块化系统和服务组件模型,它为Java平台提供了一种动态部署、管理和更新应用程序和服务的方法。...

    《深入理解OSGi:Equinox原理、应用与最佳实践》

    《深入理解OSGi:Equinox原理、应用与最佳实践》自从1999年OSGi联盟成立以来,OSGi技术随着Java一起飞速发展,它已经成为一种被广泛认可的软件架构技术和方法,许多世界著名的IT企业都加入到OSGi的阵营之中,OSGi...

    OSGi_Service

    OSGi(Open Service Gateway Initiative)是一种Java模块化系统,它为创建、部署和管理软件组件提供了一种强大而灵活的方式。在Java世界中,OSGi被视为解决大型复杂应用系统中模块化问题的有效解决方案。下面我们将...

    深入理解OSGi:Equinox原理、应用与最佳实践,书本源代码

    在深入理解OSGi:Equinox原理、应用与最佳实践中,我们可以学习到以下几个关键知识点: 1. **模块化编程**:OSGi的核心是模块化,它将应用程序划分为独立的单元,称为服务或bundle。每个bundle都有自己的类路径,...

    深入理解OSGi:Equinox原理、应用与最佳实践.zip

    在《深入理解OSGi:Equinox原理、应用与最佳实践》这本书中,作者深入探讨了OSGi的核心概念、Equinox的工作原理以及如何在实际项目中应用OSGi。这本书的源码可能是为了辅助读者理解和实践书中所讲解的内容。 **OSGi...

    《深入理解OSGi:Equinox原理、应用与最佳实践》迷你书

    本书《深入理解OSGi:Equinox原理、应用与最佳实践》深入剖析了OSGi技术的原理和应用,着重介绍了基于OSGi R5.0规范的内容,并结合了Equinox框架的实践经验,旨在帮助读者更好地理解和应用OSGi技术。 本书共分为四...

    《深入理解OSGi:Equinox原理、应用与最佳实践》附赠光盘

    《深入理解OSGi:Equinox原理、应用与最佳实践》这本书是关于OSGi技术的一部权威著作,其附赠光盘包含丰富的学习资源,旨在帮助读者深入掌握OSGi的精髓,特别是Equinox实现的细节。OSGi(Open Services Gateway ...

    SpringDM笔记28-Spring And OSGi:Layers of Integration

    标题中的"SpringDM笔记28-Spring And OSGi:Layers of Integration"表明这是一篇关于Spring框架与OSGi(Open Service Gateway Initiative)集成的详细笔记。OSGi是一种模块化系统,它允许Java应用程序以模块化的方式...

    Eclipse RCP与Spring OSGi技术详解与最佳实践

    《Eclipse RCP与Spring OSGi:技术详解与最佳实践》由资源的Eclipse专家亲自执笔,并得到了Eclipse官方技术社区的强烈推荐,权威性毋庸置疑!内容全面,系统讲解了利用Eclipse RCP和Spring OSGi开发大规模Java应用的...

    OSGi Service Platform Service Compendium

    ### OSGi Service Platform Service Compendium 知识点解析 #### 一、OSGi Service Platform Service Compendium 概览 **OSGi Service Platform Service Compendium** 是由 **OSGi Alliance** 发布的一份关于 OSGi...

    深入理解OSGi:Equinox原理、应用与最佳实践.mobi

    全面解读OSGi规范,深刻揭示OSGi原理,详细讲解OSGi服务,系统地介绍Equinox框架的用法,并通过源代码分析其工作机制,包含大量可操作性极强的解决方案和最佳实践。

Global site tag (gtag.js) - Google Analytics