SlideShare a Scribd company logo
1 of 51
Download to read offline
OSGi Bootcamp
Day 2
Jan Willem Janssen
Agenda
• OSGi design patterns
• Managing service dependencies
• more convenient options for easily managing service
dependencies
• The compendium
• some sample services, sending and receiving events
with EventAdmin and using and implementing the
Log Service
Design Patterns for OSGi
• Null-object pattern
• Whiteboard pattern
• Singleton services
• Aspect services
• Adapter services
• Resource adapter services
Null Object Pattern
An object that implements a certain interface,
can be safely invoked and does nothing
http://en.wikipedia.org/wiki/Null_Object_pattern
Whiteboard Pattern
“don’t call us...
we’ll call you”
http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf
Singleton Services
• Binds logic in a single instance
get()
getVersions()
get(version)
store(Document)
Document
Repository
Singleton
Storage
requires
Singleton Services
manager.add(createComponent()
.setInterface(DocumentRepository.class.getName(), null)
.setImplementation(DocumentRepositoryImpl.class)
.add(createServiceDependency()
.setService(Storage.class))
);


manager.add(createComponent()
.setInterface(Storage.class.getName(), null)
.setImplementation(FileBasedStorage.class)
);
Singleton Services
• What if I don’t want singletons?
• org.osgi.framework.ServiceFactory
• org.osgi.framework.PrototypeServiceFactory
• the consumer of the service is oblivious to this!
• Transparently inject an interceptor service 
• "in front of" all services matching a filter
Aspect Services
get()
getVersions()
get(version)
store(Document)
Repository Cache
Aspect
get()
getVersions()
get(version)
store(Document)
Repository
intercepts
Aspect Services
manager.add(
createAspectService(DocumentRepository.class, 

null /* filter */, 

10 /* ranking */, 

null /* autoConfig */

).setImplementation(DocumentRepositoryCache.class)
);
Adapter Services
• Start an instance of the adapter service for any
• "adaptee" service matching a filter
getCacheHits()
setSize()
setTTL()
flush()
Repository Cache
Manageable
Adapter
get()
getVersions()
get(version)
store(Document)
Repository Cache
adapts
Adapter Services
manager.add(
createAdapterService(MyService.class, null),
.setInterface(MyAdapterInterface.class.getName(),

null /* filter */),
.setImplementation(AdapterImpl.class))

);
Resource Adapters
• Start an instance of a Resource Driven Service for all
resources matching a filter
• resources: any valid URL
play()
pause()
stop()
Audio Track
Resource
Adapter
MP3
File
adapts
Resource Adapters
manager.add(
createResourceAdapterService(
"(path=*.mp3)" /* filter */,
false /* propagate */,
null /* callbackInstance */,
“changed" /* callbackMethod */)

.setInterface(AudioTrack.class, null)

.setImplementation(MP3AudioTrack.class))
);
Dependency Management
• Components need other services before:
• they can publish their own service
• they can do their work
• Complex dependency graphs
• hard to manage by hand
• lots of boilerplate code



Dependency Management
Bundle
Component StorageService
LogService
En5tyStore
Dependency Libraries
• Blueprint Services
• spring inspired
• XML
• Declarative Services
• OSGi standard
• annotation/XML based
Dependency Libraries
• iPOJO
• similar to DS
• extends OSGi service lifecycle
• Dependency Manager
• annotation/API-based
• runtime control
Dependency Manager
• API based dependency management
• optional and required dependencies
• supports extensible types of dependencies:
• service dependency
• configuration dependency
• change dependencies dynamically at runtime
Dependency Manager
• Extend DependencyActivatorBase, override init() and destroy()
• Talk to the DependencyManager to:
• create a new service object and:
• set any service interface and properties;
• set the implementation class;
• add any service or configuration dependencies and:
• make it required or optional
• refer to a specific service or configuration
public class SampleComparator implements Comparator {
private volatile LogService m_log;
public int compare(Object o1, Object o2) {
return o1.equals(o2) ? 0 : -1;
}
void start() {
m_log.log(LogService.LOG_INFO, "Hello there!");
}
}
Dependency Manager -
Example
public class Activator extends DependencyActivatorBase {
public void init(BundleContext context, DependencyManager dm) {
dm.add(
createComponent()
.setInterface(Comparator.class.getName(), null)
.setImplementation(SampleComparator.class)
.add(createServiceDependency()
.setService(LogService.class)
.setRequired(false)));
}
}
Dependency Manager -
Example
@Component
public class SampleComparator implements Comparator {
@ServiceDependency
private volatile LogService m_log;
public int compare(Object o1, Object o2) {
return o1.equals(o2) ? 0 : -1;
}
@Start
void start() {
m_log.log(LogService.LOG_INFO, "Hello there!");
}
}
Dependency Manager -
Example
• Add the DM annotation processor to bnd:
-plugin: 
${ext.repositories.-plugin},
org.apache.felix.dm.annotation.plugin.bnd.AnnotationPlugin;
path:=${plugin-dir}/org.apache.felix.dependencymanager.annotation.jar
Dependency Manager -
Example
Dependency Manager
• Create one or more components:

manager.add(createComponent() ...
• Use POJOs to implement services:

.setImplementation(MyPOJO.class)
• Optionally define the service interfaces:

.setInterface(MySvc.class.getName, props)
• Add dependencies
Service Dependencies
• Are defined using the DependencyManager:

.add(createServiceDependency() ...
• Can be optional or required: 

.setRequired(boolean)
• Track a specific service:

.setService(LogService.class, “(name=mine)”)
• Can be injected into an instance:

.setAutoConfig(true) // this is the default
• Can trigger callbacks on the instance:

.setCallbacks(“addService”, “removeService”)

// NOTE: callbacks can define any of the following parameters:

(ServiceReference reference, Object service)
Dependency Life Cycle
start
Installed
start
Resolved
Ac/veUninstalled
end
install
stop
uninstall Ac/ve
Wai/ng6for6
required
Monitoring6
op/onal
ac/vatedeac/vate
Dependency Activation
• If the reference to the implementation is a class,
instantiate it, otherwise directly use the reference
• Invoke the init() method on the instance
• Inject all required and optional dependencies, using
NullObjects where appropriate, and any
BundleContext or ServiceRegistration
• Invoke the start() method on the instance
OSGi compendium
Log
HTTP
Device Access
Configuration Admin
Preferences
Metatype
Wire AdminUser Admin
IO Connector
Initial Provisioning
UPnP™ Device
Declarative Services
Event Admin
Service Tracker
XML Parser
Position
Measurement and State
Execution Environment Spec
Remote Services
Deployment Admin
Blueprint Container
Log Service
The Log Service Interface Log Service Specification Version 1.3
Figure 101.1 Log Service Class Diagram org.osgi.service.log package
<<interface>>
LogService
<<interface>>
LogReader
Service
<<interface>>
LogEntry
<<interface>>
LogListener
a Log Reader
Service impl.
LogEntry impl
a Log user bundle
a Log Service
impl
a Log reader user
Log a
message
Store a message in the log for retrieval
message log
send new log entry
retrieve log
1 1
1
0..n (impl dependent maximum)
1
0..n
LogEntry has references to
ServiceReference,
Throwable and Bundle
or register
listener
Bundle using
Log Service
Bundle using
Log Reader
Service
Log implementation bundle
Log Service
• an update of this spec is coming!
• tries to solve many of the problems:
• static logger
• dynamic reconfiguration per logger
• align API with SLF4J
Event Admin
• Publish subscribe
• Asynchronous and synchronous
• Hierarchical topics
• Decouple event creation and handling
Event Admin
Bundle
Component,
invoking,a,
service
Bundle
Component
providing,a,
service
method,call
MyService
Bundle
EventAdmin-
implementa0on
Bundle
Component-
listening-for-
events
EventAdmin
Bundle
Component-
publishing-an-
event
(a)synch-event
EventHandler
Listen to Events
• Create an EventHandler that listens to all events
• Launch it in a framework that has an Event Admin
implementation running
Event Admin - Example
class MySubscriber extends DependencyActivatorBase implements EventHandler {
static final String[] topics ={ "com/acme/*", 

"org/osgi/service/log/LogEntry/*" };


public void init(BundleContext context, DependencyManager dm) {
Dictionary dict = new Hashtable();
dict.put(EventConstants.EVENT_TOPIC, topics);
dict.put(EventConstants.EVENT_FILTER, "(bundle.symbolicName=com.acme.*)");


dm.add(createComponent()

.setInterface(EventHandler.class.getName(), dict)
.setImplementation(SampleComparator.class);
}


@Override
public void handleEvent(Event event) {
//...
}
}
Sending events
• Add a service dependency to EventAdmin
• Use either sendEvent() or postEvent() to send
events
Event Admin - Example
public class EventPublishingService {
private volatile EventAdmin m_eventAdmin;

private volatile LogService m_log;
public void someLogic() {
if (m_eventAdmin != null) {
Dictionary properties = new Hashtable();
properties.put("timestamp", new Date());
m_eventAdmin.postEvent(

new Event("com/acme/timer", properties));
} else {
m_log.log(LogService.LOG_INFO,

"unable to send event: no event admin!");
}
}
}
Configuration Admin
• contains externally configurable settings for a service;
• service is identified by its PID (persistent ID)
• allows management systems 

to configure all settings;
• settings can be

created even before the

actual bundle is installed.
Bundle
Component
ManagedService
service.pid6=6nl.luminis.store
Configuration Admin
• Used for:
• dynamically configuring singleton services

(ManagedService)
• creating new services based on configuration

(ManagedServiceFactory)
Configuration Admin
port=8080
protocol=REST
public=true
PID=connector
style=winxp
colorset=silver
PID=gui
Configura?onAdmin
getConfigura?on()
listConfigura?ons()
Configura?on
getProper?es()
update()
delete()
manageEconfigura?ons no?fiesEofEchanges
ManagedService
updated()
Service
PID=connector
Configura?onE
Manager
Configuration Dependencies
public class MyConfiguredService implements ManagedService {
private volatile String m_name;
@Override
public void updated(Properties props)
throws ConfigurationException {
// check given properties
if (props == null) {
m_name = "<default>";

} else {
// update local settings
Object v = props.get("name");
if (v instanceof String) {
m_name = (String) v;
} else {
throw new ConfigurationException("name", 

"must be a string!");
}
}

}
// …
}
Configuration Dependencies
• Configuration updates are optional, but what about
required configurations?
• DependencyManager can help:
• define a configuration dependency
• our component is started only when the configuration
becomes available
• updated(props) is invoked before other life cycle
methods of DM
Configuration Dependencies
// Define in the init() of your activator:
manager.add(createService()
.setImplementation(MyConfiguredService.class)
.add(createConfigurationDependency()
.setPid("my.service.pid"))
);
HTTP service
• provides Servlet API
• whiteboard style registration of:
• listeners
• filters
• servlets
HTTP service 

Example
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, 

HttpServletResponse resp) throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_OK);
resp.getWriter().print("Hello World");
resp.flushBuffer();
}
}
HTTP service

Example
// Define in the init() of your activator:
Properties props = new Properties();
props.put("osgi.http.whiteboard.servlet.pattern", "/hello");
manager.add(createService()

.setInterface(Servlet.class.getName(), props)
.setImplementation(MyServlet.class)
);
OSGi tooling
• The popularity of frameworks depend on their ease of
use
• OSGi development lacked in this area for long
OSGi tooling
• Enter Bndtools:
• actively developed plugin for Eclipse
• makes it really easy to develop for/with OSGi:
• automatic rebuilding of bundles
• hot-deployment of bundles
• very good support for semantic versioning
OSGi tooling
• demo
Books
• Building Modular Cloud Apps with OSGi
• Paul Bakker & Bert Ertman
• Java Application Architecture

Modularity Patterns with Examples using OSGi
• Kirk Knoernschild
Links
• https://github.com/jawi/osgi-tutorial contains the demo
project as shown during the demo
• http://bndtools.org/ the home of the Bndtools plugin
for Eclipse
• http://bnd.bndtools.org/ contains lots of information
about the nitty-gritty details of Bnd
• http://luminis.eu my current employer

More Related Content

What's hot

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...
Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...
Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...mfrancis
 
GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactionsHusain Dalal
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Janel Heilbrunn
 
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?SegFaultConf
 
Inside Azure Diagnostics
Inside Azure DiagnosticsInside Azure Diagnostics
Inside Azure DiagnosticsMichael Collier
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Angular - injection tokens & Custom libraries
Angular - injection tokens & Custom librariesAngular - injection tokens & Custom libraries
Angular - injection tokens & Custom librariesEliran Eliassy
 

What's hot (19)

UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...
Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...
Modularity and Domain Driven Design - A killer combination - T De Wolf & S va...
 
GR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails WebflowGR8Conf 2011: Grails Webflow
GR8Conf 2011: Grails Webflow
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
Linq
LinqLinq
Linq
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactions
 
Input Method Kit
Input Method KitInput Method Kit
Input Method Kit
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2
 
Docker and java
Docker and javaDocker and java
Docker and java
 
Net remoting
Net remotingNet remoting
Net remoting
 
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
 
GraphQL 101
GraphQL 101GraphQL 101
GraphQL 101
 
Ondemand scaling-aws
Ondemand scaling-awsOndemand scaling-aws
Ondemand scaling-aws
 
Inside Azure Diagnostics
Inside Azure DiagnosticsInside Azure Diagnostics
Inside Azure Diagnostics
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Angular - injection tokens & Custom libraries
Angular - injection tokens & Custom librariesAngular - injection tokens & Custom libraries
Angular - injection tokens & Custom libraries
 

Similar to OSGi bootcamp - part 2

Dependencies, dependencies, dependencies
Dependencies, dependencies, dependenciesDependencies, dependencies, dependencies
Dependencies, dependencies, dependenciesMarcel Offermans
 
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependenciesOSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependenciesmfrancis
 
Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...
Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...
Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...mfrancis
 
Fredrik knalstad 10 ways to trigger orchestrator runbooks in the it jungle
Fredrik knalstad   10 ways to trigger orchestrator runbooks in the it jungleFredrik knalstad   10 ways to trigger orchestrator runbooks in the it jungle
Fredrik knalstad 10 ways to trigger orchestrator runbooks in the it junglePer Riis
 
10 ways to trigger runbooks from Orchestrator
10 ways to trigger runbooks from Orchestrator10 ways to trigger runbooks from Orchestrator
10 ways to trigger runbooks from OrchestratorFredrik Knalstad
 
Fredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungle
Fredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungleFredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungle
Fredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungleNordic Infrastructure Conference
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsJosh Lane
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with javaDPC Consulting Ltd
 
Overview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technologyOverview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technologyPeter R. Egli
 
Shindig in 2 hours
Shindig in 2 hoursShindig in 2 hours
Shindig in 2 hourshanhvi
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksMohammad Asif Siddiqui
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & DevelopmentGlobalLogic Ukraine
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17aminmesbahi
 

Similar to OSGi bootcamp - part 2 (20)

Dependencies, dependencies, dependencies
Dependencies, dependencies, dependenciesDependencies, dependencies, dependencies
Dependencies, dependencies, dependencies
 
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependenciesOSGi Community Event 2010 - Dependencies, dependencies, dependencies
OSGi Community Event 2010 - Dependencies, dependencies, dependencies
 
Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...
Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...
Automatically Managing Service Dependencies in an OSGi Environment - Marcel O...
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
 
Fredrik knalstad 10 ways to trigger orchestrator runbooks in the it jungle
Fredrik knalstad   10 ways to trigger orchestrator runbooks in the it jungleFredrik knalstad   10 ways to trigger orchestrator runbooks in the it jungle
Fredrik knalstad 10 ways to trigger orchestrator runbooks in the it jungle
 
10 ways to trigger runbooks from Orchestrator
10 ways to trigger runbooks from Orchestrator10 ways to trigger runbooks from Orchestrator
10 ways to trigger runbooks from Orchestrator
 
Fredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungle
Fredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungleFredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungle
Fredrik Knalstad - 10 ways to trigger orchestrator runbooks in the it jungle
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic Apps
 
Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
ServerLess by usama Azure fuctions.pptx
ServerLess by usama Azure fuctions.pptxServerLess by usama Azure fuctions.pptx
ServerLess by usama Azure fuctions.pptx
 
OSGi compendium
OSGi compendiumOSGi compendium
OSGi compendium
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with java
 
Overview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technologyOverview of Microsoft .Net Remoting technology
Overview of Microsoft .Net Remoting technology
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
Shindig in 2 hours
Shindig in 2 hoursShindig in 2 hours
Shindig in 2 hours
 
All About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice FrameworksAll About Microservices and OpenSource Microservice Frameworks
All About Microservices and OpenSource Microservice Frameworks
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
 
Android meetup
Android meetupAndroid meetup
Android meetup
 
Serverless computing
Serverless computingServerless computing
Serverless computing
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

OSGi bootcamp - part 2

  • 1. OSGi Bootcamp Day 2 Jan Willem Janssen
  • 2. Agenda • OSGi design patterns • Managing service dependencies • more convenient options for easily managing service dependencies • The compendium • some sample services, sending and receiving events with EventAdmin and using and implementing the Log Service
  • 3. Design Patterns for OSGi • Null-object pattern • Whiteboard pattern • Singleton services • Aspect services • Adapter services • Resource adapter services
  • 4. Null Object Pattern An object that implements a certain interface, can be safely invoked and does nothing http://en.wikipedia.org/wiki/Null_Object_pattern
  • 5. Whiteboard Pattern “don’t call us... we’ll call you” http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf
  • 6. Singleton Services • Binds logic in a single instance get() getVersions() get(version) store(Document) Document Repository Singleton Storage requires
  • 8. Singleton Services • What if I don’t want singletons? • org.osgi.framework.ServiceFactory • org.osgi.framework.PrototypeServiceFactory • the consumer of the service is oblivious to this!
  • 9. • Transparently inject an interceptor service  • "in front of" all services matching a filter Aspect Services get() getVersions() get(version) store(Document) Repository Cache Aspect get() getVersions() get(version) store(Document) Repository intercepts
  • 10. Aspect Services manager.add( createAspectService(DocumentRepository.class, 
 null /* filter */, 
 10 /* ranking */, 
 null /* autoConfig */
 ).setImplementation(DocumentRepositoryCache.class) );
  • 11. Adapter Services • Start an instance of the adapter service for any • "adaptee" service matching a filter getCacheHits() setSize() setTTL() flush() Repository Cache Manageable Adapter get() getVersions() get(version) store(Document) Repository Cache adapts
  • 13. Resource Adapters • Start an instance of a Resource Driven Service for all resources matching a filter • resources: any valid URL play() pause() stop() Audio Track Resource Adapter MP3 File adapts
  • 14. Resource Adapters manager.add( createResourceAdapterService( "(path=*.mp3)" /* filter */, false /* propagate */, null /* callbackInstance */, “changed" /* callbackMethod */)
 .setInterface(AudioTrack.class, null)
 .setImplementation(MP3AudioTrack.class)) );
  • 15. Dependency Management • Components need other services before: • they can publish their own service • they can do their work • Complex dependency graphs • hard to manage by hand • lots of boilerplate code
 

  • 17. Dependency Libraries • Blueprint Services • spring inspired • XML • Declarative Services • OSGi standard • annotation/XML based
  • 18. Dependency Libraries • iPOJO • similar to DS • extends OSGi service lifecycle • Dependency Manager • annotation/API-based • runtime control
  • 19. Dependency Manager • API based dependency management • optional and required dependencies • supports extensible types of dependencies: • service dependency • configuration dependency • change dependencies dynamically at runtime
  • 20. Dependency Manager • Extend DependencyActivatorBase, override init() and destroy() • Talk to the DependencyManager to: • create a new service object and: • set any service interface and properties; • set the implementation class; • add any service or configuration dependencies and: • make it required or optional • refer to a specific service or configuration
  • 21. public class SampleComparator implements Comparator { private volatile LogService m_log; public int compare(Object o1, Object o2) { return o1.equals(o2) ? 0 : -1; } void start() { m_log.log(LogService.LOG_INFO, "Hello there!"); } } Dependency Manager - Example
  • 22. public class Activator extends DependencyActivatorBase { public void init(BundleContext context, DependencyManager dm) { dm.add( createComponent() .setInterface(Comparator.class.getName(), null) .setImplementation(SampleComparator.class) .add(createServiceDependency() .setService(LogService.class) .setRequired(false))); } } Dependency Manager - Example
  • 23. @Component public class SampleComparator implements Comparator { @ServiceDependency private volatile LogService m_log; public int compare(Object o1, Object o2) { return o1.equals(o2) ? 0 : -1; } @Start void start() { m_log.log(LogService.LOG_INFO, "Hello there!"); } } Dependency Manager - Example
  • 24. • Add the DM annotation processor to bnd: -plugin: ${ext.repositories.-plugin}, org.apache.felix.dm.annotation.plugin.bnd.AnnotationPlugin; path:=${plugin-dir}/org.apache.felix.dependencymanager.annotation.jar Dependency Manager - Example
  • 25. Dependency Manager • Create one or more components:
 manager.add(createComponent() ... • Use POJOs to implement services:
 .setImplementation(MyPOJO.class) • Optionally define the service interfaces:
 .setInterface(MySvc.class.getName, props) • Add dependencies
  • 26. Service Dependencies • Are defined using the DependencyManager:
 .add(createServiceDependency() ... • Can be optional or required: 
 .setRequired(boolean) • Track a specific service:
 .setService(LogService.class, “(name=mine)”) • Can be injected into an instance:
 .setAutoConfig(true) // this is the default • Can trigger callbacks on the instance:
 .setCallbacks(“addService”, “removeService”)
 // NOTE: callbacks can define any of the following parameters:
 (ServiceReference reference, Object service)
  • 27. Dependency Life Cycle start Installed start Resolved Ac/veUninstalled end install stop uninstall Ac/ve Wai/ng6for6 required Monitoring6 op/onal ac/vatedeac/vate
  • 28. Dependency Activation • If the reference to the implementation is a class, instantiate it, otherwise directly use the reference • Invoke the init() method on the instance • Inject all required and optional dependencies, using NullObjects where appropriate, and any BundleContext or ServiceRegistration • Invoke the start() method on the instance
  • 29. OSGi compendium Log HTTP Device Access Configuration Admin Preferences Metatype Wire AdminUser Admin IO Connector Initial Provisioning UPnP™ Device Declarative Services Event Admin Service Tracker XML Parser Position Measurement and State Execution Environment Spec Remote Services Deployment Admin Blueprint Container
  • 30. Log Service The Log Service Interface Log Service Specification Version 1.3 Figure 101.1 Log Service Class Diagram org.osgi.service.log package <<interface>> LogService <<interface>> LogReader Service <<interface>> LogEntry <<interface>> LogListener a Log Reader Service impl. LogEntry impl a Log user bundle a Log Service impl a Log reader user Log a message Store a message in the log for retrieval message log send new log entry retrieve log 1 1 1 0..n (impl dependent maximum) 1 0..n LogEntry has references to ServiceReference, Throwable and Bundle or register listener Bundle using Log Service Bundle using Log Reader Service Log implementation bundle
  • 31. Log Service • an update of this spec is coming! • tries to solve many of the problems: • static logger • dynamic reconfiguration per logger • align API with SLF4J
  • 32. Event Admin • Publish subscribe • Asynchronous and synchronous • Hierarchical topics • Decouple event creation and handling
  • 34. Listen to Events • Create an EventHandler that listens to all events • Launch it in a framework that has an Event Admin implementation running
  • 35. Event Admin - Example class MySubscriber extends DependencyActivatorBase implements EventHandler { static final String[] topics ={ "com/acme/*", 
 "org/osgi/service/log/LogEntry/*" }; 
 public void init(BundleContext context, DependencyManager dm) { Dictionary dict = new Hashtable(); dict.put(EventConstants.EVENT_TOPIC, topics); dict.put(EventConstants.EVENT_FILTER, "(bundle.symbolicName=com.acme.*)"); 
 dm.add(createComponent()
 .setInterface(EventHandler.class.getName(), dict) .setImplementation(SampleComparator.class); } 
 @Override public void handleEvent(Event event) { //... } }
  • 36. Sending events • Add a service dependency to EventAdmin • Use either sendEvent() or postEvent() to send events
  • 37. Event Admin - Example public class EventPublishingService { private volatile EventAdmin m_eventAdmin;
 private volatile LogService m_log; public void someLogic() { if (m_eventAdmin != null) { Dictionary properties = new Hashtable(); properties.put("timestamp", new Date()); m_eventAdmin.postEvent(
 new Event("com/acme/timer", properties)); } else { m_log.log(LogService.LOG_INFO,
 "unable to send event: no event admin!"); } } }
  • 38. Configuration Admin • contains externally configurable settings for a service; • service is identified by its PID (persistent ID) • allows management systems 
 to configure all settings; • settings can be
 created even before the
 actual bundle is installed. Bundle Component ManagedService service.pid6=6nl.luminis.store
  • 39. Configuration Admin • Used for: • dynamically configuring singleton services
 (ManagedService) • creating new services based on configuration
 (ManagedServiceFactory)
  • 41. Configuration Dependencies public class MyConfiguredService implements ManagedService { private volatile String m_name; @Override public void updated(Properties props) throws ConfigurationException { // check given properties if (props == null) { m_name = "<default>";
 } else { // update local settings Object v = props.get("name"); if (v instanceof String) { m_name = (String) v; } else { throw new ConfigurationException("name", 
 "must be a string!"); } }
 } // … }
  • 42. Configuration Dependencies • Configuration updates are optional, but what about required configurations? • DependencyManager can help: • define a configuration dependency • our component is started only when the configuration becomes available • updated(props) is invoked before other life cycle methods of DM
  • 43. Configuration Dependencies // Define in the init() of your activator: manager.add(createService() .setImplementation(MyConfiguredService.class) .add(createConfigurationDependency() .setPid("my.service.pid")) );
  • 44. HTTP service • provides Servlet API • whiteboard style registration of: • listeners • filters • servlets
  • 45. HTTP service 
 Example public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, 
 HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().print("Hello World"); resp.flushBuffer(); } }
  • 46. HTTP service
 Example // Define in the init() of your activator: Properties props = new Properties(); props.put("osgi.http.whiteboard.servlet.pattern", "/hello"); manager.add(createService()
 .setInterface(Servlet.class.getName(), props) .setImplementation(MyServlet.class) );
  • 47. OSGi tooling • The popularity of frameworks depend on their ease of use • OSGi development lacked in this area for long
  • 48. OSGi tooling • Enter Bndtools: • actively developed plugin for Eclipse • makes it really easy to develop for/with OSGi: • automatic rebuilding of bundles • hot-deployment of bundles • very good support for semantic versioning
  • 50. Books • Building Modular Cloud Apps with OSGi • Paul Bakker & Bert Ertman • Java Application Architecture
 Modularity Patterns with Examples using OSGi • Kirk Knoernschild
  • 51. Links • https://github.com/jawi/osgi-tutorial contains the demo project as shown during the demo • http://bndtools.org/ the home of the Bndtools plugin for Eclipse • http://bnd.bndtools.org/ contains lots of information about the nitty-gritty details of Bnd • http://luminis.eu my current employer