SlideShare a Scribd company logo
An introduction to the OSGi Framework and Specifications
OSGI
Dario Bonino, Ph.D
bonino@ismb.it
• Introduction
• Flash History
• What is it?
• Specifications
• Sets
• Framework Implementations
• OSGi for beginners
• Bundle
• Bundle lifecycle
• Hello bundle!
• Services
• Publish services
• Use services
Agenda
INTRODUCTION
Flash introduction to the main OSGi features, with a hint on
history
• Founded in March 1999
• Formerly an acronym for Open Services Gateway
initiative (OSGi), now OSGi Alliance.
• Several versions starting from early 200x
• …
• v4.1 – 2007
• v4.2 – 2009
• v4.3 – 2011
• v5.0 – 2012
• v6.0 – 2015
The Origin
• Founded in March 1999
• Formerly an acronym for Open Services Gateway
initiative (OSGi), now OSGi Alliance.
• Several versions starting from early 200x
• …
• v4.1 – 2007
• v4.2 – 2009
• v4.3 – 2011
• v5.0 – 2012
• v6.0 – 2015
The Origin
Sorry for the SPRING (breakers)…
No more space for claims about maturity: SPRING first version was released on
2002 (almost 3 years later)
• Strategic members
• Adobe, NTT, Deutsche Telekom, Oracle, Huawei Technologies Inc.,
Paremus Ltd., IBM, ProSyst Software, Liferay, Software AG.
• Principal members
• Cloudyle, Makewave, Luminis, Sumitomo Electric Industries Ltd.
• Contributing associates
• Bitreactive AS, Orange, Eclipse Foundation Inc, Red Hat, Eurotech,
Sagecom SAS, Hitachi, Schneider Electric, Intuit Inc., Telecom Italia
S.p.A., Mitsubishi Electric, TIBCO, NEC, Unify GmbH & Co. KG
• Supporters
• >40
The Alliance
“The OSGi technology is a set of specifications that define
a dynamic component system for Java”
“Specifications enable a development model where
applications are dynamically composed of many different
and reusable components”
“Components hide their implementations from other
components while communicating through services”
Definition
• Set of specifications
• Component – based design and development model
• Opaque modules communicating through services
• SOA (Service Oriented Architecture)
• Loosely coupled
Definition rephrased
• Modular architecture
• Component-based systems
• Off-the-shelf components available
• Embedded to large scale deployments
• Mature
• Widely adopted
Features
• Reduces complexity
• loose coupling between modules, i.e., bundles
• Reuse
• very easy to use any third party components
• Real world
• dynamic bundle update, dynamic addition/removal of services,
etc.
• Easy deployment
• specifies how components are installed and managed
Benefits (1/2)
• Adaptive
• modules can be composed in almost any fashion
• Versioning support
• Dive into jar version hell through dependency management
• Small
• v4.0 core -> 300KByte jar
• … many others
Benefits (2/2)
SPECIFICATIONS
OSGi specifications, quick overview
• At the beginning they were 2…
• OSGi Core
• OSGi Compendium
• Now (v6.0) they are 3+
• OSGi Core
• OSGi Compendium
• OSGi Residential
• OSGi Enterprise
Specification Sets
“The Framework forms the core of the OSGi Specifications.
It provides a general-purpose, secure, and managed Java
framework that supports the deployment of extensible
and downloadable applications known as bundles.”
Core - Framework
• Open Source
• Eclipse Equinox (!)
• Apache Felix
• Apache Karaf
• Knoplerfish
• …
• Commercial
• ProSyst
• …
Framework implementations
• Security Layer
• Module Layer
• Lyfecycle Layer
• Service Layer
• Actual services (Bundles)
Framework Layers
• Based on Java2 security
• Adds some constraint
• Fixes some “blanks” in the
original Java2 specification
OSGi Core specifications, v6.0
– p.17
Security Layer
• Defines a modularization model
for Java
• Rules for
• Sharing packages between “Bundles”
• Hiding packages from other “Bundles”
• Can be used without upper layers
• Lyfe cycle
• Service
OSGi Core Specification, v6.0 – p.31
Module Layer
• Provides a lifecycle API to bundles
• Defines how bundles are:
• Started
• Stopped
• Installed
• Updated
• Uninstalled
• Defines the APIs for a management
bundle controlling the OSGi Framework
• Requires the Module Layer
• Security is optional
OSGi Core Specification, v6.0 – p.93
Lyfe Cycle Layer
• Dynamic, concise, consistent
model for Java Bundles
developers
• Decouples service specification
(Java Interface) from
implementation(s)
• Allows binding services basing on
Interfaces, only
• Specific service implementations
selected at runtime
(through the Framework
Registry)
OSGi Core Specification, v6.0 –
p.127
Service Layer
Layer Interaction
BUNDLES
Hands on introduction to bundles and bundle development
• Single unit of Modularization
• Java classes + other resources
• Can share packages with other bundles
• Export
• Import
• Deployed as Java Archive file
• JAR
• (Zip encoded)
Bundle (1/2)
• Content
• Java classes + resources needed
to provide a given functionality
• Manifest file
• Describes the JAR content
• Provides information about the
bundle
• E.g., imported / exported
packages
• Documentation in
• OSGI-OPT folder
• [See later] Declarative service
specification in
• OSGI-INF folder
Bundle (2/2)
• Bundles
• Library Bundles
• Only provide library functions through the export-package header
• Fragment Bundles
• Can be attached to one or more host bundles
• Treated as part of the host bundle
• Extension Bundles
• Deliver optional parts of the framework implementation
• Provide functionality that must reside on the boot class path
• Cannot be provided by the normal import / export clauses
Types of Bundles
• Part of the Life Cycle Layer
• Defines how a bundle is
• Installed
• Updated
• Uninstalled
Bundle lifecycle
• A Bundle is started through its
• Bundle Activator
• The Bundle Activator is identified by the
• Bundle-Activator header in the Bundle manifest
• The Bundle Activator class must implement the
BundleActivator interface
• start(BundleContext ctx)
• stop(BundleContext ctx)
*REMINDER: WE WILL USE DECLARATIVE SERVICES (OSGI COMPENDIUM)
Starting Bundles
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator
{
public void start(BundleContext context)
{
System.out.println("Starting bundle");
}
public void stop(BundleContext context)
{
System.out.println("Stopping bundle");
}
}
Activator Example
• Bundle identifier
• A long number
• Assigned by the framework
• Typically ascending order of installation
• Bundle location
• Assigned by the management agent
• URL to the bundle JAR file (not mandatory)
• Unique in a framework instance
• Bundle Symbolic Name and Bundle Version
• Assigned by the developer
• Semantic versioning
• Naming convention <-> Java package naming (free indeed)
Bundle Identification (1/2)
• Bundle identifier
• A long number
• Assigned by the framework
• Typically in ascending order of installation
• Bundle location
• Assigned by the management agent
• URL to the bundle JAR file (not mandatory)
• Unique in a framework instance
• Bundle Symbolic Name and Bundle Version
• Assigned by the developer
• Semantic versioning
• Naming convention <-> Java package naming (free indeed)
Bundle Identification (2/2)
Bundle States
Bundle States
The Bundle has been
successfully installed
Bundle States
All Java classes are
available (ready to be
started or just stopped)
Bundle States
The bundle is being
started. The Bundle
Activator start() will
be called.
Bundle States
The bundle has been
successfully activated
and is running.
start() has been
called and returned.
Bundle States
The bundle is being
stopped. The stop()
method has been called
but it has not yet
returned
Bundle States
The bundle has been
uninstalled. It cannot
move into another state.
ECLIPSE EXAMPLE
Hello World bundle in Eclipse Equinox
• Download Eclipse RCP
• Install Eclipse RCP
• Run Eclipse
Environment Set-up
• File > New > New Plugin
Project
Hello World! (1/7)
• Type the bundle ID (reverse
Java package notation)
• Version (Semantic
versioning)
• 1.0.0.(qualifier)
• Name of the project/bundle
• Hello World OSGi
• Define the activator class
• It.ismb.pert.hello.HelloActivat
or
• Hit on finish
Hello World! (2/7)
Hello World! (3/7)
Structure and Manifest, after the initial project creation
• Write the activator body
• Simply print on the console
• “Hello OSGi world, I’m active
now!” on activation
• “Goodbye OSGi world!” on
deactivation
Hello World! (4/7)
Hello World! (5/7)
Hello World! (6/7)
Hello World! (7/7)
BUNDLES - RELOADED
More deep discussion on bundles
• Dependency on external
entities
• Requirements
• Import-Package
• Capabilities
• Export-Package
Requirements and Capabilities
• Resolving is the process that
creates a wiring between
bundles
• Any mandatory requirement must be
matched to at least one capability in the same
namespace provided by any of the resolved
bundles, including itself and the system
bundle.
• The required execution environments as
defined by the Bundle-
RequiredExecutionEnvironment header.
• Native code
• Import and export packages (the Dynamic
Import-Package header is ignored in this
phase)
• Required bundles, which import all exported
packages from a bundle as defined in
Requiring Bundles on page 79.
• Fragments, which provide their contents and
definitions to the host as defined in .
Resolving (1/2)
• A bundle can be resolved
only if:
• Execution Environment
• The VM implements at least one
of the execution environments
listed in
• Bundle-
RequiredExecutionEnviron
ment
• Native Code
• The Native code dependencies
must be resolved
• Bundle-NativeCode
• A bundle can be resolved if
• All its mandatory requirements
are satisfied
• All its mandatory imports are
wired
• All its mandatory required
bundles are available and their
exports wired
Resolving (2/2)
• A wire is only created if
• The importer's version range matches the exporter's version
• The importer specifies all mandatory attributes from the
exporter
• All the importer's attributes match the attributes of the
corresponding exporter.
• Implied packages referring to the same package as the wire are
wired to the same exporter
• The wire is connected to a valid exporter.
Wiring (1/2)
• Preferences in wiring
• A resolved exporter must be preferred over an unresolved
exporter.
• An exporter with a higher version is preferred over an exporter
with a lower version.
• An exporter with a lower bundle ID is preferred over a bundle
with a higher ID.
Wiring (2/2)
Class loading
• A bundle can be started
• Calling one of its start methods
• Automatically by the framework if
• Is ready
• The bundle is resolved
• The bundle start level is met (optional)
• Autostart is set
• Stopped (the bundle should not start)
• Started with eager activation (started once ready and eagerly activated)
• Started with a declared activation (started once ready, according to the
declared activation policy)
Starting a bundle
• Eager activation
• Started as soon as possible (i.e. when resolved)
• Lazy activation
• Must not be activated until it receives the first request to load a
class
• Class can be loaded
• through normal class loading or
• by calling the Bundle loadClass method
Bundle Activation policies (1/2)
Bundle Activation Policies (2/2)
• The framework is represented as a bundle
• System Bundle
• Allows to register services that can be used by other bundles
• Has always bundle ID=0
• getLocation returns “System Bundle”
• Symbolic Name unique for a specific version
• Cannot be managed as normal bundles
• Start – the system bundle is already started
• Stop – shutdown the framework on another thread
• Update – stops and restarts the framework on another thread
• Uninstall – throws a BundleException since it cannot be uninstalled
The System bundle
• The Life Cycle Layer supports/generates
• Framework events
• Framework has started, changed start level, packages have been
refreshed, errors occured
• Bundle events
• Changes in the lifecycle of bundles
• Listeners can be associated to all events
• Synchronous
• In the event loop (CAREFUL!)
• Asynchronous
Events
• INSTALLED
• Sent after a bundle is installed. The state is now
Bundle INSTALLED state.
• RESOLVED
• Sent when the Framework has resolved a bundle.
The state is now the Bundle RESOLVED state.
• LAZY_ACTIVATION
• The bundle has specified an activation policy; its
activation is deferred to a later point in time. The
state is set to the Bundle STARTING state. This is
only sent to SynchronousBundleListener
objects.
• STARTING
• Sent when the Framework is about to activate a
bundle. This is only sent to
SynchronousBundleListener objects. The
state is now the Bundle STARTING state.
• STARTED
• Sent when the Framework has started a bundle.
The state is now the Bundle ACTIVE state.
• STOPPING
• Sent when the Framework is about to stop a
bundle or the start method of the Bundle
Activator has thrown an exception and the
bundle is stopped. This event indicates that the
Bundle Context will be destroyed. This event is
only sent to SynchronousBundleListener
object
• STOPPED
• Sent when the Framework has stopped a bundle.
• UNINSTALLED
• Sent when the Framework has uninstalled a
bundle
• UNRESOLVED
• Sent when the Framework detects that a bundle
becomes unresolved; this could happen when the
bundle is refreshed or updated.
• UPDATED
• Sent after a bundle is updated.
Bundle events
• ERROR
• Important error that requires the immediate
attention of an operator.
• INFO
• General information that is of interest in special
situations.
• PACKAGES_REFRESHED
• The Framework has refreshed the packages.
• STARTED
• The Framework has performed all initialization
and is running in normal mode.
• STARTLEVEL_CHANGED
• Is sent by the Framework after a new start level
has been set and processed.
• STOPPED
• Sent by the Framework because of a stop
operation on the system bundle.
• STOPPED_BOOTCLASSPATH_MODIFIED
• Sent by the Framework because of a stop
operation on the system bundle and a boot
class path extension bundle has been
installed or updated.
• STOPPED_UPDATE
• Sent by the Framework because of an
update operation on the system bundle.
The Framework will be restarted after this
event is fired.
• WARNING
• A warning to the operator that is not crucial
but may indicate a potential error situation.
• WAIT_TIMEDOUT
• Returned from the waitForStop method
when the Framework did not stop before
the given wait time-out expired.
Framework events
SERVICES
OSGi Services – Quick introduction
• Defined at the Service Layer
• Publish, find and bind model
• “A service is a normal Java object that is registered under
one or more Java interfaces within the service registry.“
• “Bundles can register services, search for them, or
receive notifications when their registration state
changes.”
OSGi Core Specification v6.0, p. 127
Service
• Service
• An object registered with the
service registry under one or
more interfaces together with
properties. The service can be
discovered and used by bundles.
• Service Registry
• Holds the service registrations.
• Service Reference
• A reference to a service. Provides
access to the service's properties
but not the actual service object.
The service object must be
acquired through a bundle's
Bundle Context.
Terminology (1/4)
• Service Registration
• The receipt provided when a service
is registered. The service registration
allows the update of the service
properties and the unregistration of
the service.
• Service Permission
• The permission to use an interface
name when registering or using a
service.
• Service Scope
• Indicates how service objects are
obtained when requesting a service
object. The following service scopes
are defined: singleton, bundle, and
prototype. The default service scope
is singleton.
Terminology (2/4)
• Service Factory
• A facility to let the registering bundle
customize the service object for each using
bundle. When using a Service Factory, the
service scope of the service is bundle.
• Prototype Service Factory
• A facility to let the registering bundle
customize the service object for each caller.
When using a Prototype Service Factory,
the service scope of the service is
prototype.
• Service Objects
• A facility to let the using bundle obtain
multiple service objects for a service with
prototype service scope.
• Service Listener
• A listener to Service Events.
Terminology (3/4)
• Service Event
• An event holding information
about the registration,
modification, or unregistration of
a service object.
• Filter
• An object that implements a
simple but powerful filter
language. It can select on
properties.
• Invalid Syntax Exception
• The exception thrown when a
filter expression contains an
error.
Terminology (4/4)
• Semantically defined by a Java Interface
• Service Interface
• As few implementation details as possible (in theory shall be
independent from implementation)
• Common interfaces are already specified by OSGi specifications
(see Compendium)
• Implemented by a Java Object
• Service Object
• Owned by a bundle
• Runs within a bundle
Service – In Short
• The bundle must register the service object within the
Framework Registry
• Dependencies between bundles
• Offering (owning) a service
• Using a service
Are directly managed by the Framework.
• For example
• When a bundle is stopped, de-register all the services “owned”
by the bundle
Find & Bind (1/2)
• The Framework maps Services (Interfaces) with
underlying Service Objects
• Event mechanism for detecting when service are:
• Registered
• Modified
• Unregistered
Find & Bind (2/2)
• Used to refer to a Service Object
• Decoupling -> No dynamic dependencies for information-only
• Can be passed / stored to/within other bundles without
setting dynamic bundle dependency
• Encapsulates the properties and meta-information about
the represented Service Object
• Properties and meta-information can be queried
Service Reference (1/2)
• Can be obtained
• From the Framework
• Querying the service registry
• From the registration process
• Through the service registration
• Acquired references are “tracked” by the framework
• See getting / un-getting services
Service Reference (2/2)
• The developer
• implements a service by
• Defining the Service Interface
• Creating a Service Object by implementing the Service Interface
• Registering the interface within the framework
• Searches for interfaces within the Framework by
• Interface name (e.g., fully qualified)
• Filter on registration properties (LDAP syntax)
Service Interfaces
• Services must be registered in the Framework registry
• Can be done through
• Bundle Context
• Every registered service has a unique
• ServiceRegistration object
• Many
• ServiceReference objects pointing at it
Registering Services (1/4)
• registerService(String,Object,Dictionary)
• For a service object registered under a single service interface.
• registerService(String[],Object,Dictionary)
• For a service object registered under multiple service
interfaces.
• registerService(Class,Object,Dictionary)
• For a service object registered under a single service interface
using the class object for the interface name.
• The Framework MUST ensure that objects registered as
Services actually implement the Service Interface.
Registering Services (2/4)
• Upon successful registration the Framework must return
a ServiceRegistration object to the caller.
• A service object can be unregistered only by the holder of
its ServiceRegistration object
• Every successful service object registration must yield a
unique ServiceRegistration object even if the same
service object is registered multiple times.
Registering Services (3/4)
• Using the ServiceRegistration object is the only way to
reliably change the service's properties after it has been
registered
• Modifying a service's Dictionary object after the service
object is registered may not have any effect on the
service's properties.
Registering Services (4/4)
• Key-Value pairs
• Key MUST be a String
• Value MUST be “recognized” by Filter objects
• Keys are CASE INSENSITIVE
• Properties shall provide information about the Service
• Properties shall never taker part in the actual function of the Service
• All properties share a single namespace in the Framework service
registry.
• use descriptive names or formal definitions to prevent conflicts.
• Several OSGi specifications reserve parts of this namespace.
• service. *
• objectClass
Service Properties
Pre-defined properties (1/3)
Pre-defined properties (2/3)
Pre-defined properties (3/3)
Services Hello World
ECLIPSE EXAMPLE
• Same as the one used for the OSGi Hello World
• Design & implement a service for printing messages on
the OSGi console
• Interface: ConsoleLogger
• Methods: log(String message)
HINT – after the example look at the OSGi LogService
Set-up
Service Interface
Service Implementation
• First:
• Prepare the service “holder”
variable
• Prepare the service
registration ”holder”, will be
used for unregistering the
service
Note: this is an oversimplified
implementation for teaching purposes
Service Registration (1/3)
• Create an instance of the
Service, i.e., the service
implementation
• Prepare the service
description properties, e.g.,
the service PID
• Register the service using the
interface class
• (can be done using the
interface fully qualified name)
Service Registration (2/3)
• On de-activation, unregister
the service
Service (Un)Registration (3/3)
• Everything done !?!?!
• No!
• The service shall be exported to allow other bundles using it
• The Java interface must be made available to other bundles
• Where? In the MANIFEST
Service Registration (4/3)
Exporting packages
• You might have noticed that
• Only packages can be exported
• No way for single classes
• Therefore
• Particular care shall be devoted
to package design
• Our example is “BAD” as the
activator and the service
interface lie in the same package -
> we will export also the
activator, which is undesirable
Last remarks
• No effect!
• Right! Nobody in the framework is using our service
• OSGi command line utils:
• SS
• Provides the list of available bundles together with their state
• Services
• Lists the services currently registered in the framework
{it.ismb.pert.service.console.logger.service.ConsoleLogger}={service.
pid=it.ismb.pert.service.console.logger.impl.SystemConsoleLogger,
service.id=46, service.bundleid=4, service.scope=singleton}
"Registered by bundle:" it.ismb.pert.service.console.logger_1.0.0 [4]
"No bundles using service."
Run and check!
• No effect!
• Right! Nobody in the framework is using our service
• OSGi command line utils:
• SS
• Provides the list of available bundles together with their state
• Services
• Lists the services currently registered in the framework
{it.ismb.pert.service.console.logger.service.ConsoleLogger}={service.
pid=it.ismb.pert.service.console.logger.impl.SystemConsoleLogger,
service.id=46, service.bundleid=4, service.scope=singleton}
"Registered by bundle:" it.ismb.pert.service.console.logger_1.0.0 [4]
"No bundles using service."
Run and check!
!
SERVICES - RELOADED
Getting & tracking services
• Services published by bundles remain unused until some
other bundle requires / gets the service
• Two ways for getting services
• BundleContext.getService(ServiceReference)
• This method should be used if the using bundle only needs a single
service object.
• ServiceObjects.getService()
• This method should be used if the service has SCOPE_PROTOTYPE scope
and the using bundle needs multiple service objects.
Getting Services (1/2)
• BundleContext.getService(ServiceReference) method
• returns an object that implements the interfaces as defined by
the objectClass property.
• A bundle making multiple calls to this method, without
releasing the service object, will receive the same service
object.
Getting Services (2/2)
• This method has the following characteristics:
• Returns null if the underlying service object has been
unregistered.
• Determines if the caller has ServicePermission to get a service
object associated with the specified Service Reference.
• Increments the usage count of the service by one for this
BundleContext object.
• If the service has SCOPE_SINGLETON scope then the registered
service object is returned.
• Special behavior for other scope types (Factory)
BundleContext.getService
ECLIPSE EXAMPLE
Getting services
• Write a bundle that exploits our ConsoleLogger service
to print random numbers on the screen
Set-up
New plug-in project
• Add a dependence on the package holding the
ConsoleLogger interface
Dependencies
• Recurrent task
• Best on a separate thread
• Must close cleanly
• Take care of creation /
disposal of the thread in the
activator
Random Generator
• Starts the generator thread
• Gets the service reference
and then the service instance
using the bundle context
• (Note this!, will be
changed…)
Activator (1/2)
• Stop cleanly:
• Stop the thread
• Wait for the thread to
gracefully close
• UNGET the service!
Activator (2/2)
• Test
• Does it log random numbers?
• Identify the bundle ID for the logger and for the random
number generator
• Stop the generator, is stop clean?
• Stop the console logger, what happens?
• Why the random number generator still works when we
stop the console logger service?
Run the services
Mmmh, what’s happening?
• The RandomGenerator Thread keeps a reference to the
actual service class (console logger)
• Any Java object is kept alive until there is a reference
pointing at it
• The logger is kept “alive” untile the generator uses it
• This should be avoided, in our case:
• No logger, no party!
Problem analysis
• Use service
references!!!
• React to
service
availability
Solution (1/2)
Solution (2/2)
SERVICES - REVOLUTION
What else?
• Many many features:
• Service Tracker
• To track / react to service availability
• Permissions
• Etc.
• See OSGi Core Specifications v6.0
What else?
• Write a bundle that generates a clock signal at 1Hz
• Exploit / modify the ConsoleLogger bundle to print the
current time, generated by the clock bundle on the
console.
Exercise
Questions?
Dario Bonino, Ph.D
bonino@ismb.it
END (FIRST EPISODE)

More Related Content

PPTX
PPTX
Integrating Microservices with Apache Camel
PPTX
Best practices for ansible
PDF
Packer by HashiCorp
PDF
OSGi Presentation
PDF
Amazon EC2 HPCインスタンス - AWSマイスターシリーズ
PPT
Ansible presentation
PDF
Evolution of containers to kubernetes
Integrating Microservices with Apache Camel
Best practices for ansible
Packer by HashiCorp
OSGi Presentation
Amazon EC2 HPCインスタンス - AWSマイスターシリーズ
Ansible presentation
Evolution of containers to kubernetes

What's hot (20)

PDF
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCD
PPTX
Postgres Playground で pgbench を走らせよう!(第35回PostgreSQLアンカンファレンス@オンライン 発表資料)
PDF
Ansible Playbook
PDF
Docker Introduction
PDF
Javaのプログラムはどうやって動いているの? JVM編
PDF
SpringOne Tour: Spring Boot 3 and Beyond
PPTX
Nomad + Flatcar: a harmonious marriage of lightweights
PPTX
Ansible presentation
PPTX
ContainerとName Space Isolation
PPTX
An introduction to Maven
PDF
Spring Framework - AOP
PDF
今Serverlessが面白いわけ
PDF
nexus helm 설치, docker/helm repo 설정과 예제
PPTX
Packer
PDF
Kubernetes - introduction
PPTX
Spring Cloud Config
PDF
Spring boot
PDF
【メモ】一般的に設計書に定義される項目例
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCD
Postgres Playground で pgbench を走らせよう!(第35回PostgreSQLアンカンファレンス@オンライン 発表資料)
Ansible Playbook
Docker Introduction
Javaのプログラムはどうやって動いているの? JVM編
SpringOne Tour: Spring Boot 3 and Beyond
Nomad + Flatcar: a harmonious marriage of lightweights
Ansible presentation
ContainerとName Space Isolation
An introduction to Maven
Spring Framework - AOP
今Serverlessが面白いわけ
nexus helm 설치, docker/helm repo 설정과 예제
Packer
Kubernetes - introduction
Spring Cloud Config
Spring boot
【メモ】一般的に設計書に定義される項目例
Ad

Similar to OSGi introduction (20)

PDF
Open Services Gateway Initiative (OSGI)
PPT
OSGi & Blueprint
PDF
OSGi tech session
PDF
OSGi user forum dc metro v1
PDF
OSGi User Forum US DC Metro
PDF
Osgi Sun 20080820
PPTX
Introduction to OSGi
PDF
OSGi bootcamp - part 1
PDF
Technical Specification Overview - OSGi World Congress 2002 Workshop Intro - ...
PPTX
Introduction to OSGi - Part-1
PPTX
What is os gi and what does osgi
PPTX
OSGi Training for Carbon Developers
PDF
Benefits of OSGi in Practise
KEY
Introduction to EclipseRT (JAX 2010)
PPT
OSGi For Java Infrastructures [5th IndicThreads Conference On Java 2010, Pune...
PDF
Eclipse_Building_Blocks
PPTX
PPTX
PPTX
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
PDF
Create *real* modular Java applications - a brief introduction -
Open Services Gateway Initiative (OSGI)
OSGi & Blueprint
OSGi tech session
OSGi user forum dc metro v1
OSGi User Forum US DC Metro
Osgi Sun 20080820
Introduction to OSGi
OSGi bootcamp - part 1
Technical Specification Overview - OSGi World Congress 2002 Workshop Intro - ...
Introduction to OSGi - Part-1
What is os gi and what does osgi
OSGi Training for Carbon Developers
Benefits of OSGi in Practise
Introduction to EclipseRT (JAX 2010)
OSGi For Java Infrastructures [5th IndicThreads Conference On Java 2010, Pune...
Eclipse_Building_Blocks
Java 9 Modules: The Duke Yet Lives That OSGi Shall Depose
Create *real* modular Java applications - a brief introduction -
Ad

More from Dario Bonino (18)

PDF
OSGi compendium
PPTX
PDF
ficloud2015
PDF
citizen-centric-app
PPTX
Dog ont
PDF
bonino_thesis_final
PPT
bonino
PDF
The Dog Gateway - Intro
PDF
Home and building automation systems sun slice
PPTX
Rilievo informatico di cavità naturali
PPTX
Dog2.3 Architecture
PPTX
Home and building automation systems
PPTX
Dog Ont In Dog
PPTX
Dog Ont
PDF
Iswc2008
PDF
Webs2008
PDF
Dog Sim
PPTX
Interoperation Modeling
OSGi compendium
ficloud2015
citizen-centric-app
Dog ont
bonino_thesis_final
bonino
The Dog Gateway - Intro
Home and building automation systems sun slice
Rilievo informatico di cavità naturali
Dog2.3 Architecture
Home and building automation systems
Dog Ont In Dog
Dog Ont
Iswc2008
Webs2008
Dog Sim
Interoperation Modeling

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
top salesforce developer skills in 2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
ai tools demonstartion for schools and inter college
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPT
Introduction Database Management System for Course Database
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Introduction to Artificial Intelligence
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Nekopoi APK 2025 free lastest update
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
System and Network Administraation Chapter 3
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Softaken Excel to vCard Converter Software.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
How to Choose the Right IT Partner for Your Business in Malaysia
top salesforce developer skills in 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Online Work Permit System for Fast Permit Processing
ai tools demonstartion for schools and inter college
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Introduction Database Management System for Course Database
Operating system designcfffgfgggggggvggggggggg
Introduction to Artificial Intelligence
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Wondershare Filmora 15 Crack With Activation Key [2025
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Nekopoi APK 2025 free lastest update
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
System and Network Administraation Chapter 3

OSGi introduction

  • 1. An introduction to the OSGi Framework and Specifications OSGI Dario Bonino, Ph.D bonino@ismb.it
  • 2. • Introduction • Flash History • What is it? • Specifications • Sets • Framework Implementations • OSGi for beginners • Bundle • Bundle lifecycle • Hello bundle! • Services • Publish services • Use services Agenda
  • 3. INTRODUCTION Flash introduction to the main OSGi features, with a hint on history
  • 4. • Founded in March 1999 • Formerly an acronym for Open Services Gateway initiative (OSGi), now OSGi Alliance. • Several versions starting from early 200x • … • v4.1 – 2007 • v4.2 – 2009 • v4.3 – 2011 • v5.0 – 2012 • v6.0 – 2015 The Origin
  • 5. • Founded in March 1999 • Formerly an acronym for Open Services Gateway initiative (OSGi), now OSGi Alliance. • Several versions starting from early 200x • … • v4.1 – 2007 • v4.2 – 2009 • v4.3 – 2011 • v5.0 – 2012 • v6.0 – 2015 The Origin Sorry for the SPRING (breakers)… No more space for claims about maturity: SPRING first version was released on 2002 (almost 3 years later)
  • 6. • Strategic members • Adobe, NTT, Deutsche Telekom, Oracle, Huawei Technologies Inc., Paremus Ltd., IBM, ProSyst Software, Liferay, Software AG. • Principal members • Cloudyle, Makewave, Luminis, Sumitomo Electric Industries Ltd. • Contributing associates • Bitreactive AS, Orange, Eclipse Foundation Inc, Red Hat, Eurotech, Sagecom SAS, Hitachi, Schneider Electric, Intuit Inc., Telecom Italia S.p.A., Mitsubishi Electric, TIBCO, NEC, Unify GmbH & Co. KG • Supporters • >40 The Alliance
  • 7. “The OSGi technology is a set of specifications that define a dynamic component system for Java” “Specifications enable a development model where applications are dynamically composed of many different and reusable components” “Components hide their implementations from other components while communicating through services” Definition
  • 8. • Set of specifications • Component – based design and development model • Opaque modules communicating through services • SOA (Service Oriented Architecture) • Loosely coupled Definition rephrased
  • 9. • Modular architecture • Component-based systems • Off-the-shelf components available • Embedded to large scale deployments • Mature • Widely adopted Features
  • 10. • Reduces complexity • loose coupling between modules, i.e., bundles • Reuse • very easy to use any third party components • Real world • dynamic bundle update, dynamic addition/removal of services, etc. • Easy deployment • specifies how components are installed and managed Benefits (1/2)
  • 11. • Adaptive • modules can be composed in almost any fashion • Versioning support • Dive into jar version hell through dependency management • Small • v4.0 core -> 300KByte jar • … many others Benefits (2/2)
  • 13. • At the beginning they were 2… • OSGi Core • OSGi Compendium • Now (v6.0) they are 3+ • OSGi Core • OSGi Compendium • OSGi Residential • OSGi Enterprise Specification Sets
  • 14. “The Framework forms the core of the OSGi Specifications. It provides a general-purpose, secure, and managed Java framework that supports the deployment of extensible and downloadable applications known as bundles.” Core - Framework
  • 15. • Open Source • Eclipse Equinox (!) • Apache Felix • Apache Karaf • Knoplerfish • … • Commercial • ProSyst • … Framework implementations
  • 16. • Security Layer • Module Layer • Lyfecycle Layer • Service Layer • Actual services (Bundles) Framework Layers
  • 17. • Based on Java2 security • Adds some constraint • Fixes some “blanks” in the original Java2 specification OSGi Core specifications, v6.0 – p.17 Security Layer
  • 18. • Defines a modularization model for Java • Rules for • Sharing packages between “Bundles” • Hiding packages from other “Bundles” • Can be used without upper layers • Lyfe cycle • Service OSGi Core Specification, v6.0 – p.31 Module Layer
  • 19. • Provides a lifecycle API to bundles • Defines how bundles are: • Started • Stopped • Installed • Updated • Uninstalled • Defines the APIs for a management bundle controlling the OSGi Framework • Requires the Module Layer • Security is optional OSGi Core Specification, v6.0 – p.93 Lyfe Cycle Layer
  • 20. • Dynamic, concise, consistent model for Java Bundles developers • Decouples service specification (Java Interface) from implementation(s) • Allows binding services basing on Interfaces, only • Specific service implementations selected at runtime (through the Framework Registry) OSGi Core Specification, v6.0 – p.127 Service Layer
  • 22. BUNDLES Hands on introduction to bundles and bundle development
  • 23. • Single unit of Modularization • Java classes + other resources • Can share packages with other bundles • Export • Import • Deployed as Java Archive file • JAR • (Zip encoded) Bundle (1/2)
  • 24. • Content • Java classes + resources needed to provide a given functionality • Manifest file • Describes the JAR content • Provides information about the bundle • E.g., imported / exported packages • Documentation in • OSGI-OPT folder • [See later] Declarative service specification in • OSGI-INF folder Bundle (2/2)
  • 25. • Bundles • Library Bundles • Only provide library functions through the export-package header • Fragment Bundles • Can be attached to one or more host bundles • Treated as part of the host bundle • Extension Bundles • Deliver optional parts of the framework implementation • Provide functionality that must reside on the boot class path • Cannot be provided by the normal import / export clauses Types of Bundles
  • 26. • Part of the Life Cycle Layer • Defines how a bundle is • Installed • Updated • Uninstalled Bundle lifecycle
  • 27. • A Bundle is started through its • Bundle Activator • The Bundle Activator is identified by the • Bundle-Activator header in the Bundle manifest • The Bundle Activator class must implement the BundleActivator interface • start(BundleContext ctx) • stop(BundleContext ctx) *REMINDER: WE WILL USE DECLARATIVE SERVICES (OSGI COMPENDIUM) Starting Bundles
  • 28. import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class Activator implements BundleActivator { public void start(BundleContext context) { System.out.println("Starting bundle"); } public void stop(BundleContext context) { System.out.println("Stopping bundle"); } } Activator Example
  • 29. • Bundle identifier • A long number • Assigned by the framework • Typically ascending order of installation • Bundle location • Assigned by the management agent • URL to the bundle JAR file (not mandatory) • Unique in a framework instance • Bundle Symbolic Name and Bundle Version • Assigned by the developer • Semantic versioning • Naming convention <-> Java package naming (free indeed) Bundle Identification (1/2)
  • 30. • Bundle identifier • A long number • Assigned by the framework • Typically in ascending order of installation • Bundle location • Assigned by the management agent • URL to the bundle JAR file (not mandatory) • Unique in a framework instance • Bundle Symbolic Name and Bundle Version • Assigned by the developer • Semantic versioning • Naming convention <-> Java package naming (free indeed) Bundle Identification (2/2)
  • 32. Bundle States The Bundle has been successfully installed
  • 33. Bundle States All Java classes are available (ready to be started or just stopped)
  • 34. Bundle States The bundle is being started. The Bundle Activator start() will be called.
  • 35. Bundle States The bundle has been successfully activated and is running. start() has been called and returned.
  • 36. Bundle States The bundle is being stopped. The stop() method has been called but it has not yet returned
  • 37. Bundle States The bundle has been uninstalled. It cannot move into another state.
  • 38. ECLIPSE EXAMPLE Hello World bundle in Eclipse Equinox
  • 39. • Download Eclipse RCP • Install Eclipse RCP • Run Eclipse Environment Set-up
  • 40. • File > New > New Plugin Project Hello World! (1/7)
  • 41. • Type the bundle ID (reverse Java package notation) • Version (Semantic versioning) • 1.0.0.(qualifier) • Name of the project/bundle • Hello World OSGi • Define the activator class • It.ismb.pert.hello.HelloActivat or • Hit on finish Hello World! (2/7)
  • 42. Hello World! (3/7) Structure and Manifest, after the initial project creation
  • 43. • Write the activator body • Simply print on the console • “Hello OSGi world, I’m active now!” on activation • “Goodbye OSGi world!” on deactivation Hello World! (4/7)
  • 47. BUNDLES - RELOADED More deep discussion on bundles
  • 48. • Dependency on external entities • Requirements • Import-Package • Capabilities • Export-Package Requirements and Capabilities
  • 49. • Resolving is the process that creates a wiring between bundles • Any mandatory requirement must be matched to at least one capability in the same namespace provided by any of the resolved bundles, including itself and the system bundle. • The required execution environments as defined by the Bundle- RequiredExecutionEnvironment header. • Native code • Import and export packages (the Dynamic Import-Package header is ignored in this phase) • Required bundles, which import all exported packages from a bundle as defined in Requiring Bundles on page 79. • Fragments, which provide their contents and definitions to the host as defined in . Resolving (1/2)
  • 50. • A bundle can be resolved only if: • Execution Environment • The VM implements at least one of the execution environments listed in • Bundle- RequiredExecutionEnviron ment • Native Code • The Native code dependencies must be resolved • Bundle-NativeCode • A bundle can be resolved if • All its mandatory requirements are satisfied • All its mandatory imports are wired • All its mandatory required bundles are available and their exports wired Resolving (2/2)
  • 51. • A wire is only created if • The importer's version range matches the exporter's version • The importer specifies all mandatory attributes from the exporter • All the importer's attributes match the attributes of the corresponding exporter. • Implied packages referring to the same package as the wire are wired to the same exporter • The wire is connected to a valid exporter. Wiring (1/2)
  • 52. • Preferences in wiring • A resolved exporter must be preferred over an unresolved exporter. • An exporter with a higher version is preferred over an exporter with a lower version. • An exporter with a lower bundle ID is preferred over a bundle with a higher ID. Wiring (2/2)
  • 54. • A bundle can be started • Calling one of its start methods • Automatically by the framework if • Is ready • The bundle is resolved • The bundle start level is met (optional) • Autostart is set • Stopped (the bundle should not start) • Started with eager activation (started once ready and eagerly activated) • Started with a declared activation (started once ready, according to the declared activation policy) Starting a bundle
  • 55. • Eager activation • Started as soon as possible (i.e. when resolved) • Lazy activation • Must not be activated until it receives the first request to load a class • Class can be loaded • through normal class loading or • by calling the Bundle loadClass method Bundle Activation policies (1/2)
  • 57. • The framework is represented as a bundle • System Bundle • Allows to register services that can be used by other bundles • Has always bundle ID=0 • getLocation returns “System Bundle” • Symbolic Name unique for a specific version • Cannot be managed as normal bundles • Start – the system bundle is already started • Stop – shutdown the framework on another thread • Update – stops and restarts the framework on another thread • Uninstall – throws a BundleException since it cannot be uninstalled The System bundle
  • 58. • The Life Cycle Layer supports/generates • Framework events • Framework has started, changed start level, packages have been refreshed, errors occured • Bundle events • Changes in the lifecycle of bundles • Listeners can be associated to all events • Synchronous • In the event loop (CAREFUL!) • Asynchronous Events
  • 59. • INSTALLED • Sent after a bundle is installed. The state is now Bundle INSTALLED state. • RESOLVED • Sent when the Framework has resolved a bundle. The state is now the Bundle RESOLVED state. • LAZY_ACTIVATION • The bundle has specified an activation policy; its activation is deferred to a later point in time. The state is set to the Bundle STARTING state. This is only sent to SynchronousBundleListener objects. • STARTING • Sent when the Framework is about to activate a bundle. This is only sent to SynchronousBundleListener objects. The state is now the Bundle STARTING state. • STARTED • Sent when the Framework has started a bundle. The state is now the Bundle ACTIVE state. • STOPPING • Sent when the Framework is about to stop a bundle or the start method of the Bundle Activator has thrown an exception and the bundle is stopped. This event indicates that the Bundle Context will be destroyed. This event is only sent to SynchronousBundleListener object • STOPPED • Sent when the Framework has stopped a bundle. • UNINSTALLED • Sent when the Framework has uninstalled a bundle • UNRESOLVED • Sent when the Framework detects that a bundle becomes unresolved; this could happen when the bundle is refreshed or updated. • UPDATED • Sent after a bundle is updated. Bundle events
  • 60. • ERROR • Important error that requires the immediate attention of an operator. • INFO • General information that is of interest in special situations. • PACKAGES_REFRESHED • The Framework has refreshed the packages. • STARTED • The Framework has performed all initialization and is running in normal mode. • STARTLEVEL_CHANGED • Is sent by the Framework after a new start level has been set and processed. • STOPPED • Sent by the Framework because of a stop operation on the system bundle. • STOPPED_BOOTCLASSPATH_MODIFIED • Sent by the Framework because of a stop operation on the system bundle and a boot class path extension bundle has been installed or updated. • STOPPED_UPDATE • Sent by the Framework because of an update operation on the system bundle. The Framework will be restarted after this event is fired. • WARNING • A warning to the operator that is not crucial but may indicate a potential error situation. • WAIT_TIMEDOUT • Returned from the waitForStop method when the Framework did not stop before the given wait time-out expired. Framework events
  • 61. SERVICES OSGi Services – Quick introduction
  • 62. • Defined at the Service Layer • Publish, find and bind model • “A service is a normal Java object that is registered under one or more Java interfaces within the service registry.“ • “Bundles can register services, search for them, or receive notifications when their registration state changes.” OSGi Core Specification v6.0, p. 127 Service
  • 63. • Service • An object registered with the service registry under one or more interfaces together with properties. The service can be discovered and used by bundles. • Service Registry • Holds the service registrations. • Service Reference • A reference to a service. Provides access to the service's properties but not the actual service object. The service object must be acquired through a bundle's Bundle Context. Terminology (1/4)
  • 64. • Service Registration • The receipt provided when a service is registered. The service registration allows the update of the service properties and the unregistration of the service. • Service Permission • The permission to use an interface name when registering or using a service. • Service Scope • Indicates how service objects are obtained when requesting a service object. The following service scopes are defined: singleton, bundle, and prototype. The default service scope is singleton. Terminology (2/4)
  • 65. • Service Factory • A facility to let the registering bundle customize the service object for each using bundle. When using a Service Factory, the service scope of the service is bundle. • Prototype Service Factory • A facility to let the registering bundle customize the service object for each caller. When using a Prototype Service Factory, the service scope of the service is prototype. • Service Objects • A facility to let the using bundle obtain multiple service objects for a service with prototype service scope. • Service Listener • A listener to Service Events. Terminology (3/4)
  • 66. • Service Event • An event holding information about the registration, modification, or unregistration of a service object. • Filter • An object that implements a simple but powerful filter language. It can select on properties. • Invalid Syntax Exception • The exception thrown when a filter expression contains an error. Terminology (4/4)
  • 67. • Semantically defined by a Java Interface • Service Interface • As few implementation details as possible (in theory shall be independent from implementation) • Common interfaces are already specified by OSGi specifications (see Compendium) • Implemented by a Java Object • Service Object • Owned by a bundle • Runs within a bundle Service – In Short
  • 68. • The bundle must register the service object within the Framework Registry • Dependencies between bundles • Offering (owning) a service • Using a service Are directly managed by the Framework. • For example • When a bundle is stopped, de-register all the services “owned” by the bundle Find & Bind (1/2)
  • 69. • The Framework maps Services (Interfaces) with underlying Service Objects • Event mechanism for detecting when service are: • Registered • Modified • Unregistered Find & Bind (2/2)
  • 70. • Used to refer to a Service Object • Decoupling -> No dynamic dependencies for information-only • Can be passed / stored to/within other bundles without setting dynamic bundle dependency • Encapsulates the properties and meta-information about the represented Service Object • Properties and meta-information can be queried Service Reference (1/2)
  • 71. • Can be obtained • From the Framework • Querying the service registry • From the registration process • Through the service registration • Acquired references are “tracked” by the framework • See getting / un-getting services Service Reference (2/2)
  • 72. • The developer • implements a service by • Defining the Service Interface • Creating a Service Object by implementing the Service Interface • Registering the interface within the framework • Searches for interfaces within the Framework by • Interface name (e.g., fully qualified) • Filter on registration properties (LDAP syntax) Service Interfaces
  • 73. • Services must be registered in the Framework registry • Can be done through • Bundle Context • Every registered service has a unique • ServiceRegistration object • Many • ServiceReference objects pointing at it Registering Services (1/4)
  • 74. • registerService(String,Object,Dictionary) • For a service object registered under a single service interface. • registerService(String[],Object,Dictionary) • For a service object registered under multiple service interfaces. • registerService(Class,Object,Dictionary) • For a service object registered under a single service interface using the class object for the interface name. • The Framework MUST ensure that objects registered as Services actually implement the Service Interface. Registering Services (2/4)
  • 75. • Upon successful registration the Framework must return a ServiceRegistration object to the caller. • A service object can be unregistered only by the holder of its ServiceRegistration object • Every successful service object registration must yield a unique ServiceRegistration object even if the same service object is registered multiple times. Registering Services (3/4)
  • 76. • Using the ServiceRegistration object is the only way to reliably change the service's properties after it has been registered • Modifying a service's Dictionary object after the service object is registered may not have any effect on the service's properties. Registering Services (4/4)
  • 77. • Key-Value pairs • Key MUST be a String • Value MUST be “recognized” by Filter objects • Keys are CASE INSENSITIVE • Properties shall provide information about the Service • Properties shall never taker part in the actual function of the Service • All properties share a single namespace in the Framework service registry. • use descriptive names or formal definitions to prevent conflicts. • Several OSGi specifications reserve parts of this namespace. • service. * • objectClass Service Properties
  • 82. • Same as the one used for the OSGi Hello World • Design & implement a service for printing messages on the OSGi console • Interface: ConsoleLogger • Methods: log(String message) HINT – after the example look at the OSGi LogService Set-up
  • 85. • First: • Prepare the service “holder” variable • Prepare the service registration ”holder”, will be used for unregistering the service Note: this is an oversimplified implementation for teaching purposes Service Registration (1/3)
  • 86. • Create an instance of the Service, i.e., the service implementation • Prepare the service description properties, e.g., the service PID • Register the service using the interface class • (can be done using the interface fully qualified name) Service Registration (2/3)
  • 87. • On de-activation, unregister the service Service (Un)Registration (3/3)
  • 88. • Everything done !?!?! • No! • The service shall be exported to allow other bundles using it • The Java interface must be made available to other bundles • Where? In the MANIFEST Service Registration (4/3)
  • 90. • You might have noticed that • Only packages can be exported • No way for single classes • Therefore • Particular care shall be devoted to package design • Our example is “BAD” as the activator and the service interface lie in the same package - > we will export also the activator, which is undesirable Last remarks
  • 91. • No effect! • Right! Nobody in the framework is using our service • OSGi command line utils: • SS • Provides the list of available bundles together with their state • Services • Lists the services currently registered in the framework {it.ismb.pert.service.console.logger.service.ConsoleLogger}={service. pid=it.ismb.pert.service.console.logger.impl.SystemConsoleLogger, service.id=46, service.bundleid=4, service.scope=singleton} "Registered by bundle:" it.ismb.pert.service.console.logger_1.0.0 [4] "No bundles using service." Run and check!
  • 92. • No effect! • Right! Nobody in the framework is using our service • OSGi command line utils: • SS • Provides the list of available bundles together with their state • Services • Lists the services currently registered in the framework {it.ismb.pert.service.console.logger.service.ConsoleLogger}={service. pid=it.ismb.pert.service.console.logger.impl.SystemConsoleLogger, service.id=46, service.bundleid=4, service.scope=singleton} "Registered by bundle:" it.ismb.pert.service.console.logger_1.0.0 [4] "No bundles using service." Run and check! !
  • 93. SERVICES - RELOADED Getting & tracking services
  • 94. • Services published by bundles remain unused until some other bundle requires / gets the service • Two ways for getting services • BundleContext.getService(ServiceReference) • This method should be used if the using bundle only needs a single service object. • ServiceObjects.getService() • This method should be used if the service has SCOPE_PROTOTYPE scope and the using bundle needs multiple service objects. Getting Services (1/2)
  • 95. • BundleContext.getService(ServiceReference) method • returns an object that implements the interfaces as defined by the objectClass property. • A bundle making multiple calls to this method, without releasing the service object, will receive the same service object. Getting Services (2/2)
  • 96. • This method has the following characteristics: • Returns null if the underlying service object has been unregistered. • Determines if the caller has ServicePermission to get a service object associated with the specified Service Reference. • Increments the usage count of the service by one for this BundleContext object. • If the service has SCOPE_SINGLETON scope then the registered service object is returned. • Special behavior for other scope types (Factory) BundleContext.getService
  • 98. • Write a bundle that exploits our ConsoleLogger service to print random numbers on the screen Set-up
  • 100. • Add a dependence on the package holding the ConsoleLogger interface Dependencies
  • 101. • Recurrent task • Best on a separate thread • Must close cleanly • Take care of creation / disposal of the thread in the activator Random Generator
  • 102. • Starts the generator thread • Gets the service reference and then the service instance using the bundle context • (Note this!, will be changed…) Activator (1/2)
  • 103. • Stop cleanly: • Stop the thread • Wait for the thread to gracefully close • UNGET the service! Activator (2/2)
  • 104. • Test • Does it log random numbers? • Identify the bundle ID for the logger and for the random number generator • Stop the generator, is stop clean? • Stop the console logger, what happens? • Why the random number generator still works when we stop the console logger service? Run the services
  • 106. • The RandomGenerator Thread keeps a reference to the actual service class (console logger) • Any Java object is kept alive until there is a reference pointing at it • The logger is kept “alive” untile the generator uses it • This should be avoided, in our case: • No logger, no party! Problem analysis
  • 107. • Use service references!!! • React to service availability Solution (1/2)
  • 110. • Many many features: • Service Tracker • To track / react to service availability • Permissions • Etc. • See OSGi Core Specifications v6.0 What else?
  • 111. • Write a bundle that generates a clock signal at 1Hz • Exploit / modify the ConsoleLogger bundle to print the current time, generated by the clock bundle on the console. Exercise