The document provides an introduction to OSGi and its architecture, describing how OSGi bundles work as modular, reusable components and how they can publish and consume services through a service registry, with examples of how to program with the OSGi framework by using bundle activators, service listeners, and more. It also discusses OSGi adoption in Java platforms and how it addresses limitations of other modular systems.
1. Introduction to the
OSGi Service Platform
Bram de Kruijff
GX creative online development
March 2008
2. Introduction to OSGi: About Bram
Bram de Kruijff
Computer Science / Cognitive Science
Product Architect @ GX COD
Interests:
The WEB (any version), Java EE, Linux, Open Source
Email:
Bram.deKruijff@gxwebmanager.com
Blog:
http://www.gxdeveloperweb.com/Blogs/Bram-de-Kruijff.htm
3. Introduction to OSGi: About GX COD
GX creative online development
Web Content Management (WCM)
Privately held / 130+ employees
Nijmegen, Amsterdam, Eindhoven (NL)
http://www.gxwebmanager.com
http://www.gxdeveloperweb.com
http://www.wcmexchange.com
Founded in 1995
First Java based CMS in 1998
5. Introduction to OSGi: Presentation Overview
Introduction
About OSGi
OSGi Architecture
The OSGi bundle
About classloading
Programming basics
Dealing with services
GX WM and OSGi
Conclusion
6. Introduction to OSGi: Introduction (1/7)
Early 2005 at GX HQ…
Increasing demand for rapid changing feature sets and
standard upgrades in CMS marketplace.
Need for a collaborative, stable and secure plug-in model to
support ecosystem model.
Desire to build a best of breed solution based on open
standards and open software.
Requirements for portability, manageability, maintainability
and of course… no downtime!
… so what about the OSGi Service Platform?
8. Introduction to OSGi: Introduction (2/7)
Evaluating J2EE deployment models…
Coarse grained application oriented deployment does not fit
component (or plugin) model well.
Large gap between specifications and implementations lead to
application server hell.
Portlet specification tightly couples implementation to the
servlet APIs.
No support for collaboration at the implementation layer
resulting in DIY classloader hell.
… so what about the OSGi Service Platform!?
9. Introduction to OSGi: Introduction (3/7)
OSGi: Open Services Gateway Initiative
The OSGi™ specifications define a standardized , component oriented , computing
environment for networked services. Adding an OSGi Service Platform to a networked
device (embedded as well as servers), adds the capability to manage the life cycle of the
software components in the device from anywhere in the network. Software components can
be installed, updated, or removed on the fly without having to disrupt the operation of the
device. Software components are libraries or applications that can dynamically discover and
use other components.
http://www.osgi.org/
10. Introduction to OSGi: Introduction (4/7)
At a glance
The OSGi Alliance is a non-profit corporation founded in March
1999.
More than 35 companies from various areas (Sun, IBM,
Ericsson, Nokia, Philips, BMW, Ricoh ...)
Roots in embedded systems (home automation, vehicle,
mobile, etc.)
The OSGi specification is at Release 4 with numerous
successful implementations.
Specification for the core framework and a compendium of
service interfaces.
11. Introduction to OSGi: Introduction (5/7)
In the JCP
JSR-291: Dynamic Component Support for JavaTM SE
- OSGi R4 spec
- Approved
- Sun voted against
JSR-277: JavaTM Module System
- Rival spec
- Initiated by Sun
- No Services layer
JSR-316: JavaTM Platform, Enterprise Edition 6 (Java EE 6)
Specification
- The showdown?
12. Introduction to OSGi: Introduction (6/7)
Adoption in SE/EE
Framework implementations
- Equinox
- Apache Felix (fka Oscar)
- Knopflerfish OSGi
Application frameworks
- Spring OSGi DM
- IPOJO
OW2 JoNaS application server
Netbeans started allignment effort
“IBM, BEA and JBoss adopting OSGi” (InfoQ 28/02/2008).
14. Introduction to OSGi: Architecture (1/7)
OSGi architecture
Application composite OSGi layers
(Bundles)
Bundle Service
Bundle
Bundle .
. .
. . . Life Cycle
Bundle Bundle Bundle
Module
Bundle Bundle Bundle
Security
Bundle Bundle Bundle
Java VM
OS/Hardware
15. Introduction to OSGi: Architecture (2/7)
Execution environment
OSGi APIs only use a subset of J2SE and J2ME CDC
Implementations can use more than the OSGi Minimum EE
Matches most profiles
CLDC/
Security is not mandatory MIDP
OSGi
Min.
J2SE
CDC/FP
Courtesy of IBM, aQute & OSGi; made available under the EPLv1.0
16. Introduction to OSGi: Architecture (3/7)
Security layer
Based on standard Java 2 security architecture
Permission based model
- By Location
- By Signer
Real time management
APIs for management
- Permission admin service
- Conditional permission admin service
17. Introduction to OSGi: Architecture (4/7)
Module layer
Partitions the system into modules
Unit for modularization: Bundle
bundle
Enforces strict visibility rules
bundle
Supports versioning of modules
bundle
bundle
bundle
bundle bundle
Courtesy of IBM, aQute & OSGi; made available under the EPLv1.0
18. Introduction to OSGi: Architecture (5/7)
Life cycle layer
INSTALLED STARTING
Bundle is started by the Bundle
Activator class start
- Start: Initialize
RESOLVED ACTIVE
- Stop: Cleanup
The Activator gets a Bundle Context stop
that provides access to the
UNINSTALLED STOPPING
Framework functions
Framework provides Start Level Courtesy of IBM, aQute & OSGi; made available under the EPLv1.0
service to control the start/stop of
groups of applications
Framework provides bundle lifecycle
events and listener interfaces
19. Introduction to OSGi: Architecture (6/7)
Service registry layer
Provides an in-VM service model
Active bundles may (un)register 0 or more services with the
Framework at any point in time
A service registration is a published interface with optional
registration properties
References to services may be obtained from the Framework
by interface and optional filter
The Framework provides service registration events and
listener interfaces
20. Introduction to OSGi: Architecture (7/7)
Services
Services are simple POJOs with a published service interface
Coupling the to framework is (should be) isolated to the
Activator and collaborators
Services may bind to other services through their published
interfaces
The framework provides a standard Service Factory
mechanism
21. Introduction to OSGi: The OSGi bundle (1/4)
At a glance
A bundle is a regular Java Archive
Meta information through Manifest headers
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: bramk
Build-Jdk: 1.5.0_12
Bundle-Activator: nl.gx.webmanager.services.bundle.compiler.impl.Compi
lerActivator
Bundle-Version: 9.4.0.SNAPSHOT
Bundle-ManifestVersion: 2
Bundle-Vendor: GX Creative Online Development
Import-Package: org.osgi.framework,org.apache.felix.dependencymanager,
javax.xml.parsers,org.osgi.service.prefs
Bundle-Name: GX WebManager JCI Eclipse Compiler
Bundle-Classpath: .,commons-collections-3.1.jar,commons-io-1.2.jar,com
mons-jci-core-1.0-RC1.jar,commons-jci-eclipse-1.0-RC1.jar,commons-jci
-fam-1.0-RC1.jar,commons-lang-2.1.jar,commons-logging-api-1.0.4.jar,c
ore-3.2.0.658.jar
Bundle-Description: GX WebManager JCI Eclipse Compiler
Bundle-SymbolicName: nl.gx.webmanager.bundles.webmanager-compiler-bundle
22. Introduction to OSGi: The OSGi bundle (2/4)
Manifest headers
Bundle-Name: Arbitrary name of the bundle
Bundle-Description: Arbitrary description of the bundle
Bundle-Vendor: Arbitrary name of the bundles vendor
Bundle-SymbolicName: Required universally unique identifier of the bundle
Bundle-Version: Required version specification of the bundle
Bundle-Classpath: Declares the classpath inside the bundle. Default „.‟
Bundle-UpdateLocation: URL that the Framework will use to update the
bundle
Import-Package: Declares provided packages required for the bundle to
resolve
Export-Package: Declares packages from the bundle classpath that can be
exported to other bundles
…. and many more
23. Introduction to OSGi: The OSGi bundle (3/4)
Resources
Bundles may contain additional resources
Embedded Java libraries are referenced from the Bundle-
ClassPath manifest header
Embedded native code libraries are references from the
Bundle-NativeCode manifest header
OSGI-INF/ contains default locations for permissions files,
localization files
OSGi security requires all resources except those in META-
INF/ to be signed
24. Introduction to OSGi: The OSGi bundle (4/4)
Assembling
Many build tools provide support for creating bundles
At GX we use the Felix OSGi Maven plugin that provides
<plugin>
<groupId>org.apache.felix.plugins</groupId>
<artifactId>maven-osgi-plugin</artifactId>
<configuration>
<osgiManifest>
<bundleActivator>
nl.gx.webmanager.wcb.componentmanager.osgi.ComponentManagerActivator
</bundleActivator>
<bundleName>GX WebManager ComponentManager</bundleName>
<bundleDescription>Manages WebManager Components (WCBs)...</bundleDescription>
<exportPackage/>
</osgiManifest>
</configuration>
</plugin>
25. Introduction to OSGi: About classloading (1/6)
Traditional classloading
Delegation model since Java 2
Parent first delegation
26. Introduction to OSGi: About classloading (2/6)
OSGi classloading
Bundles have their own classloader that does not delegate to
the parent classloader by default
Bundle classloaders effectively implement the visibilty
constraints in the Framework
The bundle classloader only has access to packages in the
bundle class space
Core packages like java.* are accessible to the bundle
classloader from the boot classpath
The system bundle may expose additional parent classloader
packages in the Framework
When a bundle resolves the Framework wires packages to the
bundle adding them to the effective class space
27. Introduction to OSGi: About classloading (3/6)
Classloader delegation
Bundle classloaders load classes by a defined search policy
First the boot classpath, then imported packages and finally
the bundle classpath
28. Introduction to OSGi: About classloading (4/6)
The Class space
The effectively visible packages make up a bundles classspace
29. Introduction to OSGi: About classloading (5/6)
Resolving
Resolving is the process where importers are wired to
exporters
Constraints declared by the bundles must be satisfied to
create a valid wire
30. Introduction to OSGi: About classloading (6/6)
Common pitfalls
Provider service instance must be assignable from the
Consumers interface
Commons logging may be hazardous to your health
Libraries may try to load resources from the context
classloader
// Switching the context classloader
ClassLoader bundleClassLoader = this.getClass().getClassLoader();
Thread currentThread = Thread.currentThread();
ClassLoader originalClassLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(bundleClassLoader);
compiler = new EclipseJavaCompiler();
} finally {
currentThread.setContextClassLoader(originalClassLoader);
}
31. Introduction to OSGi: Programming basics (1/10)
Programming basics
The Bundle Activator
Providing a service
Consuming a service
Using FrameworkListener
Using BundleListener
Using ServiceListener
Using ServiceFactory
Using ServiceTracker
Using filters
32. Introduction to OSGi: Programming basics (2/10)
The Bundle Activator
Bundle-Activator manifest entry specifies the activator FQN
An OSGi bundle may specify 0 or 1 activator class. Library bundles have no
need for it
The Activator class must implement org.osgi.framework.BundleActivator
The Framework instantiates and invokes the startmethod when the bundle
enters the ACTIVE state
The Framework invokes the stop method when the bundle leaves the ACTIVE
state
Receives a unique BundleContext that provides access to the Framework
public class SimpleActivator implements BundleActivator {
private BundleContext myBc;
public void start(BundleContext bc) throws Exception {
myBc = bc;
}
public void stop(BundleContext bc) throws Exception { }
}
33. Introduction to OSGi: Programming basics (3/10)
Providing a service
Services are registered with the Framework through the BundleContext
Services are registered by 1 more interface FQNs and optional registration
properties
The Framework returns a ServiceRegistration object for future reference
Registration and unregistration may be done at any point in time
public void registerLongService() {
Long i = new Long(20);
Dictionary props = new Hashtable();
props.put("myvalue", "20");
mySr = myBc.registerService(Long.class.getName(), i, props);
}
public void unregisterLongService() {
mySr.unregister();
}
34. Introduction to OSGi: Programming basics (4/10)
Consuming a service
Services are retrieved from the Framework through the BundleContext
The Framework returns a ServiceReference object that can be used to get the
service instance and may be kept for future reference
Consumers must unget the ServiceReference when done to let the Framework
know the service is released.
Consumers must guard against keeping stale references to service instances
public void consumerLongService() {
ServiceReference sr = myBc.getServiceReference(Long.class.getName());
if (sr != null) {
Long si = (Long) myBc.getService(sr);
if (si != null) {
// ...
myBc.ungetService(sr);
}
}
}
35. Introduction to OSGi: Programming basics (5/10)
Using FrameworkListener
Framework listeners can be (un)registered at the Framework through the
BundleContext
public void registerFrameworkListener() {
myFl = new FrameworkListener() {
public void frameworkEvent(FrameworkEvent fe) {
switch (fe.getType()) {
case FrameworkEvent.ERROR:
Throwable whatHappend = fe.getThrowable();
// ..
break;
default: break;
}
}
};
myBc.addFrameworkListener(myFl);
}
public void unregisterFrameworkListener() {
myBc.removeFrameworkListener(myFl);
}
36. Introduction to OSGi: Programming basics (6/10)
Using BundleListener
Bundle listeners can be (un)registered at the Framework through the
BundleContext
public void registerBundleListener(){
myBl = new BundleListener(){
public void bundleChanged(BundleEvent be) {
Bundle b = be.getBundle();
switch (be.getType()) {
case BundleEvent.INSTALLED:
// ...
break;
default: break;
}
}
};
myBc.addBundleListener(myBl);
}
public void unregisterBundleListener(){
myBc.removeBundleListener(myBl);
}
37. Introduction to OSGi: Programming basics (7/10)
Using ServiceListener
Service listeners can be (un)registered at the Framework through the
BundleContext
A filter can be specified to filter out irrelevant events
public void registerLongServiceListener(){
mySl = new ServiceListener() {
ServiceReference sr = se.getServiceReference();
switch (se.getType()) {
case ServiceEvent.REGISTERED:
// ...
break;
default: break;
}
};
try {
myBc.addServiceListener(sl, null);
} catch (InvalidSyntaxException e) { }
}
public void unregisterLongServiceListener(){
myBc.removeServiceListener(mySl); }
38. Introduction to OSGi: Programming basics (8/10)
Using ServiceFactory
Instead of a service instance a ServiceFactory instance may be registered for
any particular interface
The Framework will call the factory to create instances of the service per
bundle
The Framework will cache service instances
public void registerSimpleLongFactoryService() {
ServiceFactory sf = new ServiceFactory() {
public Object getService(Bundle bundle, ServiceRegistration reg) {
return new Long(bundle.getBundleId);
}
public void ungetService(Bundle bundle,
ServiceRegistration reg, Object service) { }
};
mySr = myBc.registerService(Long.class.getName(), sf, null);
}
public void unRegisterSimpleLongFactoryService() {
mySr.unregister();
}
39. Introduction to OSGi: Programming basics (9/10)
Using ServiceTracker
Convenience class provided by the Framework that makes life a little easier
The tracker guarantees to hold all currently available services
The tracker may naturally return null if no services are available.
private ServiceTracker myLt;
public void registerLongServiceTracker() {
myLt = new ServiceTracker(myBc, Long.class.getName(), null);
}
public Long getLongService(){
return (Long)myLt.getService();
}
public void useLongService(){
Long l = getLongService();
if(l != null){
// ...
}
}
40. Introduction to OSGi: Programming basics (10/10)
Using filters
The Framework allows the application of filters for lookups and service events
Filters are defined in LDAP query syntax (RFC 1960)
Framework API allows passing filters as strings
try {
ServiceReference sr = myBc.getServiceReference(Long.class.getName());
Filter f = myBc.createFilter("(&(objectclassname=" + Long.class.getName()
+ ")(myvalue=20))");
if (sr != null) {
if (f.match(sr)) {
Long si = (Long) myBc.getService(sr);
if (si != null) {
// ...
}
}
myBc.ungetService(sr);
}
} catch (InvalidSyntaxException e) { }
41. Introduction to OSGi: Dealing with services (1/4)
Dealing with OSGi services
Understand (OSGi) service architecture
- Services may not be there
- Services may leave
- Services may be multiple
- Services may fail
Application frameworks make life eas(y/ier)
- Apache Felix Dependency Manager
- IPOJO service component framework
- Spring OSGi Dynamic Modules
42. Introduction to OSGi: Dealing with services (2/4)
Felix dependency manager
Manages full service lifecycle
Provides dependency injection on members
public class JackRabbitRepositoryActivator extends DependencyActivatorBase {
public void init(BundleContext bc, DependencyManager dm)
throws Exception {
dm.add(createService()
.setInterface(JcrRepository.class.getName(), null)
.setImplementation(JackRabbitRepositoryService.class)
.add(
createServiceDependency()
.setService(FrameworkConfig.class)
.setRequired(true)
)
);
}
public void destroy(BundleContext bc, DependencyManager dm)
throws Exception {
}
}
43. Introduction to OSGi: Dealing with services (3/4)
Felix IPOJO
Provides declarative application assembly
Manages full service lifecycle
Provides dependency injection on members
Use bytecode generation / proxies
<?xml version="1.0" encoding="UTF-8"?>
<iPOJO>
<component className="ipojo.example.hello.client.HelloClient">
<requires field="m_hello"/>
<callback transition="validate" method="starting"/>
<callback transition="invalidate" method="stopping"/>
</component>
<instance component="ipojo.example.hello.client.HelloClient" name="HelloClient"/>
</iPOJO>
44. Introduction to OSGi: Dealing with services (4/4)
Spring OSGi Dynamic Modules
Provides declarative application assembly
Manages limited(?!) service lifecycle
Provides setter based dependency injection
Uses spring proxies
<?xml version="1.0" encoding="UTF-8"?>
<beans … >
<bean id="clinic"
class="org.springframework.osgi.samples.petclinic.jdbc.JdbcClinic" lazy-
init="false"
init-method="init">
<property name="dataSource">
<osgi:reference interface="javax.sql.DataSource" timeout="5000"/>
</property>
</bean>
...
</beans>
45. Introduction to OSGi: GXWM and OSGi (1/9)
GX WebManager Component Framework
GXWM Service framework
GXWM Component framework
WCBs
“GX WebManager is a J2EE web application that embeds an OSGi
framework runtime inside a Spring Web Application context”
46. Introduction to OSGi: GXWM and OSGi (2/9)
GXWM Service Framework
Embeds the OSGi runtime
- Apache Felix
- Knopflerfish OSGi
Exposes platform APIs / packages
- GXWM design / handler APIs
- javax packages
- Spring framework packages
Provides platform services
- Configuration management
- License management
- JCR / EM persistence
- Component management
- and many more…
47. Introduction to OSGi: GXWM and OSGi (3/9)
GXWM Service Framework
id Serv ice Framew ork
GX WebManager OSGi Serv ice Platform R4 Name: Service Framework
Author: bramk
Version: 1.0
Created: 3/13/2006 3:12:56 PM
Updated: 3/14/2006 10:15:48 AM
Serv ice Framew ork
«realize»
KnopflerFish OSGi
«realize»
Serv iceFramew ork
OSGi Service Platform:
http://www.osgi.org/
Knopflerfish OSGi:
http://knopflerfish.org/
KnopflerFishFramew ork
48. Introduction to OSGi: GXWM and OSGi (4/9)
GXWM Component Framework
Defines WM Component service contracts
Manages component services
- License
- Deployment
- …
Provides pluggable delegation model
- Elements
- Panels
- Servlets
- …
Provides dependency tracking & injection
49. Introduction to OSGi: GXWM and OSGi (5/9)
GXWM Component Framework : concepts
ComponentManager
- Tracks and manages available ComponentTypes and
ComponentBundles
ComponentType
- Tracks and manages available Components of its own
ComponentType
ComponentBundle
- Registers, manages the lifecycle and manages dependencies of a
set of Components
Component
- Implements the logic required by its declared type and
(optionally) more
51. Introduction to OSGi: GXWM and OSGi (8/9)
GXWM WCBs
A WCB is a regular OSGi Bundle
Will typically utilize convenience classes
- ComponentBundleActivatorBase
Must registers ComponentBundle service
May register 0 or more Component services
May contains type specific resources
52. Introduction to OSGi: GXWM and OSGi (9/9)
Deployment view
GX WebManager is e J2EE web application that embeds an OSGi framework
implementation inside a Spring Web Application context
GX WebManager Component Framework
WebManager Components
GX WebManager Platform
OSGi services
GX WebManager System OSGi Service Framework
Spring beans
GX WebManager System Spring application context
Servlets & Filters
Servlet container
Java 5 runtime
53. Introduction to OSGi: Demo
Demo
Simple example: Package dependency
Simple example: Service dependency
Use case: Switching JDBC drivers
Use case: Integration services