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”中,指明了这是一个关于OSGi入门的系列文章中的第一部分。描述部分虽然为“NULL”,但可以从给定的内容中提取出文章的重点信息。标签“源码工具”可能意味着在文章的系列...
"Getting Started with OSGi 5 Consuming a Service.doc"紧接着讲解如何消费这些注册的服务。开发者将学习如何使用服务跟踪器来动态地发现和使用服务,这对于响应服务的添加、修改和移除至关重要。 "Getting ...
在OSGi(Open Service Gateway Initiative)框架中,理解并管理模块间的依赖关系是至关重要的。本篇教程将深入探讨这一主题,帮助开发者们更好地掌握OSGi环境下的程序设计。 一、OSGi概述 OSGi是一种动态模块系统,...
OSGi(Open Services Gateway initiative)是一种Java框架,它定义了服务加载和模块化应用的标准方式。OSGi技术广泛应用于企业级应用开发中,尤其是在Eclipse插件开发和Java EE应用服务器中。OSGi规范定义了如何在...
本资源包括两部分:《深入理解OSGi:Equinox原理、应用与最佳实践》的源代码和equinox-SDK-3.8的源代码。 深入理解OSGi这本书提供了对OSGi,特别是Equinox实现的全面洞察。书中可能涵盖以下几个知识点: 1. **OSGi...
OSGi(Open Service Gateway Initiative)是一种Java模块化系统,它为创建、部署和管理软件组件提供了一种强大而灵活的方式。在Java世界中,OSGi被视为解决大型复杂应用系统中模块化问题的有效解决方案。下面我们将...
标题中的"SpringDM笔记28-Spring And OSGi:Layers of Integration"表明这是一篇关于Spring框架与OSGi(Open Service Gateway Initiative)集成的详细笔记。OSGi是一种模块化系统,它允许Java应用程序以模块化的方式...
《Eclipse RCP与Spring OSGi:技术详解与最佳实践》由资源的Eclipse专家亲自执笔,并得到了Eclipse官方技术社区的强烈推荐,权威性毋庸置疑!内容全面,系统讲解了利用Eclipse RCP和Spring OSGi开发大规模Java应用的...
OSGI原理与最佳实践的完整版,共12章 第1 章OSGi 简介 第2 章OSGi 框架简介 第3 章基于Spring-DM 实现Petstore 第4 章基于Apache CXF 实现分布式Petstore 第5 章构建OSGI Bundle Repositor'y 第6 章OSGi 规范解读 ...
### OSGi Service Platform Service Compendium 知识点解析 #### 一、OSGi Service Platform Service Compendium 概览 **OSGi Service Platform Service Compendium** 是由 **OSGi Alliance** 发布的一份关于 OSGi...
osgi的jar包,第一次上传,有需要的可以自取,联网下载很慢,希望对你们有帮助,偶然间遇到了
OSGi(Open Service Gateway Initiative)是一个Java社区定义的模块化服务平台,它允许在同一个运行环境中部署多个版本的同一个组件,而不会相互冲突,从而提供了一个动态的、模块化的运行时环境。OSGi规范定义了...
带有嵌入式OSGI的Spring Boot 这是一个嵌入了Felix OSGI框架的示例Spring Boot项目。 其他项目是API(接口和模型类)及其实现。 Spring Boot应用程序将这些程序包作为OSGI框架的额外程序包公开(以便能够使用公开的...
教程-osgi OSGI 示例 设置 设置 Git、Ant 和 Maven 查看示例。 $ git clone https://github.com/danidemi/tutorial-osgi.git $ cd tutorial-osgi 只需在项目文件夹中运行ant ,这将指示 Ant 下载一些额外的库。 ...
OSGI(Open Services Gateway Initiative)是一个Java平台的模块化系统,它允许开发人员将应用程序分解为独立的组件,称为服务。这些服务可以独立地安装、更新和卸载,而不会中断整个系统的运行。在OSGI环境中,错误...
标题:开始使用Equinox与OSGi 描述:在Dzone论坛上发现的一个快速入门卡片教程,为初学者提供了一瞥。 知识点: 1. **Equinox简介**:Equinox是一个高度模块化、动态的Java运行环境,基于OSGi框架规范构建。它...