Introduction To Osgi Working in Osgi Environment: Valentin Valchev

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Introduction to OSGi Working in OSGi Environment

Valentin Valchev June 9, 2001

Contents
1 Introduction 1.1 The Connected Home . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 The OSGi Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 OSGi Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Bundles 2.1 What is a Bundle . . . . . . . 2.2 Bundle Manifests . . . . . . . 2.3 Writing Bundles . . . . . . . . 2.4 What is Bundle Lifecycle . . . 2.5 A Bundle without an Activator 3 Services 3.1 What is a Service . . . . . . . 3.2 Bundles and Services . . . . . 3.3 Core OSGi Services . . . . . . 3.3.1 Device Access Service 3.3.2 HTTP Service . . . . . 3.3.3 Log Service . . . . . . 3.4 Using Services . . . . . . . . 3.5 Service Properties . . . . . . . 3.6 LDAP Filters . . . . . . . . . 3.7 Service Events and Listeners . 3.8 Using Service Tracker . . . . 4 Conclusion 2 2 2 2 4 4 4 5 6 7 9 9 9 9 9 9 10 10 12 16 18 20 22

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

1 INTRODUCTION

1 Introduction
1.1 The Connected Home
A long time ago, the computer was created to help scientists do their mathematical calculations. Years later, the computer became a tool for personal usage - we can use electronic spread sheets, we can write letters using powerful word processors, play games at home, etc. Computers are going more and more powerful each day. There are board computers in airplanes, trucks, cars, there are computers even at home. Along with progressive manufacturers offering complete home automation suite, it would be nice if we could connect these devices with our personal computer. Wouldnt it be nice to control some of your household chores by just sending a simple message through Internet. Wouldnt you feel more comfortable if you leave home knowing that everything is safe because you can control your home anytime and from anywhere. Besides home control, you can enjoy network-based services that are delivered to you by service providers and you can enjoy benets like watching your favorite movie on request, pay your phone bill while watching television and this without any particular knowledge of the whole system because your service provider does everything about maintenance instead of you.

1.2 The OSGi Model


Now imagine a home gateway - a small, integrated device that links networked devices and it is the key to the connected home. It requires minimum or no upkeep by the homeowner. It doesnt need a specic hardware platform, adding just a small piece of software transforms any broadband termination device into a home gateway. Most importantly to the consumer, all the services of the home gateway can be managed by external service providers. Just like cable or phone services, home gateway services are there when they are needed the consumer doesnt need to understand anything about how or why they work, just what they do. For a service provider to deliver cost and management effective services to end user in March 1999 was formed public organization called OSGi. It has been working to dene and promote open specications for the delivery of multiple services over widearea networks to local networks and devices. The OSGi specication denes an open framework that enables multiple software services to be loaded and run on a services gateway such as a set top box, cable modem, DSL modem, PC or dedicated residential gateway. It provides core platform for management, control and delivery of services over network connection. The OSGi organization does not provide end-user software but open industry standard for developing efcient home networking environment and services. For more information you should look at OSGi Whitepaper

1.3 OSGi Basics


In brief, the OSGi standard denes an execution platform for residential gateways (called frameworks) and some core services like logging facility, http service, service for device access, central conguration storage, etc. Along with core services there exist many vendor services specic for a particular device, network or such that satisfy user requirements.

1 INTRODUCTION

1.3 OSGi Basics

The OSGi specication allows easy maintenance of device and services, dynamic update of device drivers, easy delivery of various services, remote control and last but not least - security. Besides these very important features, as OSGi species that all software is written in Java, this makes it portable across various platforms and code written for one gateway will run without any modication on another one. The OSGi framework is the heart of the residential gateway. Each other piece of code is called bundle and it can be dynamically delivered to framework. Old Software can be easily replaced and that which is not anymore necessary can be also such easily uninstalled. Bundles themselves communicate with each other through services. The OSGi model has advanced API for retrieving and using services. Service repository enables developers to reuse common code without rewriting it and increasing software footprint and memory requirements.

2 BUNDLES

2 Bundles
This section describes what a bundle is, how a bundle is dened and how to write bundles. The chapters below are written for beginners but they presume that the reader has already downloaded the OSGi specication. If you dont have it, please download it from www.osgi.org and take a look at it before reading the following chapters. Dont worry if you initially dont understand anything - this tutorial will help you to understand it - but the specication is still required just for reference.

2.1 What is a Bundle


A bundle is a package archive containing software written for the OSGi framework, deployed as a JAR le. It represents a functional component that can be installed, activated, deactivated and uninstalled. The operations that can be performed over a bundle form its so called lifecycle . Bundles can share Java classes. They can import/export packages available from/to other bundles. They can also provide services and register them to the frameworks service repository. Apart from Java classes, bundles may contain resources like images, data les and native libraries. The OSGi model has advanced methods for installing the proper native libraries for the platform on which the framework is running. Just like any application that has a main method in its starting class, which is invoked by the Java Virtual Machine, each bundle has its main class called activator with some methods that are invoked by the OSGi framework. How the framework determines which is the activator object is explained in the next section.

2.2 Bundle Manifests


As you already know, bundles are packed in jar les. These jar les contain an important le called Manifest.mf residing in the META-INF directory. This le contains entries describing certain parameters of the bundles packages. Here are all predened entries that a bundles jar may have:

Bundle-ClassPath is an optional header for bundles that use their own resources. A typical bundle that uses this header is bundle - wrapper for another vendors packages. Bundle-NativeCode is a required header for bundles that exploit native code. This header is read by the bundle loader class and the described libraries are extracted from the bundles jar le and loaded by the Java Virtual Machine. Import-Package is used by bundles that use resources from other bundles. Imported packages must be exported by another bundle rst. If an imported package cannot be found, the bundle cannot be used. Export-Package is used by bundles that expose resources/packages to other bundles in the framework. Bundle-Activator contains the main activator class name which should be loaded by the bundle loader.

2 BUNDLES

2.3 Writing Bundles

Bundle-Name is a mandatory eld. This is the user friendly name of this bundle. Bundle-Description is a optional eld containing additional, more comprehensive description of the bundle and its purpose. Bundle-Version is an optional eld containing bundle version number. Bundle-Vendor is an optional eld that contains the bundle vendors name. Bundle-DocURL is an optional parameter containing the url where could nd more information about this bundle. Bundle-ContactAddress is an optional parameter containing additional information about how to receive support with this bundle. Bundle-UpdateLocation is a deprecated eld that must not be used.
And here is a simple manifest content:
Manifest-Version: 1.0 Bundle-Vendor: ProSyst Bundle-Version: 4.1.0 Bundle-ClassPath: ., servlet.jar Bundle-Category: OSGi Bundle-Activator: com.prosyst.mbs.impl.services.http.HttpActivator Bundle-Name: Http Bundle Export-Package: org.osgi.service.http, javax.servlet, javax.servlet.http Bundle-Description: The HTTP Bundle hosts an integrated HTTP server and Servlet 2.2 Engine that allow access to server and bundle resources over HTTP 1.1. Import-Package: org.osgi.service.cm

Although the manifest le is very important, there is nothing as important as the source code. In the next chapter you will learn how to write simple bundles.

2.3 Writing Bundles


We have already learnt something about bundles. Now we will try to create a simple bundle. Remember that the source below is available outside the document in the sources directory. The rst interface from the OSGi specication well meet is BundleActivator. Now open your copy of the specication, locate the documentation for that interface and study it carefully. Now that you read the JavaDoc, we can proceed further. You already know that a bundle is started by invoking the start method of its activator object. and when a bundle is stopped, the stop method is called. So lets go now and create our rst Hello World bundle. Here is the code for it:

2 BUNDLES

2.4 What is Bundle Lifecycle

package tutorial.bundles.hello; import org.osgi.framework.; public class HelloActivator implements BundleActivator public void start(BundleContext bc) throws BundleException System.out.println("Hello World started");

public void stop(BundleContext bc) throws BundleException System.out.println("Hello World stopped");

Having the source code, we are ready to compile it. You should have at least the interfaces dened by OSGi to compile this example. When the source is compiled, we have to create a manifest le for our bundle. Here are the manifests contents:

Bundle-Version: 1.0.0 Bundle-Name: Hello Bundle-Description: The Hello World bundle. Bundle-Activator: tutorial.bundles.hello.HelloActivator

Having both compiled classes and written the manifest le, we can create the bundle - just pack the classes in a jar le not forgetting to add the right manifest le. The JAR le youve just created is our hello world bundle. Now you can install it on an OSGi framework and start it. You will see the Hello World started message. This bundle is the simplest we can create. More advanced topics about bundles are covered by the following sections. The next chapter will be your guide to OSGi services.

2.4 What is Bundle Lifecycle


When a bundle is installed on a framework, it receives a unique identity (a long value chosen by the framework, which will stay persistent throughout the bundles life). Besides this identity, a bundle gets state which is assigned by the framework again. A bundle can have any of all six available states: UNINSTALLED, INSTALLED, RESOLVED, STARTING, STOPPING and ACTIVE. The values assigned to these states have no specic ordering. They represent bit values that may be ORed together for the purposes of determining if a bundle is in one of a set of states. Here is a visual representation of bundles lifecycle:

2 BUNDLES

2.5 A Bundle without an Activator

Installed

Uninstalled

Resolved

Stopping

Starting

Explicit Transition Automatic Transition

Active

When a bundle is installed, it is initially set to INSTALLED stated. During its life, the bundles state can switch among STARTING, STOPPING and ACTIVE. Once a bundle is stopped it gets RESOLVED state. When a bundle is no longer needed and a framework administrator uninstalls it, it will receive UNINSTALLED state. The moments a bundle becomes INSTALLED and UNINSTALLED are the end points in its Lifecycle. Hence, Bundle Lifecycle implies the periodical change of a bundles state between INSTALLED and UNINSTALLED events. What is so important about this? The idea of bundle lifecycle is the dynamic deployment, management and control over bundles and services. The JavaDoc section of the Bundle interface contains more detailed description of a Bundle itself, how it is created and methods which can be invoked on it. It is also very useful reading before continuing with the next chapters.

2.5 A Bundle without an Activator


Is this possible? How are we supposed to start a bundle that doesnt have an Activator class? Is this a Joke? - No! This is a very reasonable question. Practically, the activator object is only necessary for bundles that export or implement services. However, bundles exporting resources may lack an Activator object. The Activator object can be omitted by the framework if it is not specied in bundles manifest le. If the Bundle-Activator eld is missing, the framework will assume that this bundle exports only packages to other bundles and thus it doesnt need any startup code. If such a bundle is started, it will automatically get STARTED state without executing any Activator objects start method. Remember that if you want to incorporate (e.g. in a bundle) another vendors specic packages inside a bundle, you can always use a bundle without activator. The only required thing is to specify Bundle-ClassPath les in the Manifest so as to

2 BUNDLES

2.5 A Bundle without an Activator

indicate the vendors packed jar le, and Export-Packages containing list of the vendors API packages.

3 SERVICES

3 Services
3.1 What is a Service
Here is a quotation of Chapter 4 (Services) of OSGi Framework Specication 1.0: A service is an object that provides some well-dened functionality which is dened by the object classes it implements. It is owned by (and runs within) a bundle that makes its functionality available to other bundles by registering it with the Framework. The dependencies between the bundle owning the service and the bundles using it are managed by the Framework. So in brief we will say that service is a collection of interfaces and their implementations. And this will be our guiding point for this chapter.

3.2 Bundles and Services


Before proceeding further we must clear some aspects of the relations between bundles and services. First of all you must know that each service is registered by a bundle. It is a common practice that registration of services is performed in the bundles activator start method and unregistration when the stop method is called. Of course services can be registered at any other time. A bundle may not register ANY service, but also it may register from one to an undenite number of services. Since services are interfaces they may have more than one implementation and these implementation may belong to different bundles. An example of such service could be any transport service and an implementation could be TCP/IP Transport, SMS Transport, Wireless Transport ... etc. Bundles access services through the BundleContext object which is dened in the OSGi Specication.

3.3 Core OSGi Services


The OSG Initiative itself denes a common set of services that are called core services. These services are described in the subsections below: 3.3.1 Device Access Service A separate document called Device Access Specication which is part of OSGi Specication 1.0 describes the functionality of this service. This chapter will not copy the specication but will provide some basic information about this specication, its goals and usage. In brief Device Access is the driver model of OSGi. It allows automatic detection of attached and detached hardware devices and and automatic device driver selection. Device Access System is an optional component and may not be present in all OSGi implementations. OSGi device access specication is differentiated in the org.osgi.service.device package. 3.3.2 HTTP Service HTTP Service is another core OSGi service. It is dened in the org.osgi.service.http package. 9

3 SERVICES

3.4 Using Services

HTTP Service allows other bundles in the OSGi Framework to register resources and servlets to be accessed via Hypertext Transfer Protocol (HTTP). HTTP Service may implement either HTTP/1.0 or HTTP/1.1. If you look through the JavaDoc for the HTTP Service you will nd valuable examples how to use it for registration of servlets and resources. 3.3.3 Log Service The OSGi framework is an execution environment for many bundles and services that may need to provide some additional information to the user via the log system. The log system can also be used in secure systems as the OSGi framework pretends to be. Thus OSGi species the core Log Service as a common storage for event, debug, emergency and security information. The Log service provides objects and methods for writing and reading log entries. The Log Service interfaces are declared in the org.osgi.service.log package and are very well documented in the corresponding JavaDoc les.

3.4 Using Services


Using services is very simple. Before using any service the service must be gotten. But before getting the service itself we must retrieve its ServiceReference and we do this using the BundleContext object and its method getServiceReference . Having the service reference we can get the service itself again using the BundleContext and the getService method must be called with the service reference we have as a parameter. The service reference will be null if this service is not installed and thus we must check for a null value before getting the service to prevent an emerge of a NullPointerException. If we have retrieved the service successfully we may use it just like we would use it if our program was not running inside an OSGi framework. Now, lets write some code, a bundle manifest and create the bundle.

10

3 SERVICES

3.4 Using Services

First the code:

package tutorial.services.log; import org.osgi.framework.; import org.osgi.service.log.; public class LogDemo implements BundleActivator private nal static String logClass = "org.osgi.service.log.LogService"; / LogService refernce / private ServiceReference sRef = null; / LogService used to log messages / private LogService logService = null;

public void start(BundleContext bc) throws BundleException sRef = bc.getServiceReference(logClass); if( sRef null ) logService = (LogService)bc.getService(sRef); logService.log(LogService.LOG INFO, "Bundle is started"); else throw new BundleException("Unable to get LogService reference");

public void stop(BundleContext bc) logService.log(LogService.LOG INFO, "Bundle is stopped"); bc.ungetService(sRef); sRef = null; logService = null;

And now the manifest:

Bundle-Version: 1.0.0 Bundle-Name: LogDemo Bundle-Description: LogDemo bundle from tutorial. Bundle-Activator: tutorial.services.log.LogDemo Import-Package: org.osgi.service.log

11

3 SERVICES

3.5 Service Properties

Now pack the bundle code and the manifest into a JAR le, install it on your OSGi Framework and play with it. When you start and stop that bundle you can watch the log messages (use your vendor provided tools) and see if it works. The sources of the packed bundle can be found in sources/log directory.

3.5 Service Properties


If you have read the above sections carefully you will know that multiple implementations can be registered by one service name. Here comes the question how we can make difference between all registered implementations. This can be done using the service properties. Again the transport example. We have TCP/IP, SMS, rewire transport. All of them are registered with the framework with one and the same service name. If we want to choose only one of them - let it be the rewire transport, we must set a Service Property called type and then use this property to determine the correct transport. The Service Properties can be used as well for many different purposes. Each service may be registered with a property called vendor and you can retrieve services by the vendors name. In order to demonstrate the usage of the service properties we will create a simple echo service and register it with the framework with some additional properties. Here is its code: EchoService.java: package tutorial.services.echo; public interface EchoService public void echo(String s);

12

3 SERVICES

3.5 Service Properties

EchoServiceImpl1.java: package tutorial.services.echo.impl; import tutorial.services.echo.EchoService; / This implementation of echo service will display echo string on System.out (java console screen) / public class EchoServiceImpl1 implements EchoService public void echo(String s) System.out.println("echo:" + s);

13

3 SERVICES

3.5 Service Properties

EchoServiceImpl2.java: package tutorial.services.echo.impl; import java.net.; import java.io.IOException; import tutorial.services.echo.EchoService; / This implementation of echo service will broadcast UDP packet to port 1234 containing echo string. / public class EchoServiceImpl2 implements EchoService DatagramSocket socket = null; InetAddress bcast = null; public EchoServiceImpl2() throws Exception socket = new DatagramSocket(); bcast = InetAddress.getByName("255.255.255.255");

public void echo(String s) if ( s null ) byte[] bytes = s.getBytes(); DatagramPacket packet = new DatagramPacket(bytes, bytes.length, bcast, 1234); try socket.send(packet); catch (IOException e) // just ignore this

EchoActivator.java:

14

3 SERVICES

3.5 Service Properties

package tutorial.services.echo; import tutorial.services.echo.impl.; import java.util.Properties; import org.osgi.framework.;

public class EchoActivator implements BundleActivator private static nal String serviceName = "tutorial.services.echo.EchoService"; / Service registration for EchoServiceImpl1 / private ServiceRegistration reg1 = null; / Service registration for EchoServiceImpl2 / private ServiceRegistration reg2 = null; private EchoServiceImpl1 impl1 = null; private EchoServiceImpl2 impl2 = null; public void start(BundleContext bc) throws BundleException Properties props = new Properties(); impl1 = new EchoServiceImpl1(); try impl2 = new EchoServiceImpl2(); catch (Exception e) / register rst implementation / props.put("origin", "console"); reg1 = bc.registerService(serviceName, impl1, props); / register second implementation / if( impl2 null ) props.put("origin", "broadcast"); reg2 = bc.registerService(serviceName, impl2, props);

public void stop(BundleContext bc) if( reg1 null ) reg1.unregister(); if( reg2 null ) reg2.unregister();

15

3 SERVICES

3.6 LDAP Filters

And nally the manifest le echo.mf:

Bundle-Version: 1.0.0 Bundle-Name: Echo Bundle-Description: Echo Service Example. This bundle illustrates usage of service properties. Bundle-Activator: tutorial.services.echo.EchoActivator Export-Package: tutorial.services.echo

This entire code and the bundle can be found in the sources/echo directory. In the next section you will learn how to retrieve services using their properties.

3.6 LDAP Filters


Retrieving a service from an OSGi framework may return an undenite number of services. It it might be well for us to be able to lter these services and receive only one - the one we are interested with. Thats why the OSGi Specication provides a method for ltering services and it is realized using an LDAP lter. This section, however will not describe what LDAP lters are but will illustrate their usage within an OSGi framework. So if this is the rst time you have heard about LDAP lters you should at least read RFC 1960 but I suggest you to read the documentation of getServiceReferences method of the BundleContext object from OSGi Specication. If you got a simple idea of LDAP lters we can write some code and see how they are used. But rst of all Ill give you a simple example of an OSGi lter. Now suppose that we have a service named com.acme.MyLamp representing a Lamp device somewhere in your house. But you have many lamps there and you want to control only the one located in your kitchen. Then you can register implementations with the framework with service property location which is different for each Lamp. So here is the lter that will retrieve the Lamp in your Kitchen:

(&(objectClass=com.acme.MyLamp)(location=Kitchen))

You can see that it is very simple and easy to construct such a lter. But now we will include the lter in a real code. We will use the echo bundle from the previous chapter and we will use the lter to choose the implementation that echoes to console. Here is the code (FiltersActivator.java):

16

3 SERVICES

3.6 LDAP Filters

package tutorial.services.lters; import tutorial.services.echo.EchoService; import org.osgi.framework.; public class FiltersActivator implements BundleActivator private static nal String serviceName = "tutorial.services.echo.EchoService"; ServiceReference ref = null; public void start(BundleContext bc) throws Exception ServiceReference[] refs = bc.getServiceReferences( serviceName, "(origin console)"); if( (refs null) && (refs[0] null) ) ref = refs[0]; EchoService svc = (EchoService)bc.getService(ref); if( svc null ) svc.echo("This string must be printed from inside Echo Service");

public void stop(BundleContext bc) if( ref null ) bc.ungetService(ref);

And the manifest le:

Bundle-Version: 1.0.0 Bundle-Name: Filters Bundle-Description: This bundle illustrates usage of LDAP filters to retrieve services. Bundle-Activator: tutorial.services.filters.FiltersActivator Import-Package: tutorial.services.echo

The sources listed here are available as .java les and a ready-built bundle in the sources/lters directory.

17

3 SERVICES

3.7 Service Events and Listeners

3.7 Service Events and Listeners


The OSGi framework is a runtime environment which allows each bundle with enough security permissions to control installation and deinstallation of bundles and services. Thats why its required and advanced the event architecture to notify these administrative bundles so they can take appropriate action. Service events are also very useful even for non administrative bundles. Suppose that you have a bundle that operates on a specic device but there is no device available at the moment. This device may be installed later and your bundle will receive notication that a service has just been registered. If this is the service for the device your bundle can use it to perform some operations with it. Besides services an OSGi Event system allows notication for Bundle and Framework events to be received but an LDAP lter can be applied only to Service Listeners. Bundles use BundleContext methods addBundleListener, addFrameworkListener, addServiceListener to register a listener for a specied event types. These methods, along with BundleListener, FrameworkListener, ServiceListener interfaces and BundleEvent, FrameworkEvent and ServiceEvent objects are well documented by the OSGi API specication. We will write a simple bundle to illustrate the usage of ServiceEvents. The example will sniff for an EchoService and display messages in the console when such a service has been registered, unregistered or modied. And here is its code:

18

3 SERVICES

3.7 Service Events and Listeners

package tutorial.services.events; import org.osgi.framework.; public class EventsActivator implements BundleActivator, ServiceListener private static nal String lter = "(objectClass tutorial.services.echo.EchoService)"; public void start(BundleContext bc) throws Exception bc.addServiceListener(this, lter);

public void stop(BundleContext bc) bc.removeServiceListener(this); / This method implements ServiceListener interface / public void serviceChanged(ServiceEvent event) ServiceReference ref = event.getServiceReference(); String action = null; switch(event.getType()) case ServiceEvent.REGISTERED: action = "REGISTERED"; break; case ServiceEvent.MODIFIED: action = "MODIFIED"; break; case ServiceEvent.UNREGISTERING: action = "UNREGISTERING"; String classes[] = (String[])ref.getProperty("objectClass"); System.out.println("Service " + classes[0] + " is " + action);

19

3 SERVICES

3.8 Using Service Tracker

And the manifest le:

Bundle-Version: 1.0.0 Bundle-Name: Echo Bundle-Description: A simple service that prints on console registering/unregistering/modifying of EchoService service. Bundle-Activator: tutorial.services.events.EventsActivator

Again everything is in the sources directory - inside the events folder.

3.8 Using Service Tracker


Using services in a dynamic environment like the OSGi framework sometimes may be difcult and small programmers mistakes may lead to signicant errors. Thats the reason why OSGi has specied an utility to track operation on services and this is the ServiceTracker utility. It provides the bundle with a simple way to perform the common operations on services. The service allows programmers to specify services that they are interested in using a class name, LDAP lter or ServiceReference. The service is designed to be easily customized - so the tracking process is very exible but even without customization it covers most of the needs of a service user. To use the service a programmer must import the ServiceTracker package inserting the line:
Import-Package: org.osgi.util.tracker; specification-version=1.1

in bundles manifest le. Afterwards a ServiceTracker object can be created in three ways. The rst one is to specify a class name and all services registered with the same class name will be tracked. The second one is to specify a LDAP lter - this way all services with specied properties will be tracked. And the third way is to provide a single ServiceReference to track the exact service to which that ServiceReference points. The tracking process begins when open method is called. When a service is added, modied or removed, the ServiceTracker will call addingService, modiedService or removedService , respectively. You can read more about ServiceTracker in its documentation (JavaDoc). But now its time to see it in action, creating a simple bundle and illustrate its usage. We will use the example from the previous section but instead of using service listeners we will use ServiceTracker.

20

3 SERVICES

3.8 Using Service Tracker

package tutorial.services.tracker; import org.osgi.framework.; import org.osgi.util.tracker.; public class TrackerActivator implements BundleActivator, ServiceTrackerCustomizer private static nal String lter = "(objectClass tutorial.services.echo.EchoService)"; private ServiceTracker tracker = null; private BundleContext bc = null; public void start(BundleContext bc) throws Exception this.bc = bc; tracker = new ServiceTracker(bc, bc.createFilter(lter), this); tracker.open();

public void stop(BundleContext bc)

//nothing here

// A simple method to extract service name from ServiceReference object. private String getServiceName(ServiceReference ref) String name = "[ "; String classes[] = (String[])ref.getProperty("objectClass"); if( classes null ) for(int i=0; i classes.length;i++) name += classes[i] + " "; name += "]"; else name = "noname?"; return name;

// The following methods implements ServiceTrackerCustomizer interface. public Object addingService(ServiceReference ref) System.out.println( "Adding service named " + getServiceName(ref) ); return bc.getService(ref);

public void modiedService(ServiceReference ref, Object service) System.out.println("Modified service named " + getServiceName(ref) );

public void removedService(ServiceReference ref, Object service) System.out.println("Removed service named " + getServiceName(ref) ); 21

4 CONCLUSION

4 Conclusion
I hope this book helped you enough and now you can easily write simple bundles and use services, lters and events. If you have any notes about this book, suggestions or anything else dont hesitate to send me an e-mail. You can do this just clicking on my name on the rst page. I would also like to write another book, containing some more topics for intermediate OSGi programmers so if you have something in mind, suggestions, ideas of what it should contain - write me. I will greatly appreciate any quality feedback.

22

You might also like