Home Application-development OSGi and Apache Felix 3.0 Beginner's Guide

OSGi and Apache Felix 3.0 Beginner's Guide

By Walid Joseph Gédéon
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Quick Intro to Felix and OSGi
About this book

The OSGi specification is a module system and service platform that implements a complete and dynamic component model. Wasn't that a complicated definition! So how would you really use it in practical modular applications? Let this book break down the seemingly overwhelming OSGi standards for you by explaining Apache Felix's powerful architecture in a simple and easy-to-understand manner using Apache Felix framework to get you up and running sooner than you could expect.

The OSGi standards have found a wide range of applications in the context of the Enterprise, Telecommunications, Telematics, Smart Home, E-Health, and Mobile applications, to name just a few. Apache Felix is one of the most famous implementations of the OSGi framework specification. This book introduces OSGi on the simple and extensible Felix framework and guides you from the development environment setup to the troubleshooting of potential issues, walking you through the development of an OSGi-based application and explaining relevant software design concepts.

The book starts with an introduction to the OSGi Service Platform, its parts, and its bundle structure. It then walks you through setting up the Felix framework and your development environment. It describes the Felix Framework and how to operate it using Gogo. It will teach you everything possible about the practical implementation of OSGi using the Felix Framework as a launch pad.

The book then kicks off the Bookshelf project, a case study that will be used to progressively explain the important concepts around OSGi using the Felix framework. The Bookshelf project feature trail will set the context to explain OSGi headers, the bundle activator, the bundle context, and so on.

As you implement the bookshelf step by step, you learn about OBR repositories, dependency management, and bundle version management with Felix.

Moving ahead, a few more advanced topics are covered, such as using iPOJO for dependency injection and service registration; then the book moves on to the implementation of a web-based graphical interface, first using a simple Servlet, and then building a JSP-based Web Application Bundle.

OSGi service specifications such as the Log Service, Http Service, and Web Container are explained. Finally, the book describes some of the common pitfalls during bundle development, and gives hints on troubleshooting them in Felix.

Publication date:
November 2010
Publisher
Packt
Pages
336
ISBN
9781849511384

 

Chapter 1. Quick Intro to Felix and OSGi

In the current fast evolving market, service providers need a way to quickly deploy new services over their networks in a managed manner. The challenge is to deliver new and updated services to devices over the network, with little or no disruption to other services provided by those devices.

Furthermore, services may be required to run on a multitude of potential targets such as embedded systems, home electronics, cable modems, set-top boxes, media gateways, and so on. A different delivery of this service per target environment constitutes an expensive overhead that is not necessary.

A universal platform with a common framework and a minimal execution environment would allow a faster time to market, reducing the component development and testing time, and thus allowing providers to quickly react to changes in the market needs.

The OSGi service platform specification aims to address this need by providing a universal platform on which applications (or bundles) can be downloaded and plugged into its base framework.

In this book, we will focus on OSGi in the context of the enterprise. Although all of the concepts introduced also apply to the other environments where OSGi is used, some of the additional discussions will be more appropriate for an enterprise service platform.

In this chapter, we will take a quick overview of the OSGi service platform and how it addresses the current market needs. We will also have a first look at the Apache Felix implementation and how it fits into the OSGi world.

You will:

  • Take a quick overview of OSGi

  • Understand the OSGi service platform, its functional layers, and their interaction

  • Take a deep dive into OSGi bundles, their manifest headers

  • Understand how bundles are activated on an OSGi platform

  • Learn about bundle start levels and how they can be used in start-up schema

  • Get an introduction to the Felix framework

What is OSGi?

Started in 1999 as the Open Services Gateway initiative, the OSGi alliance initially targeted embedding Java technology for networked home gateways. It has grown into a cross-market framework for the delivery of services onto a wide variety of devices ranging from customer premise equipments to cars and mobile phones, and from backend servers to home PCs.

With a widespread adoption by the Open Source community and constant improvement brought by the big market players that make up the alliance, the applications of this flexible framework has gained a fast momentum and was greatly improved in the last few releases of its specifications.

The main benefits of the OSGi framework is the standardized means of deploying and maintaining its modular system over the network; a modular system that is based on a non-intrusive, yet powerful set of specifications.

Among the many adopters of OSGi as an application framework in the Open Source community are Knopflerfish, Equinox (Eclipse), and Felix. We will be working with the Apache Felix OSGi service platform implementation.

The OSGi Service Platform's Core Specification documents the framework's expected behavior and also specifies the way its different parts interact, and react to external requests in order to offer its managed services.

This Core Specification is augmented with a set of service specifications, grouped by target market, and includes the definition of service interfaces for the common services in that market, along with specifications on how those services are to behave. Those include:

  • The Service Compendium, which contains the specifications of OSGi services such as:

    • The Preferences service, which holds bundles' preferences in a persistent manner

    • The Event Admin service, which helps bundles communicate through the exchange of events

  • The Enterprise Specification focuses on the enterprise side of things such as distribution, scalability, and so on. The Enterprise expert group is supported by many of the major players in the Java enterprise market such as IBM, Oracle, and SAP, to name a few. For more on this, please refer to http://www.osgi.org/Markets/Enterprise.

We will look more closely at the Log Service and HTTP Service from the Service Compendium in Chapter 10, Improve the Logging and Chapter 11, How about a Graphical Interface? respectively.

Moreover, the applications of OSGi extend into other market segments in addition to the enterprise with the following expert groups:

  • The Mobile market, which focuses on building a robust and secure platform for mobile phones, with implementations available for the major mobile operating systems (such as Android, Windows Mobile, Symbian, Brew, and Linux). For more on this, please refer to http://www.osgi.org/Markets/Mobile

  • The Telematics market, which focuses on automotive, railway systems, shipment tracking, and so on. For more on this, please refer to http://www.osgi.org/Markets/Telematics

  • The Smart Home market, which focuses on the adaptation and uses of this universal platform in the residential context. Applications range from the streaming of audio and video for entertainment and education, to the monitoring and management of energy consumption. For more on this, please refer to http://www.osgi.org/Markets/SmartHome

  • The E-Health market, which focuses on applications in the field of health services, with applications in areas such as hospitalization, personal training programs, or assisted living. For more on this, please refer to http://www.osgi.org/Markets/EHealth

In short, the applications of OSGi are limitless and with a wide involvement from many disparate parties. Do you think you can contributing? If yes, you can consider following one of the previous groups and contribute your experience!

Let's take a look at the layout of an OSGi service platform and understand the way it works.

 

What is OSGi?


Started in 1999 as the Open Services Gateway initiative, the OSGi alliance initially targeted embedding Java technology for networked home gateways. It has grown into a cross-market framework for the delivery of services onto a wide variety of devices ranging from customer premise equipments to cars and mobile phones, and from backend servers to home PCs.

With a widespread adoption by the Open Source community and constant improvement brought by the big market players that make up the alliance, the applications of this flexible framework has gained a fast momentum and was greatly improved in the last few releases of its specifications.

The main benefits of the OSGi framework is the standardized means of deploying and maintaining its modular system over the network; a modular system that is based on a non-intrusive, yet powerful set of specifications.

Among the many adopters of OSGi as an application framework in the Open Source community are Knopflerfish, Equinox (Eclipse), and Felix. We will be working with the Apache Felix OSGi service platform implementation.

The OSGi Service Platform's Core Specification documents the framework's expected behavior and also specifies the way its different parts interact, and react to external requests in order to offer its managed services.

This Core Specification is augmented with a set of service specifications, grouped by target market, and includes the definition of service interfaces for the common services in that market, along with specifications on how those services are to behave. Those include:

  • The Service Compendium, which contains the specifications of OSGi services such as:

    • The Preferences service, which holds bundles' preferences in a persistent manner

    • The Event Admin service, which helps bundles communicate through the exchange of events

  • The Enterprise Specification focuses on the enterprise side of things such as distribution, scalability, and so on. The Enterprise expert group is supported by many of the major players in the Java enterprise market such as IBM, Oracle, and SAP, to name a few. For more on this, please refer to http://www.osgi.org/Markets/Enterprise.

We will look more closely at the Log Service and HTTP Service from the Service Compendium in Chapter 10, Improve the Logging and Chapter 11, How about a Graphical Interface? respectively.

Moreover, the applications of OSGi extend into other market segments in addition to the enterprise with the following expert groups:

  • The Mobile market, which focuses on building a robust and secure platform for mobile phones, with implementations available for the major mobile operating systems (such as Android, Windows Mobile, Symbian, Brew, and Linux). For more on this, please refer to http://www.osgi.org/Markets/Mobile

  • The Telematics market, which focuses on automotive, railway systems, shipment tracking, and so on. For more on this, please refer to http://www.osgi.org/Markets/Telematics

  • The Smart Home market, which focuses on the adaptation and uses of this universal platform in the residential context. Applications range from the streaming of audio and video for entertainment and education, to the monitoring and management of energy consumption. For more on this, please refer to http://www.osgi.org/Markets/SmartHome

  • The E-Health market, which focuses on applications in the field of health services, with applications in areas such as hospitalization, personal training programs, or assisted living. For more on this, please refer to http://www.osgi.org/Markets/EHealth

In short, the applications of OSGi are limitless and with a wide involvement from many disparate parties. Do you think you can contributing? If yes, you can consider following one of the previous groups and contribute your experience!

Let's take a look at the layout of an OSGi service platform and understand the way it works.

 

The framework layout


The modular entity in an OSGi framework is referred to as a bundle. A bundle is a collection of code, resources, and configuration files that are packaged as a Java ARchive (JAR).

A bundle can be compared to a Web ARchive (WAR) in the context of a web container, or to an Enterprise ARchive (EAR) in the context of a Java Enterprise Platform. For example, a web container would inspect the contents of a WAR for configuration, resources, and code that it needs to publish the web application and manage its lifecycle.

In the OSGi world, the framework focuses on the functionality that's required to operate the bundle as an entity with a lifecycle and provides code and services. It then communicates changes to the other components in the framework and the installed bundles.

For example, as we will see in Chapter 13, Improving the Graphics, a web container installed as a bundle listens to bundles that are installed and grabs those that are identified as web applications for registration. The web container would be a service published by a bundle on the framework. In this case, both the web container and the web application are bundles installed on the framework one bundle using the other to provide a service.

Such a split of responsibilities (for example, web application publishing and lifecycle management) offers a greater flexibility in the design of a service platform. It is also applied within the framework in the organization of its components.

The functional layers

The components in the OSGi framework are grouped into distinct functional layers. Each layer is responsible for a specific set of tasks related to the integration of the bundle with the framework. Those layers are explained as follows:

  • The execution environment layer, which is the bottom layer on which the bundles live, is selected to fit the underlying hardware or operating system. Two examples of the common execution environments are CDC-1.1/Foundation-1.1 and JavaSE-1.6. Others can be found in Table 3.2 of the OSGi Core specification.

  • The module layer, which is the bundle space, holds the bundles that are installed on the framework and are managed through the lifecycle layer.

  • The lifecycle layer manages and keeps track of the frameworks and bundles lifecycle state. It is used to install or uninstall framework objects and start or stop them.

  • The service layer, which holds the service-side of the framework, keeps the service registry and manages it.

  • The security layer, which extends the Java 2 security architecture, is optional. When active, it validates bundle signatures, and controls component access rights.

Although we're only going to use the service layer to register our services during this case study, it is interesting to understand the functional breakdown of the framework.

The clear definition of the interfaces of the components in each layer allows for a better flexibility in the implementation of a framework, as well as a well-defined means for bundles to communicate with the service platform.

For example, a different execution environment layer would be selected depending on the target system on which the framework will run. This will happen without affecting the other layers or the bundles that are installed on the platform.

The following diagram depicts this layering and shows some of the interaction between the layers of the framework:

The bundles are kept in a sort of a sandbox and wired together, based on their declared requirements. This not only allows you to enforce a tight control over class visibility, but it also keeps track of which packages a bundle is using from other bundles. This control helps manage bundles better, resulting in the possibility to decide when a bundle can be updated without resetting the bundles that depend on it, allowing runtime update of bundles.

The bundle lifecycle states

The lifecycle of a bundle within a framework starts with its install. A bundle can be installed either by another bundle in the framework, using the framework API, or via the framework implementation.

For example, as we will see in Chapter 5, The Book Inventory Bundle, the Felix framework provides a shell command (the install command) that is used to install bundles. The shell service is installed as a bundle and exposes the command for use as part of the console.

Before a bundle is active on the framework, it must go through the resolution process, in which the module layer reads its manifest headers, performs required checks, and identifies the bundle's dependencies.

When a bundle is successfully resolved, it can be started and the lifecycle layer takes over the process. If a bundle activator is provided with the bundle (using the Bundle-Activator header), then the framework will use it to activate the bundle for initialization. The framework gives control to the bundle activator through the start() method. We'll look more closely at bundle activation in Chapter 5.

The activation can be eager or lazy, as defined by the Bundle-ActivationPolicy header we introduced a bit earlier.

With the eager activation policy, the bundle is activated as soon as it is done starting. When the activation policy is set to lazy, then the bundle is only activated when the first class from that bundle is loaded.

The following state machine describes the states that a bundle can go through during its lifecycle. It also shows the actions that are performed on the bundle to shift its state.

Those states are as follows:

  • INSTALLED: The bundle has been successfully installed. The framework knows enough about this bundle to attempt to load it.

  • RESOLVED: All resources needed for this bundle have been loaded successfully and the bundle is ready to be started. This is also the state the bundle would be in, once successfully stopped.

  • STARTING: The bundle is being started, but has not finished starting.

  • ACTIVE: The bundle has been successfully activated and is running, ready to be used.

  • STOPPING: The bundle is being stopped, but has not finished stopping.

  • UNINSTALLED: The bundle has been uninstalled. Once uninstalled, nothing can be done with the module.

As we'll see in Chapter 5, by defining a bundle activator, the framework will temporarily give the bundle control of the execution flow when it is in the starting and stopping states by calling the bundle activator's start() and stop() methods.

Unless instructed otherwise (that is, by requesting start or stop in transient mode), the framework will keep track of whether a bundle is active and attempt to restore that state at the next startup. When the bundle is started, it is persistently marked for start.

Bundle wiring

Without going into the details of the class loading and visibility constraints, it's worth knowing that the framework keeps separate codebases for the different bundles, controlling how each bundle's classes are loaded and which classes a bundle can "see". The process of linking a bundle to provide its access to another bundle's content is called wiring.

When the framework resolves a bundle for installation, it reads the bundle manifest looking for its capabilities (the packages it provides or exports) and its requirements (those that it imports). It uses this information to wire the bundles together in a mesh of dependencies, thus constructing the class space visible to each bundle.

This mechanism allows each bundle to clearly define which of its packages (and classes) are hidden from other bundles and which are shared.

For example, if Bundle B exports package b and Bundle C exports package c, then those packages are made available for bundles that require them on the framework.

Here, Bundle A imports packages b and c. Those bundle capabilities and requirements are expressed in the form of the Import-Package and Export-Package OSGi headers that we'll see in a bit.

The preceding diagram is a simple view of this wiring. The wires are actually a bit more complex and keep track of constraints such as dependency version ranges, optional dependencies, and so on.

If Bundle C were not installed and package c is not provided by another bundle, then Bundle A cannot be resolved successfully because of its missing dependency.

 

The shared service registry


As part of the activation process, a bundle may register services with the framework's service layer registry. Services are meant to be shared among bundles in the framework.

When a bundle needs to publish a service for use by other bundles, it instantiates that service. Then using the service interface, which will identify the service within the framework, the bundle registers the service with the framework-shared service registry.

From this point, until the bundle unregisters the service, other bundles can then find and get the service, using the service interface to look it up without knowing which bundle has provided it.

Services and their interfaces can be defined and implemented by any provider (or vendor). However, there are a standard set of interfaces for some of the commonly used services defined by the OSGi specifications. This standard definition allows vendors to provide their own implementations of a service, without binding the service consumer to their proprietary interface.

As we will see in Chapter 9, Improving the Bookshelf Service with iPOJO, there are also a few ways to abstract away from the service registration and lookup process by using a configuration-based service definition and injection.

 

Working with bundles


A bundle is very much like a regular JAR, archived in a standard ZIP format.

The main difference between an OSGi bundle and a regular JAR is the additional headers in the manifest file that describe the bundle, providing the framework bundle information such as identity, version, and so on; as well as instructions relating to what this bundle provides as functionality and what it requires from the other bundles on the framework.

Anatomy of a bundle

A bundle holds the resources that are needed for it to provide functionality such as Java classes, HTML files, images, embedded JARs, and so on. It also holds its OSGi header entries in the JAR manifest file. The manifest file is found under META-INF/MANIFEST.MF.

The optional OSGI-OPT/ directory can be used to store additional resources that are not needed for the proper functioning of the bundle: resources such as source code and additional documentation. The framework may choose to throw this content away, if it needs to save storage space.

Another standard OSGi directory that can also be present in a bundle archive is the OSGI-INF/ directory. This is typically used to hold bundle-related configuration and properties, used by other framework bundles when processing this bundle's registration. For example, declarative services' configurations may be placed in this directory.

As we'll see in a bit, among the OSGi manifest header entries are directives for which packages are to be exported and made available to other bundles. The other packages are private and can only be seen and used within the bundle.

The OSGi headers

The bundle uses its manifest meta-data to provide the framework with identity information, description of its content, and directives on how the framework should use this content.

When an OSGi framework attempts to resolve a bundle, it will read and process its header entries. Headers follow strict naming and format rules, the framework will ignore headers that are unknown.

The remainder of this section quickly covers the OSGi headers, stopping on a few for a more detailed description. Many of the headers described in the following sections allow optional parameters, or directives, in their syntax. Those directives are mentioned in some situations, but may have been omitted for simplicity. It is recommended that you refer to the OSGi Core Specifications documentation to get the complete syntax description.

Mandatory headers

The minimal set of headers required by an OSGi framework to correctly register a bundle is the Bundle-ManifestVersion and the Bundle-SymbolicName.

The Bundle-ManifestVersion specifies the version of the manifest header syntax. For the scope of this book, we're following version 4 of the Core Specifications. This header will have the value 2:

Bundle-ManifestVersion: 2

Combined with the bundle version, the Bundle-SymbolicName uniquely identifies the bundle within a framework.

Although not required, it is recommended that the symbolic name be based on the reverse domain name of the bundle provider. For example, the Felix Shell Service bundle, a Felix sub-project which is a project of the Apache Foundation (apache.org), has the symbolic name org.apache.felix.shell.

The Bundle-SymbolicName may also include optional parameters, or directives, such as singleton and fragment-attachment, which we won't describe here.

Functional headers

Some headers define the bundle requirement from the service platform, for example, the Bundle-RequiredExecutionEnvironment declares the list of execution environments this bundle requires to be present on the platform.

During the wiring process, information provided by headers such as Import-Package and Export-Package is used to know the capabilities and requirements of the bundle.

For example, the Import-Package header declares the packages that the bundle imports, that is, the packages that it needs from other bundles. The Require-Bundle header is used to declare that this bundle imports all packages exported by the specified, comma-separated, and bundle symbolic names.

The lifecycle layer allows the bundle to take part in the activation process. By providing a class as a Bundle-Activator. The bundle activator is given the execution control when (the bundle) is starting. The Bundle-ActivationPolicy specifies whether the framework should activate the bundle in a lazy manner once started or in an eager manner. Eager activation is signified by omitting the header.

The Bundle-Version header specifies the version of this bundle. A version is composed of a major part, optionally followed by a minor, micro, and qualifier parts. Those parts are dot separated. When not specified, the version of a bundle is set to 0.0.0.

We'll talk a little more about versions in Chapters 4, Let's Get Started: The Bookshelf Project, and Chapter 5,

Fragments are bundles that attach to other bundles, called hosts, to extend their host with manifest headers and bundle content. They are typically used to add resources such as localization files, graphical themes, and so on. Fragments declare the host that they wish to attach with the Fragment-Host header.

Information headers

Other headers are given for information purposes. They provide additional information to the bundle consumer.

For example, the Bundle-Name and Bundle-Description headers provide a human-readable name and a short description for the bundle. The Bundle-Category header tags this bundle with a set of category names. It is a comma-separated list of category names.

The Bundle-ContactAddress header provides the contact address of the vendor, and the Bundle-Copyright header contains the copyright specification for the bundle.

Many other information headers have not been listed here. The core specification is a good place to get a full listing along with a description of their usage.

 

Start levels


Although this is not necessary with well designed and implemented bundles, there is value in being able to define a sequence in which bundles are started when starting a service platform. This is to control the start and stop of groups of installed bundles, stepwise.

The Start Level Service

The Start Level Service on the OSGi framework allows just that the idea is to assign a "bundle start level" to each bundle, a non-negative number, and to be able to change the "active start level" in a stepwise manner in order to control which group of bundles are active at that time.

The Start Level Service also allows setting an initial bundle start level to be assigned to newly installed bundles. The default bundle start level is 1. This level can be changed by either issuing a command to change it (we'll cover this command in Chapter 3, Felix Gogo) or by changing it in the framework configuration. In Felix, the configuration property to set the initial bundle start level is:

felix.startlevel.bundle=1

Change this property in conf/config.properties of the installed distribution.

The active start level

For example, in the following diagram, we have a Felix instance with an additional three bundles installed (bundles A, B, and C). In this example, the installed bundles are given start level 2 and Bundle C is not started.

The start level 0 is assigned to the System Bundle, no other bundle is allowed on that start level, and the bundles provided with the Felix distribution are on start level 1.

When the framework is starting up, it will first have an active start level of 0, at which point the System Bundle is starting. Once this is done, it will go onto start level 1 and start all the bundles that were persistently marked for start. All bundles on a start level are started before going onto the next.

In the Chapter 3, we'll look at some of the Felix shell commands and learn how to check and change the active and bundle start levels.

In this example, if we change the framework's active start level, it will attempt to start Bundle A and Bundle B, and then set the active start level to 3.

Since Bundle C was not persistently marked as started (it's stopped), it will only be resolved.

By default, Felix will start up until active start level 1. To make it set a different active start level on startup, change the configuration entry that sets the beginning start level; for example, to set it to 3, you would add a property in conf/config.properties as such:

org.osgi.framework.startlevel.beginning=3

Using start levels

As mentioned previously, there are cases where grouping the start of bundles into distinct steps can be useful.

For example, in development scenarios, one may want to split the bundles into "Validated" and "Under Test" and assign those the start levels of 2 and 3 respectively. This would allow separating bundles that may cause issues from the others and control their startup more closely.

In other situations, when the start-up time is lengthy, a splash screen bundle may be placed on start level 1 and would only be removed when all bundles are started.

In our case, we will separate the bundles from a functional point of view. Those bundles are assigned start levels that simplify the operational and support activities needed to maintain the application:

This diagram does not contain all the bundles that will be used for this case study: some of them have been hidden to reduce clutter.

The start levels that we'll use to organize the bundles in our study are as follows:

  • Common Services (level 1), to which are assigned validated common services and libraries, in addition to the bundles provided as part of the distribution.

  • Tier 3 Services (level 2), to which are assigned the data access related bundles. In our case, those will be the Bookshelf Inventory API and the Bookshelf Inventory Mock Impl bundles.

  • Tier 2 Services (level 3), to which are assigned application business logic bundles; in our case, the Bookshelf Service bundle.

  • Tier 1 Service Providers (level 4), to which are assigned bundles that provide user interaction services. For example, the Http Service (which we will look at in details in Chapter 11) is given the start level 4.

  • Tier 1 Services (level 5), to which are assigned bundles that plug into user interface providers. For example, a bundle that implements the text UI commands (in Chapter 8, Adding a command-line interface) is assigned start level 5.

For example, when going through a data migration or cleansing activity; the active start level is set to 2, which keeps only the inventory bundles active and stops the ones on higher start levels.

In the case where web-server maintenance is required, going down to active start level 3 is enough.

 

Apache Felix and sub-projects


Apache Felix is an open-source community effort to implement the OSGi Service Platform Release 4 Core specification under the Apache license.

Started as an initial codebase donation from the Oscar project (on ObjectWeb), it graduated from incubation and became a top-level project in 2007. The result is a performant and small footprint piece of software.

In addition to the framework implementation sub-project, the Felix project provides many services specified in the OSGi Service Compendium specification such as:

  • Log Service specification implementation (section 101) for message logging by bundles in the context of the framework. We will work with the Log service implementation in Chapter 10,

  • Http Service specification implementation (section 102) for providing an http interface to bundles and allowing them to interact with users on a network using standard technologies such as XML or HTML. We will work with the Felix Http Service implementation in Chapter 11.

  • Configuration Admin Service specification implementation (section 104), which is used to manage a bundle's configuration data.

  • Metatype service implementation (section 105), which allows us to describe attribute types that bundle services can use as arguments in a machine-readable format.

  • Preferences service implementation (section 106), which can be used by bundles to store settings and preferences such as user profiles or application data.

  • Service Component Runtime, which is an implementation of the OSGi Declarative Services specification (section 112) providing a service-oriented component model to simplify OSGi-based development, as well as the runtime activities of service registration and handling of dependencies.

  • Event Admin Service specification implementation (section 113), which facilitates the exchange of events as a means of communication between bundles using a publish and subscribe model.

  • UPnP Device service implementation (section 111), which helps the integration of UPnP devices on a peer-to-peer network using XML over HTTP.

Note

UPnP™ is a trademark of the UPnP Implementers Corporation.

In addition to these services, the Felix project provides useful services that improve the developer's experience as well as simplify the framework administration tasks like:

  • Dependency Manager, which uses a declarative approach to simplify dependency management.

  • File Install, which is a service that provides a simple, directory-based, bundle deployment management.

  • Gogo, which is an advanced shell for interacting with the OSGi frameworks (implementation of OSGi RFC 147). We will introduce Gogo in Chapter 3, and learn how to create new commands that hook into it in Chapter 8.

  • iPOJO, which (provides) a sophisticated service-oriented component (environment that simplifies) the development of OSGi bundles by assisting with property injection and service registration. We will work with iPOJO in Chapter 9.

  • Maven Bundle Plugin, which improves the bundle developer's experience by providing automation in the process of bundle creation, thus reducing the error-prone manual intervention. We will work with the Maven Bundle Plugin throughout our case study in Chapter 5.

  • Maven SCR Plugin, which assists the developer's use of declarative services by automating the creation of metatype descriptors.

  • OSGi Bundle Repository Service, which simplifies the framework administrator's task by enabling the connection to remote bundle repositories, the listing of deployed bundles and their installation onto the framework, also handling the deployment of their dependencies. We will learn more about the OSGi Bundle Repository Service and start using it in Chapter 6.

  • Shell Service, Remote Shell Service, and Shell TUI provide means to interact with bundles on the framework, locally and remotely, using a simple command-line console.

  • Web Console Service provides an extensible, browser-based, graphical administration console to the framework. We will look closely at the Web Console in Chapter 12.

Those services, combined with the wide variety of bundles made available by other parties, constitute a rich selection for the construction of an enterprise application.

Pop Quiz

Let's quickly check what you've learned so far:

  1. 1 Which of the following best describes an OSGi bundle?

    1. a. It is an XML file, with headers and properties that describe the bundle

    2. b. It is a service that is registered using the Service layer components

    3. c. It is a Java archive, containing additional headers in its manifest file

  2. 2 How would you register an OSGi bundle with the framework?

    1. a. I implement registration code in the main() method

    2. b. I provide properties in the bundle manifest

    3. c. It is detected automatically by the framework

  3. 3 What happens if, the active start level being at 4, you set it to 3?

    1. a. All the bundles in level 3 are started

    2. b. All the bundles in level 4 are stopped

    3. c. All the bundles are stopped and those on level 3 are started.

 

Summary


In this chapter, we have taken a beginner's overview of the OSGi world, skimmed through some background and history. We have also covered the OSGi Service Platform, its functional layout, the framework's modular entities, and the structure of bundles and their life-cycle on the framework.

We've also introduced the Apache Felix project and quickly covered the services it provides.

By now, you should know:

  • What OSGi is and the market needs it addresses

  • How the OSGi Service Platform is laid out and the function of its layers

  • Understand OSGi bundles, how they are structured, and the way the OSGi Service Platform recognizes and handles them

  • Know about the Apache Felix project and its sub-projects

  • Understand the bundle start levels and the ways you can use them

You have also probably read some more documentation online and have deepened your understanding of those topics.

About the Author
  • Walid Joseph Gédéon

    Walid Joseph Michel Gédéon is a painter and sculptor living in the south of France. He is also a telecommunications network and OSS senior expert. Over the past decade, he has focused his attention on the design and integration of distributed operations support systems in the real world (and around it).

    Browse publications by this author
OSGi and Apache Felix 3.0 Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now