SlideShare a Scribd company logo
Automatically Managing Service Dependencies in an OSGi Environment - Marcel Offermans, Senior Software Engineer, Luminis
Automatically Managing
Service Dependencies in
an OSGi Environment
Marcel OffermansMarcel Offermans
About me...About me...
•• Marcel OffermansMarcel Offermans
•• Senior Software Engineer at luminisSenior Software Engineer at luminis®®
•• Our mission is to provide knowledge and products toOur mission is to provide knowledge and products to
organisations who create software intensiveorganisations who create software intensive
products, to help them adopt software technologyproducts, to help them adopt software technology
innovations.innovations.
•• We use OSGi at the core of the architecture forWe use OSGi at the core of the architecture for
managable, embedded systems.managable, embedded systems.
AgendaAgenda
•• Dependencies in OSGiDependencies in OSGi
•• Goals for a dependency managerGoals for a dependency manager
•• Architecture, illustrated by examplesArchitecture, illustrated by examples
•• ConclusionsConclusions
Dependencies in OSGiDependencies in OSGi
•• Package dependencies, which in R4 have beenPackage dependencies, which in R4 have been
extended with requiring, fragment and extensionextended with requiring, fragment and extension
bundles. These are all resolved in the module layer.bundles. These are all resolved in the module layer.
•• Service dependencies, which are resolved in theService dependencies, which are resolved in the
service layer.service layer.
Service DependenciesService Dependencies
•• Need to be managed at runtimeNeed to be managed at runtime
•• The OSGi framework offers basic tools:The OSGi framework offers basic tools:
–– Service listenerService listener
–– Service trackerService tracker
•• Third party tools:Third party tools:
–– Service binderService binder
–– ...probably there are more :)...probably there are more :)
Goals for the Dependency ManagerGoals for the Dependency Manager
•• Minimize the amount of code that needs to beMinimize the amount of code that needs to be
written.written.
•• Provide a clean separation between the serviceProvide a clean separation between the service
implementation andimplementation and ““glueglue”” code.code.
•• Be dynamic. Allow the programmer to add servicesBe dynamic. Allow the programmer to add services
and dependencies at any time.and dependencies at any time.
Types of dependenciesTypes of dependencies
•• Required dependencies, which need to be resolvedRequired dependencies, which need to be resolved
before the service can work at all.before the service can work at all.
•• Optional dependencies, which are used whenOptional dependencies, which are used when
available but are not essential for the service toavailable but are not essential for the service to
work.work.
Architecture: state diagramArchitecture: state diagram
Standard use caseStandard use case
•• A service with two required dependencies and oneA service with two required dependencies and one
optional one.optional one.
public class Activator extends DependencyActivatorBase {
public void init(BundleContext bc, DependencyManager dm) {
dm.add(createService()
.setInterface(MyService.class.getName(), null)
.setImplementation(MyServiceImpl.class)
.add(createServiceDependency()
.setService(HttpService.class)
.setRequired(true))
.add(createServiceDependency()
.setService(SomeOtherService.class)
.setRequired(true))
.add(createServiceDependency()
.setService(LogService.class)
.setRequired(false))
);
}
public void destroy(BundleContext bc, DependencyManager dm) {
}
}
Standard use caseStandard use case
•• Implementation instantiated lazily, invokes callbacksImplementation instantiated lazily, invokes callbacks
as part of lifeas part of life--cycle: init, start, stop, destroycycle: init, start, stop, destroy
•• Dependencies are injected using reflectionDependencies are injected using reflection
•• Null object pattern used for optional dependenciesNull object pattern used for optional dependencies
public class MyServiceImpl implements MyService {
private HttpService httpService;
private SomeOtherService someOtherService;
private LogService logService;
public void start() {
logService.log(LogService.LOG_INFO, “Starting”);
}
public void stop() {
logService.log(LogService.LOG_INFO, “Stopping”);
}
}
Code size reduction:Code size reduction:
public class Activator implements BundleActivator {
private BundleContext context;
private ServiceRegistration registration;
private AudioBroadcaster audioBroadcaster;
private AudioSource audioSource;
private AudioEncoder audioEncoder;
private ServiceTracker audioSourceTracker;
private ServiceTracker audioEncoderTracker;
private ServiceTracker logTracker;
public void start(BundleContext context) throws Exception {
this.context = context;
audioSourceTracker = new ServiceTracker(context,
AudioSource.class.getName(), customizer);
audioEncoderTracker = new ServiceTracker(context,
AudioEncoder.class.getName(), customizer);
logTracker = new ServiceTracker(context, LogService.class.getName(),
null);
logTracker.open();
audioSourceTracker.open();
audioEncoderTracker.open();
}
public void stop(BundleContext context) throws Exception {
audioSourceTracker.close();
audioEncoderTracker.close();
logTracker.close();
}
private ServiceTrackerCustomizer customizer =
new ServiceTrackerCustomizer() {
public Object addingService(ServiceReference reference) {
Object service = context.getService(reference);
setService(reference, service);
return service;
}
private void setService(ServiceReference reference, Object service) {
// update service references
Object objectclass = reference.getProperty(Constants.OBJECTCLASS);
if (objectclass instanceof String) {
String name = (String) objectclass;
setNamedService(service, name);
}
if (objectclass instanceof String[]) {
String[] names = (String[]) objectclass;
for (int i = 0; i < names.length; i++) {
setNamedService(service, names[i]);
}
}
// register service if necessary
if ((registration == null) && (audioSource != null)
&& (audioEncoder != null)) {
// instantiate the implementation and pass the services
audioBroadcaster = new AudioBroadcasterImpl(audioSource,
audioEncoder, logTracker);
registration = context.registerService(
AudioBroadcaster.class.getName(), audioBroadcaster, null);
}
// unregister service if necessary
if (((audioSource == null) || (audioEncoder == null))
&& (registration != null)) {
registration.unregister();
registration = null;
audioBroadcaster = null;
}
}
private void setNamedService(Object service, String name) {
if (AudioEncoder.class.getName().equals(name)) {
audioEncoder = (AudioEncoder) service;
}
else if (AudioSource.class.getName().equals(name)) {
audioSource = (AudioSource) service;
}
}
public void modifiedService(ServiceReference reference,
Object service) {
}
public void removedService(ServiceReference reference,
Object service) {
setService(reference, null);
context.ungetService(reference);
}
};
}
public class Activator extends DependencyActivatorBase {
public void init(BundleContext ctx, DependencyManager manager)
throws Exception {
manager.add(createService()
.setInterface(AudioBroadcaster.class.getName(), null)
.setImplementation(AudioBroadcasterImpl.class));
.add(createServiceDependency()
.setService(AudioSource.class, null)
.setRequired(true))
.add(createServiceDependency()
.setService(AudioEncoder.class, null)
.setRequired(true))
.add(createServiceDependency()
.setService(LogService.class, null)
.setRequired(false))
}
public void destroy(BundleContext ctx, DependencyManager manager)
throws Exception {
}
}
Tracking dependenciesTracking dependencies
•• Setting up a service with an optional dependencySetting up a service with an optional dependency
that can track multiple dependent services:that can track multiple dependent services:
public class Activator extends DependencyActivatorBase {
public void init(BundleContext bc, DependencyManager dm) {
dm.add(createService()
.setImplementation(DeviceTracker.class)
.add(createServiceDependency()
.setService(Device.class)
.setAutoConfig(false)
.setCallbacks(“addDevice”, “removeDevice”)
.setRequired(false))
);
}
public void destroy(BundleContext bc, DependencyManager dm) {
}
}
Tracking dependenciesTracking dependencies
•• Implementation:Implementation:
public class DeviceTracker {
private List devs = new ArrayList();
public void addDevice(ServiceReference ref, Object srv) {
devs.add(srv);
}
public void removeDevice(ServiceReference ref, Object srv) {
devs.remove(srv);
}
}
Architecture: class diagramArchitecture: class diagram
Other features:Other features:
•• Injection of BundleContext and ServiceRegistrationInjection of BundleContext and ServiceRegistration
•• New services and dependencies can be added orNew services and dependencies can be added or
removed dynamicallyremoved dynamically
•• Callbacks are configurable and will look for methodsCallbacks are configurable and will look for methods
withwith ““suitablesuitable”” signaturessignatures
•• Service listeners allow you to track the state of aService listeners allow you to track the state of a
serviceservice
•• Manager allows for addition of customizedManager allows for addition of customized
dependencies (so you're not limited to servicedependencies (so you're not limited to service
dependencies)dependencies)
ConclusionsConclusions
•• Clean separation between service implementationClean separation between service implementation
and dependency management, you can use a POJOand dependency management, you can use a POJO
if you wantif you want
•• Dynamic nature of dependencies has proven to beDynamic nature of dependencies has proven to be
useful in several scenariosuseful in several scenarios
•• Substantial code reduction is realized whenSubstantial code reduction is realized when
compared to using service trackerscompared to using service trackers
Further infoFurther info
•• Contacting me:Contacting me:
ee--mail: marcel.offermans@luminis.nlmail: marcel.offermans@luminis.nl
ICQ: 22100024ICQ: 22100024
Skype: marcel_offermansSkype: marcel_offermans
•• Article:Article:
http://www.osgi.org/news_events/articles.asp?section=4http://www.osgi.org/news_events/articles.asp?section=4
•• Development site:Development site:
https://opensource.luminis.net/confluence/x/PwEhttps://opensource.luminis.net/confluence/x/PwE

More Related Content

PDF
Spring Boot Revisited with KoFu and JaFu
PDF
OSGi Cloud Ecosystems (EclipseCon 2013)
PDF
Maximize the power of OSGi
PPTX
Open Stack compute-service-nova
PDF
Openstack 101
PPTX
Openstack in 10 mins
PDF
OpenStack Super Bootcamp.pdf
PDF
What Is OpenStack | OpenStack Tutorial For Beginners | OpenStack Training | E...
Spring Boot Revisited with KoFu and JaFu
OSGi Cloud Ecosystems (EclipseCon 2013)
Maximize the power of OSGi
Open Stack compute-service-nova
Openstack 101
Openstack in 10 mins
OpenStack Super Bootcamp.pdf
What Is OpenStack | OpenStack Tutorial For Beginners | OpenStack Training | E...

What's hot (20)

PPTX
Quick overview of Openstack architecture
PPTX
Introduction to Kubernetes
PPTX
Hitchhiker's Guide to Open Source Cloud Computing
PPTX
Kubered -Recipes for C2 Operations on Kubernetes
PPTX
Introduction to OpenStack Architecture (Grizzly Edition)
PDF
VNG/IRD - Cloud computing & Openstack discussion 3/5/2014
PPTX
OpenStack Architecture and Use Cases
PDF
OpenStack Architecture
PDF
Kogito: cloud native business automation
PPTX
OSCON 2013 - The Hitchiker’s Guide to Open Source Cloud Computing
PDF
OpenStack: Security Beyond Firewalls
PDF
2012 CloudStack Design Camp in Taiwan--- CloudStack Overview-2
PDF
What's cool in the new and updated OSGi Specs (EclipseCon 2014)
PPTX
Service Discovery using etcd, Consul and Kubernetes
PDF
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
PDF
OpenStack keystone identity service
PDF
BeJUG Meetup - What's coming in the OSGi R7 Specification
PDF
Weaving Through the Mesh: Making Sense of Istio and Overlapping Technologies
KEY
JBoss World 2010
PDF
Webinar "Introduction to OpenStack"
Quick overview of Openstack architecture
Introduction to Kubernetes
Hitchhiker's Guide to Open Source Cloud Computing
Kubered -Recipes for C2 Operations on Kubernetes
Introduction to OpenStack Architecture (Grizzly Edition)
VNG/IRD - Cloud computing & Openstack discussion 3/5/2014
OpenStack Architecture and Use Cases
OpenStack Architecture
Kogito: cloud native business automation
OSCON 2013 - The Hitchiker’s Guide to Open Source Cloud Computing
OpenStack: Security Beyond Firewalls
2012 CloudStack Design Camp in Taiwan--- CloudStack Overview-2
What's cool in the new and updated OSGi Specs (EclipseCon 2014)
Service Discovery using etcd, Consul and Kubernetes
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
OpenStack keystone identity service
BeJUG Meetup - What's coming in the OSGi R7 Specification
Weaving Through the Mesh: Making Sense of Istio and Overlapping Technologies
JBoss World 2010
Webinar "Introduction to OpenStack"
Ad

Similar to Automatically Managing Service Dependencies in an OSGi Environment - Marcel Offermans, Senior Software Engineer, Luminis (20)

PDF
Dependencies, dependencies, dependencies
PDF
The Ultimate Dependency Manager Shootout (QCon NY 2014)
PDF
OSGi bootcamp - part 2
KEY
Beyond OSGi Software Architecture
PPT
Enabling modularization through OSGi and SpringDM
PDF
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
PDF
The ultimate dependency manager shoot out - X Uiterlinden & S Mak
PPT
The Web on OSGi: Here's How
ODP
Java Tech & Tools | OSGi Best Practices | Emily Jiang
PDF
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
PPT
Service oriented component model
PDF
Dependency Injection
PDF
OSGi In Anger - Tara Simpson
PPTX
OSGi Training for Carbon Developers
PPT
Os gi introduction made by Ly MInh Phuong-SOC team
ODP
Peaberry - Blending Services And Extensions
PDF
W-JAX 08 - Declarative Services versus Spring Dynamic Modules
PPTX
Introduction to OSGi - Part-2
PDF
Microservices and the Art of Taming the Dependency Hell Monster
PDF
A toolbox for statical analysis and transformation of OSGi bundles
Dependencies, dependencies, dependencies
The Ultimate Dependency Manager Shootout (QCon NY 2014)
OSGi bootcamp - part 2
Beyond OSGi Software Architecture
Enabling modularization through OSGi and SpringDM
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
The ultimate dependency manager shoot out - X Uiterlinden & S Mak
The Web on OSGi: Here's How
Java Tech & Tools | OSGi Best Practices | Emily Jiang
iPOJO - The Simple Life - Richard Hall, Visiting Assistant Professor at Tufts...
Service oriented component model
Dependency Injection
OSGi In Anger - Tara Simpson
OSGi Training for Carbon Developers
Os gi introduction made by Ly MInh Phuong-SOC team
Peaberry - Blending Services And Extensions
W-JAX 08 - Declarative Services versus Spring Dynamic Modules
Introduction to OSGi - Part-2
Microservices and the Art of Taming the Dependency Hell Monster
A toolbox for statical analysis and transformation of OSGi bundles
Ad

More from mfrancis (20)

PDF
Eclipse Modeling Framework and plain OSGi the easy way - Mark Hoffman (Data I...
PDF
OSGi and Java 9+ - BJ Hargrave (IBM)
PDF
Simplify Web UX Coding using OSGi Modularity Magic - Paul Fraser (A2Z Living)
PDF
OSGi for the data centre - Connecting OSGi to Kubernetes - Frank Lyaruu
PDF
Remote Management and Monitoring of Distributed OSGi Applications - Tim Verbe...
PDF
OSGi with Docker - a powerful way to develop Java systems - Udo Hafermann (So...
PDF
A real world use case with OSGi R7 - Jurgen Albert (Data In Motion Consulting...
PDF
OSGi Feature Model - Where Art Thou - David Bosschaert (Adobe)
PDF
Migrating from PDE to Bndtools in Practice - Amit Kumar Mondal (Deutsche Tele...
PDF
OSGi CDI Integration Specification - Ray Augé (Liferay)
PDF
How OSGi drives cross-sector energy management - Jörn Tümmler (SMA Solar Tech...
PDF
Improved developer productivity thanks to Maven and OSGi - Lukasz Dywicki (Co...
PDF
It Was Twenty Years Ago Today - Building an OSGi based Smart Home System - Ch...
PDF
Popular patterns revisited on OSGi - Christian Schneider (Adobe)
PDF
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
PDF
OSG(a)i: because AI needs a runtime - Tim Verbelen (imec)
PDF
Flying to Jupiter with OSGi - Tony Walsh (ESA) & Hristo Indzhov (Telespazio V...
PDF
MicroProfile, OSGi was meant for this - Ray Auge (Liferay)
PDF
Prototyping IoT systems with a hybrid OSGi & Node-RED platform - Bruce Jackso...
PDF
How to connect your OSGi application - Dirk Fauth (Bosch)
Eclipse Modeling Framework and plain OSGi the easy way - Mark Hoffman (Data I...
OSGi and Java 9+ - BJ Hargrave (IBM)
Simplify Web UX Coding using OSGi Modularity Magic - Paul Fraser (A2Z Living)
OSGi for the data centre - Connecting OSGi to Kubernetes - Frank Lyaruu
Remote Management and Monitoring of Distributed OSGi Applications - Tim Verbe...
OSGi with Docker - a powerful way to develop Java systems - Udo Hafermann (So...
A real world use case with OSGi R7 - Jurgen Albert (Data In Motion Consulting...
OSGi Feature Model - Where Art Thou - David Bosschaert (Adobe)
Migrating from PDE to Bndtools in Practice - Amit Kumar Mondal (Deutsche Tele...
OSGi CDI Integration Specification - Ray Augé (Liferay)
How OSGi drives cross-sector energy management - Jörn Tümmler (SMA Solar Tech...
Improved developer productivity thanks to Maven and OSGi - Lukasz Dywicki (Co...
It Was Twenty Years Ago Today - Building an OSGi based Smart Home System - Ch...
Popular patterns revisited on OSGi - Christian Schneider (Adobe)
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
OSG(a)i: because AI needs a runtime - Tim Verbelen (imec)
Flying to Jupiter with OSGi - Tony Walsh (ESA) & Hristo Indzhov (Telespazio V...
MicroProfile, OSGi was meant for this - Ray Auge (Liferay)
Prototyping IoT systems with a hybrid OSGi & Node-RED platform - Bruce Jackso...
How to connect your OSGi application - Dirk Fauth (Bosch)

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
KodekX | Application Modernization Development
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Big Data Technologies - Introduction.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
Machine learning based COVID-19 study performance prediction
Encapsulation_ Review paper, used for researhc scholars
Reach Out and Touch Someone: Haptics and Empathic Computing
Review of recent advances in non-invasive hemoglobin estimation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Chapter 3 Spatial Domain Image Processing.pdf
Network Security Unit 5.pdf for BCA BBA.
Big Data Technologies - Introduction.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
MYSQL Presentation for SQL database connectivity
Digital-Transformation-Roadmap-for-Companies.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.

Automatically Managing Service Dependencies in an OSGi Environment - Marcel Offermans, Senior Software Engineer, Luminis

  • 2. Automatically Managing Service Dependencies in an OSGi Environment Marcel OffermansMarcel Offermans
  • 3. About me...About me... •• Marcel OffermansMarcel Offermans •• Senior Software Engineer at luminisSenior Software Engineer at luminis®® •• Our mission is to provide knowledge and products toOur mission is to provide knowledge and products to organisations who create software intensiveorganisations who create software intensive products, to help them adopt software technologyproducts, to help them adopt software technology innovations.innovations. •• We use OSGi at the core of the architecture forWe use OSGi at the core of the architecture for managable, embedded systems.managable, embedded systems.
  • 4. AgendaAgenda •• Dependencies in OSGiDependencies in OSGi •• Goals for a dependency managerGoals for a dependency manager •• Architecture, illustrated by examplesArchitecture, illustrated by examples •• ConclusionsConclusions
  • 5. Dependencies in OSGiDependencies in OSGi •• Package dependencies, which in R4 have beenPackage dependencies, which in R4 have been extended with requiring, fragment and extensionextended with requiring, fragment and extension bundles. These are all resolved in the module layer.bundles. These are all resolved in the module layer. •• Service dependencies, which are resolved in theService dependencies, which are resolved in the service layer.service layer.
  • 6. Service DependenciesService Dependencies •• Need to be managed at runtimeNeed to be managed at runtime •• The OSGi framework offers basic tools:The OSGi framework offers basic tools: –– Service listenerService listener –– Service trackerService tracker •• Third party tools:Third party tools: –– Service binderService binder –– ...probably there are more :)...probably there are more :)
  • 7. Goals for the Dependency ManagerGoals for the Dependency Manager •• Minimize the amount of code that needs to beMinimize the amount of code that needs to be written.written. •• Provide a clean separation between the serviceProvide a clean separation between the service implementation andimplementation and ““glueglue”” code.code. •• Be dynamic. Allow the programmer to add servicesBe dynamic. Allow the programmer to add services and dependencies at any time.and dependencies at any time.
  • 8. Types of dependenciesTypes of dependencies •• Required dependencies, which need to be resolvedRequired dependencies, which need to be resolved before the service can work at all.before the service can work at all. •• Optional dependencies, which are used whenOptional dependencies, which are used when available but are not essential for the service toavailable but are not essential for the service to work.work.
  • 10. Standard use caseStandard use case •• A service with two required dependencies and oneA service with two required dependencies and one optional one.optional one. public class Activator extends DependencyActivatorBase { public void init(BundleContext bc, DependencyManager dm) { dm.add(createService() .setInterface(MyService.class.getName(), null) .setImplementation(MyServiceImpl.class) .add(createServiceDependency() .setService(HttpService.class) .setRequired(true)) .add(createServiceDependency() .setService(SomeOtherService.class) .setRequired(true)) .add(createServiceDependency() .setService(LogService.class) .setRequired(false)) ); } public void destroy(BundleContext bc, DependencyManager dm) { } }
  • 11. Standard use caseStandard use case •• Implementation instantiated lazily, invokes callbacksImplementation instantiated lazily, invokes callbacks as part of lifeas part of life--cycle: init, start, stop, destroycycle: init, start, stop, destroy •• Dependencies are injected using reflectionDependencies are injected using reflection •• Null object pattern used for optional dependenciesNull object pattern used for optional dependencies public class MyServiceImpl implements MyService { private HttpService httpService; private SomeOtherService someOtherService; private LogService logService; public void start() { logService.log(LogService.LOG_INFO, “Starting”); } public void stop() { logService.log(LogService.LOG_INFO, “Stopping”); } }
  • 12. Code size reduction:Code size reduction: public class Activator implements BundleActivator { private BundleContext context; private ServiceRegistration registration; private AudioBroadcaster audioBroadcaster; private AudioSource audioSource; private AudioEncoder audioEncoder; private ServiceTracker audioSourceTracker; private ServiceTracker audioEncoderTracker; private ServiceTracker logTracker; public void start(BundleContext context) throws Exception { this.context = context; audioSourceTracker = new ServiceTracker(context, AudioSource.class.getName(), customizer); audioEncoderTracker = new ServiceTracker(context, AudioEncoder.class.getName(), customizer); logTracker = new ServiceTracker(context, LogService.class.getName(), null); logTracker.open(); audioSourceTracker.open(); audioEncoderTracker.open(); } public void stop(BundleContext context) throws Exception { audioSourceTracker.close(); audioEncoderTracker.close(); logTracker.close(); } private ServiceTrackerCustomizer customizer = new ServiceTrackerCustomizer() { public Object addingService(ServiceReference reference) { Object service = context.getService(reference); setService(reference, service); return service; } private void setService(ServiceReference reference, Object service) { // update service references Object objectclass = reference.getProperty(Constants.OBJECTCLASS); if (objectclass instanceof String) { String name = (String) objectclass; setNamedService(service, name); } if (objectclass instanceof String[]) { String[] names = (String[]) objectclass; for (int i = 0; i < names.length; i++) { setNamedService(service, names[i]); } } // register service if necessary if ((registration == null) && (audioSource != null) && (audioEncoder != null)) { // instantiate the implementation and pass the services audioBroadcaster = new AudioBroadcasterImpl(audioSource, audioEncoder, logTracker); registration = context.registerService( AudioBroadcaster.class.getName(), audioBroadcaster, null); } // unregister service if necessary if (((audioSource == null) || (audioEncoder == null)) && (registration != null)) { registration.unregister(); registration = null; audioBroadcaster = null; } } private void setNamedService(Object service, String name) { if (AudioEncoder.class.getName().equals(name)) { audioEncoder = (AudioEncoder) service; } else if (AudioSource.class.getName().equals(name)) { audioSource = (AudioSource) service; } } public void modifiedService(ServiceReference reference, Object service) { } public void removedService(ServiceReference reference, Object service) { setService(reference, null); context.ungetService(reference); } }; } public class Activator extends DependencyActivatorBase { public void init(BundleContext ctx, DependencyManager manager) throws Exception { manager.add(createService() .setInterface(AudioBroadcaster.class.getName(), null) .setImplementation(AudioBroadcasterImpl.class)); .add(createServiceDependency() .setService(AudioSource.class, null) .setRequired(true)) .add(createServiceDependency() .setService(AudioEncoder.class, null) .setRequired(true)) .add(createServiceDependency() .setService(LogService.class, null) .setRequired(false)) } public void destroy(BundleContext ctx, DependencyManager manager) throws Exception { } }
  • 13. Tracking dependenciesTracking dependencies •• Setting up a service with an optional dependencySetting up a service with an optional dependency that can track multiple dependent services:that can track multiple dependent services: public class Activator extends DependencyActivatorBase { public void init(BundleContext bc, DependencyManager dm) { dm.add(createService() .setImplementation(DeviceTracker.class) .add(createServiceDependency() .setService(Device.class) .setAutoConfig(false) .setCallbacks(“addDevice”, “removeDevice”) .setRequired(false)) ); } public void destroy(BundleContext bc, DependencyManager dm) { } }
  • 14. Tracking dependenciesTracking dependencies •• Implementation:Implementation: public class DeviceTracker { private List devs = new ArrayList(); public void addDevice(ServiceReference ref, Object srv) { devs.add(srv); } public void removeDevice(ServiceReference ref, Object srv) { devs.remove(srv); } }
  • 16. Other features:Other features: •• Injection of BundleContext and ServiceRegistrationInjection of BundleContext and ServiceRegistration •• New services and dependencies can be added orNew services and dependencies can be added or removed dynamicallyremoved dynamically •• Callbacks are configurable and will look for methodsCallbacks are configurable and will look for methods withwith ““suitablesuitable”” signaturessignatures •• Service listeners allow you to track the state of aService listeners allow you to track the state of a serviceservice •• Manager allows for addition of customizedManager allows for addition of customized dependencies (so you're not limited to servicedependencies (so you're not limited to service dependencies)dependencies)
  • 17. ConclusionsConclusions •• Clean separation between service implementationClean separation between service implementation and dependency management, you can use a POJOand dependency management, you can use a POJO if you wantif you want •• Dynamic nature of dependencies has proven to beDynamic nature of dependencies has proven to be useful in several scenariosuseful in several scenarios •• Substantial code reduction is realized whenSubstantial code reduction is realized when compared to using service trackerscompared to using service trackers
  • 18. Further infoFurther info •• Contacting me:Contacting me: ee--mail: marcel.offermans@luminis.nlmail: marcel.offermans@luminis.nl ICQ: 22100024ICQ: 22100024 Skype: marcel_offermansSkype: marcel_offermans •• Article:Article: http://www.osgi.org/news_events/articles.asp?section=4http://www.osgi.org/news_events/articles.asp?section=4 •• Development site:Development site: https://opensource.luminis.net/confluence/x/PwEhttps://opensource.luminis.net/confluence/x/PwE