OSGi with Eclipse Equinox - TutorialLars Vogel
Version 4.1
Copyright ? 2008, 2009, 2010, 2012 Lars Vogel 10.02.2012
Table of Contents
OSGi is a specification. The core of the OSGi specification defines a component and service model for Java. The components and services can be dynamically activated, de-activated, updated and de-installed. A very practical advantage of OSGi is that every bundle must define its exported Java packages and its required dependencies. This way you can effectively control the provided API and the dependencies of your plug-ins. The OSGi specification defines the OSGi bundle as the unit of modularization. A bundle is a cohesive, self-contained unit, which explicitly defines its dependencies to other modules and services. It also explicitly defines its external API. Technically OSGi bundles are .jar files with additional meta information. This meta information is stored in the "META-INF" folder in the "MANIFEST.MF" file. The "MANIFEST.MF" file is part of a standard jar specification to which OSGi adds additional metadata. Any non-OSGi runtime will ignore the OSGi metadata. Therefore OSGi bundles can be used without restrictions in non-OSGi Java environments.
Each bundle has a symbolic name which is defined via the
Each bundle has also a version number in the
The
Both properties are defined in the "MANIFEST.MF" file. The following is an example of a "MANIFEST.MF" file.
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Popup Plug-in Bundle-SymbolicName: de.vogella.rcp.intro.commands.popup; singleton:=true Bundle-Version: 1.0.0 Bundle-Activator: de.vogella.rcp.intro.commands.popup.Activator Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6
The following table gives an explanation of the identifiers. Table 1. OSGi Manifest Identifier
Via the "MANIFEST.MF" file a bundle can define its dependency to
other
bundles or packages. OSGi will throw a
In the MANIFEST.MF file a bundle also defines the Java packages which should be exported and therefore available to other bundles (as API). Packages which are not exported are not visible to other bundles.
All these restrictions are enforced via a
specific
OSGi
A bundle can define that it depends on a certain version (or a range) of another bundle, e.g. bundle A can define that it depends on bundle C in version 2.0, while bundle B defines that it depends on version 1.0 of bundle C. Equinox supports that a exported package is declared as provisional via the x-internal flag.
This results in the following MANIFEST.MF file.
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Example Bundle-SymbolicName: osgi.example Bundle-Version: 1.0.0.qualifier Bundle-Activator: osgi.example.Activator Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Import-Package: org.osgi.framework;version="1.3.0" Export-Package: osgi.example;x-internal:=true
Eclipse will show the usage of this API as an error, warning or ignore this, depending on the setting in Window → Preferences → Java → Compiler → Error
You can also release a package only for a specific plug-in via the x-friends directive. This flag is added if you add a plug-in to the "Package Visibility" section on the Runtime tab of th MANIFEST.MF editor.
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Provider Bundle-SymbolicName: de.vogella.osgi.xinternal.provider Bundle-Version: 1.0.0.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: de.vogella.osgi.xinternal.provider;x-friends:="de.vogella.osgi.xinternal.consumer"
OSGi is responsible for the dependency management between the bundles. OSGi reads the MANIFEST.MF of a bundle during its installation. It ensures that all dependent bundles are also loaded, if the bundle is activated. If the dependencies are not met, then the bundle is not loaded. With the installation of a bundle in the OSGi runtime this bundle is persisted in a local bundle cache. The OSGi runtime is then trying to resolve all dependencies of the bundle. If all required dependencies are resolved the bundle is in the status "RESOLVED" otherwise it is in the status "INSTALLED". If several bundles exist which would satisfy the dependency, then the bundle with the highest version is taking. If the versions are the same, then the bundle with the lowest ID will be taken. If the bundle is started, its status is "STARTING". Afterwards it gets the "ACTIVE" status. Eclipse Equinox is the reference implementation of the base OSGi specification. Eclipse Equinox is the runtime environment on which Eclipse application are based. In Eclipse the smallest unit of modularization is a plug-in. The terms plug-in and bundle are (almost) interchangeable. An Eclipse plug-in is also an OSGi bundle and vice versa. Eclipse Equinox extends the concept of bundles with the concept of extension points. The OSGI console is like an MS-DOS prompt. In this console you can type a command to perform certain OSGI actions. The following is a reference of the most important OSGi commands. Use for example the command ss to get an overview of all bundles and their status.
Table 2. OSGi commands
Bundles can be identified via their id which is displayed by the command ss. As of Eclipse 4.2 (and Eclpise 3.8) you have to add the following bundles to your runtime configuration to use the OSGi console.
If you specify the
The following assumes that you have already Java installed. If not please Google for "How to installed Java for MyOS", while replacing "MyOS" with the operating system your are using. Browse to Eclipse download site and download the package "Eclipse for RCP and RAP Developers". Extract the download to your harddisk. Avoid having special characters or spaces in the path to Eclipse. In case you have downloaded the Eclipse Java IDE (or any other non RCP flavor) distribution you can use the Eclipse Update Manager to install the plug-ins required for RCP development. Install General Purpose Tools → Eclipse Plug-in Development Environment → Eclipse RCP Plug-in Developer Resources → → from the Eclipse update site for your release. You may have to remove the "Group items by category" flag to see all available features.
In the following we will define and consume a service. Our service will return "famous quotes". Create a plugin project "de.vogella.osgi.quote" and the package "de.vogella.osgi.quote". Do not use a template. You do not need an activator. Afterwards select the MANIFEST.MF and the "Runtime" tab. Add "de.vogella.osgi.quote" to the exported packages.
Create the following interface "IQuoteService".
package de.vogella.osgi.quote; public interface IQuoteService { String getQuote(); }
We will now define a bundle which will provide the service. Create a plugin project "de.vogella.osgi.quoteservice". Do not use a template. Select the MANIFEST.MF and dependecy tab. Add "de.vogella.osgi.quote" to the required plugins.
Create the following class "QuoteService".
package de.vogella.osgi.quoteservice.internal; import java.util.Random; import de.vogella.osgi.quote.IQuoteService; public class QuoteService implements IQuoteService { @Override public String getQuote() { Random random = new Random(); // Create a number between 0 and 2 int nextInt = random.nextInt(3); switch (nextInt) { case 0: return "Tell them I said something"; case 1: return "I feel better already"; default: return "Hubba Bubba, Baby!"; } } }
Register the service in the class Activator.
package de.vogella.osgi.quoteservice; import java.util.Hashtable; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import de.vogella.osgi.quote.IQuoteService; import de.vogella.osgi.quoteservice.internal.QuoteService; public class Activator implements BundleActivator { public void start(BundleContext context) throws Exception { IQuoteService service = new QuoteService(); // Third parameter is a hashmap which allows to configure the service // Not required in this example context.registerService(IQuoteService.class.getName(), service, null); System.out.println("IQuoteService is registered"); } public void stop(BundleContext context) throws Exception { } }
Export your bundles and install them on your server. Start the service bundle.
TipNothing fancy happens, as we are not yet consuming our service.
Create a new plugin "de.vogella.osgi.quoteconsumer". Add also a dependency to the package "de.vogella.osgi.quote".
TipPlease note that we have added the dependency against the package NOT against the plugin. This way we later replace the service with a different implementation.
Lets register directly to the service and use it.
package de.vogella.osgi.quoteconsumer; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import de.vogella.osgi.quote.IQuoteService; public class Activator implements BundleActivator { private BundleContext context; private IQuoteService service; public void start(BundleContext context) throws Exception { this.context = context; // Register directly with the service ServiceReference reference = context .getServiceReference(IQuoteService.class.getName()); service = (IQuoteService) context.getService(reference); System.out.println(service.getQuote()); } public void stop(BundleContext context) throws Exception { System.out.println(service.getQuote()); } }
Export this bundle, install it and start and stop it. Everything work. But if you stop the service bundle then your receive an error.
The reason for this is that OSGi is a very dynamic environment and service may be registered and de-registered any time. The next chapter will use a service tracker to improve this. Declare a package dependency to the package "org.osgi.util.tracker" in your bundle. To use this define the following class "MyQuoteServiceTrackerCustomizer"
package de.vogella.osgi.quoteconsumer; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTrackerCustomizer; import de.vogella.osgi.quote.IQuoteService; public class MyQuoteServiceTrackerCustomizer implements ServiceTrackerCustomizer { private final BundleContext context; public MyQuoteServiceTrackerCustomizer(BundleContext context) { this.context = context; } private MyThread thread; @Override public Object addingService(ServiceReference reference) { IQuoteService service = (IQuoteService) context.getService(reference); thread = new MyThread(service); thread.start(); return service; } @Override public void modifiedService(ServiceReference reference, Object service) { // removedService(reference, service); // addingService(reference); } @Override public void removedService(ServiceReference reference, Object service) { context.ungetService(reference); System.out.println("How sad. Service for quote is gone"); thread.stopThread(); } public static class MyThread extends Thread { private volatile boolean active = true; private final IQuoteService service; public MyThread(IQuoteService service) { this.service = service; } public void run() { while (active) { System.out.println(service.getQuote()); try { Thread.sleep(5000); } catch (Exception e) { System.out.println("Thread interrupted " + e.getMessage()); } } } public void stopThread() { active = false; } } }
You also need to register a service tracker in your activator of your serviceconsumer.
package de.vogella.osgi.quoteconsumer; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; import de.vogella.osgi.quote.IQuoteService; public class Activator implements BundleActivator { private ServiceTracker serviceTracker; public void start(BundleContext context) throws Exception { System.out.println("Starting quoteconsumer bundles"); // Register directly with the service MyQuoteServiceTrackerCustomizer customer = new MyQuoteServiceTrackerCustomizer( context); serviceTracker = new ServiceTracker(context, IQuoteService.class .getName(), customer); serviceTracker.open(); } public void stop(BundleContext context) throws Exception { System.out.println("Stopping quoteconsumer bundles"); serviceTracker.close(); } }
Export your bundle again. Start the OSGI console. Use the update command or the install command to get the new version of your bundle and start it. Once you start your service the tracker will be called and the consumer bundle will start writing messages to the console. Stop the service and verify that the consumer does not use the service anymore. Declarative services (DS) allow to define and consume services via metadata (XML). Via DS you can define OSGi services without extending or implementing OSGi classes. This allows that these services can be tested independently of the OSGi runtime. The "OSGi service component" is responsible for starting the service (service component). For the service consumer it is not visible if the service has been created via declarative service or via other means. Service Components consists of an XML description (Component Description) and an object (Component Instance). The component description contains all information about the service component, e.g. the class name of the component instance and the service interface. A reference to the component description is maintained in the "MANIFEST.MF" file. This file is read by the OSGi runtime and if a component description is found the corresponding service is created. The component description in the "MANIFEST.MF" file looks for example like the following:
Service-Component: component.xml, OSGI-INF/component.xml
To run declarative services you require the following bundles.
Typically component definitions are created in the project
folder
"OSGI-INF" via
New → Other → Plug-in
Development
→ Component
Definition
. The wizard will also add the
On the next page of the wizard, you can maintain the name of the component definition file, a name and the class which implements the services (or consumes the services).
If you press finish, the service editor opens.
On the service tab you can maintain provided services or referred services. For example to provide a service you would press "Add" under "Provided Services" and select the service interface you want to implement.
As a final step you would implement the class which would provide the service. A correctly maintained component.xml would look like the following in XML.
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www./xmlns/scr/v1.1.0" name="de.vogella.osgi.ds.quoteservice"> <implementation class="de.vogella.osgi.ds.quoteservice.QuoteService"/> <service> <provide interface="de.vogella.osgi.quote.IQuoteService"/> </service> </scr:component>
This means that there is a component called "de.vogella.osgi.ds.quoteservice" which provides a service to the OSGI Service Registry under the interface "de.vogella.osgi.quote.IQuoteService". This component is implemented by the class "de.vogella.osgi.ds.quoteservice.QuoteService. After the definition of the component your MANIFEST.MF would contain an entry to the service component.
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Quoteservice Bundle-SymbolicName: de.vogella.osgi.ds.quoteservice Bundle-Version: 1.0.0.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Import-Package: de.vogella.osgi.quote Service-Component: OSGI-INF/component.xml
The
Therefore this bundle needs to start before the service becomes available.
You can ensure this in your run configuration by setting
Please note that using start levels to ensure the correct starting of the OSGi bundles is not a good approach, but other ways are even worse of have been unrealiable. The following will define a DS service based on the quote example. It is therefore required that you have created the "de.vogella.osgi.quote" project which contains the interface definition. Create a new plugin project "de.vogella.osgi.ds.quoteservice". Do not use a template, do not create an activator. Import package "de.vogella.osgi.quote" in MANIFST.MF on the tab "dependencies". Create the Folder "OSGI-INF" in your project. Create a new component definition as described earlier. The implementing class is de.vogella.osgi.ds.quoteservice.QuoteService which provides the service for IQuoteService. Create the class "QuoteService" which implements the interface IQuoteService.
package de.vogella.osgi.ds.quoteservice; import java.util.Random; import de.vogella.osgi.quote.IQuoteService; public class QuoteService implements IQuoteService { @Override public String getQuote() { Random random = new Random(); // Create a number between 0 and 2 int nextInt = random.nextInt(3); switch (nextInt) { case 0: return "Ds: Tell them I said something"; case 1: return "Ds: I feel better already"; default: return "Ds: Hubba Bubba, Baby!"; } } }
Open component.xml and select the tab "Source". The final result should look like the following.
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www./xmlns/scr/v1.1.0" name="de.vogella.osgi.ds.quoteservice"> <implementation class="de.vogella.osgi.ds.quoteservice.QuoteService"/> <service> <provide interface="de.vogella.osgi.quote.IQuoteService"/> </service> </scr:component>
Copy the "org.eclipse.equinox.ds*.jar", "org.eclipse.osgi.services.jar" and "org.eclipse.equinox.util*.jar" from your Eclipse/plugin installation directory into a folder, e.g. "C:\temp\bundles\plugins" and install the bundle into your OSGi runtime via.
install file:c:\temp\bundles\plugins\org.eclipse.equinox.ds.jar install file:c:\temp\bundles\plugins\org.eclipse.equinox.util.jar install file:c:\temp\bundles\plugins\org.eclipse.osgi.services.jar
Start the bundles manually so that declarative services are available. Export your own bundle to "de.vogella.osgi.ds.quoteservice.jar". and install it via:
install file:c:\temp\bundles\plugins\de.vogella.osgi.ds.quoteservice.jar
To check if your service was registered use the command "services". This will list all installed and available services. If you stop / uninstall the old service provider and start the new one your service should be picked up by the consumer.
Of course you can also define the consumption of services via DS. Create a new plugin "de.vogella.osgi.ds.quoteconsumer". Do not use a template, do not create an activator. Import the package "de.vogella.osgi.quote" in MANIFEST.MF on the tab "Dependencies". Create the following class.
package de.vogella.osgi.ds.quoteconsumer; import de.vogella.osgi.quote.IQuoteService; public class QuoteConsumer { private IQuoteService service; public void quote() { System.out.println(service.getQuote()); } // Method will be used by DS to set the quote service public synchronized void setQuote(IQuoteService service) { System.out.println("Service was set. Thank you DS!"); this.service = service; // I know I should not use the service here but just for demonstration System.out.println(service.getQuote()); } // Method will be used by DS to unset the quote service public synchronized void unsetQuote(IQuoteService service) { System.out.println("Service was unset. Why did you do this to me?"); if (this.service == service) { this.service = null; } } }
TipNote that this class has no dependency to OSGi.
Create the Folder "OSGI-INF" and create a new "Component Definition" in this folder.
This time we will use a service. Maintain the "Referenced Services".
Make the relationship to the bind / unbind method via by selecting your entry can pressing "Edit".
The result component.xml should look like:
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www./xmlns/scr/v1.1.0" name="de.vogella.osgi.ds.quoteconsumer"> <implementation class="de.vogella.osgi.ds.quoteconsumer.QuoteConsumer"/> <reference bind="setQuote" cardinality="1..1" interface="de.vogella.osgi.quote.IQuoteService" name="IQuoteService" policy="static" unbind="unsetQuote"/> </scr:component>
The result MANIFEST.MF should look like:
Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Quoteconsumer Bundle-SymbolicName: de.vogella.osgi.ds.quoteconsumer Bundle-Version: 1.0.4 Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Import-Package: de.vogella.osgi.quote Service-Component: OSGI-INF/component.xml
Export your plugin and install it via: install file:c:\temp\bundles\plugins \de.vogella.osgi.ds.quoteconsumer.jar "If you start the bundle now with "start id_of_your_bundle" you should get the feedback that the service was set and one quote should be returned Eclipse use the PDE tooling to manage bundles. Alternatively you can use Bndtools hosted at http:/// . Please see Bndtools tutorial for an introduction. Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www. Google Group. I have created a short list how to create good questions which might also help you. http://www. OSGi Homepage http://www./equinox Equinox Homepage http://www./equinox/documents/quickstart.php Equinox Quickstart guide http://www.ibm.com/developerworks/opensource/library/os-osgiblueprint/ OSGi Blueprint services Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel Android Tutorial Introduction to Android Programming GWT Tutorial Program in Java and compile to JavaScript and HTML Eclipse RCP Tutorial Create native applications in Java JUnit Tutorial Test your application Git Tutorial Put everything you have under distributed version control system |
|