SlideShare una empresa de Scribd logo
1 de 29
Deep Dive into OSGi
(Lifecycle Layer)
(Chapter 3)
Aruna Karunarathna
Discussion
o Software Lifecycle Management
o Lifecycle of a Bundle
o The Lifecycle API
o Explore relationship between modules and lifecycle layer
o Demo (Sample Application)
Software Lifecycle Management
● Installation
○ Along with the all dependencies
● Execution
○ Acquiring resources and start functionalities
it suppose to do, if no longer needed stop application
● Update
○ Update application
● Uninstall
○ Remove application when no longer needed
Note - Most Applications(e.g Standard Java app ) do above steps as
whole; for modular applications, using fine grained lifecycle
management it is possible for manage lifecycle of individual
modules.
OSGi Lifecycle Layer
o Internal to your application
The lifecycle layer precisely defines the bundle lifecycle operations. These
lifecycle operations allow you to manage and evolve your application by
dynamically changing the composition of bundles inside a running framework
o External to your application
The lifecycle layer defines how your bundles gain access to their execution
context, which provides them with a way to interact with the OSGi framework and
the facilities it provides at execution time
OSGi Bundle Lifecycle
o Modular Layer - Relies on Metadata provided by bundle
o Lifecycle Layer - API provided by OSGi
There is no other way to deal with the OSGi Life Cycle other than the
provided API.
● Which is very powerful
● OSGi core framework doesn’t mandate any particular mechanism of
interacting with the lifecycle API
OSGi Framework role in Lifecycle - Installation
o Standard Java - Place Jar files in classpath
o OSGi Framework - Install bundles to framework
OSGi Framework role in Lifecycle - Installation Cntd...
o Inherent Dynamism
The OSGi framework supports the full bundle lifecycle at execution time. This
is similar to modifying what’s on the classpath dynamically in a Standard java
app.
o Persist the Cache
This means the next time you start the framework, any previously
installed bundles are automatically reloaded from the bundle cache, and the
original JAR files are no longer necessary
Note- You can disable the persist bundle cache if you need a fresh framework
start.
Bundle Activator Manifest Entry
o Defines the bundle’s identity
o Specifies the packages on which this
bundle depends
o Specifies the packages on which this
bundle exports
o Declares additional human-readable
information
Manifest-Version: 1.0
Bnd-LastModified: 1405099135557
Build-Jdk: 1.7.0_55
Built-By: aruna
Bundle-Activator: org.sample.Activator
Bundle-ManifestVersion: 2
Bundle-Name: sample
Bundle-SymbolicName: sample
Bundle-Vendor: WSO2 Inc
Bundle-Version: 1.0.0
Created-By: Apache Maven Bundle Plugin
Export-Package:
org.sample;uses:="org.osgi.framework";
version="1.0.0"
Import-Package:
org.osgi.framework;version="[1.7,2)"
Tool: Bnd-2.1.0.20130426-122213
Bundle Activator Manifest Entry cntd...
o Bundle Activator Manifest Entry is the hook to the Bundle execution entry
point.
o Similar to the Main Method of a Jar file?..
o Header value specifies the name of a reachable class
o Either a class in an Imported Package
o A class in the Bundle class path
o This class implements the org.osgi.framework.BundleActivator interface, and
implements the following two methods.
o Can use these two methods to customize the behaviours when the bundle is
started and stopped.
public interface BundleActivator {
void start(org.osgi.framework.BundleContext bundleContext) throws java.lang.Exception;
void stop(org.osgi.framework.BundleContext bundleContext) throws java.lang.Exception;
}
Bundle Activator Manifest Entry cntd...
o When the bundle installed and started, OSGi Framework creates an instance of
Bundle Activator class and call the start() method.
o When the bundle stop is initiated, OSGi Framework call the stop() method.
o In practice when the stop is called, you should undo everything you did in
the start method.
o The activator instance on which start() is called is the same instance
on which stop() is called.
o The activator instance is discarded and isn’t used again, after stop()
is called.
o If the bundle is subsequently restarted after being stopped, a new
activator instance is created, and the start() and stop() methods are
invoked on it as appropriate.
Bundle Activator vs Threading
o OSGi is designed around the normal java thread abstraction.
o The framework assumes that you handle the thread management and the programs
are correctly synchronized and thread safe.
o The OSGi libraries are thread safe, and callbacks are normally done in a
thread safe manner
o for. e.g The same thread called the start() method, is guaranteed by
the framework to be called the stop() method in order not concurrently.
o If threads are used in a bundle make sure that all threads are stopped when
the stop() method returns.
Bundle Context
o Can be accessed via start() and stop() of Bundle Activator class
o Bundle context object is its role as the unique execution context of its
associated bundle
o Valid while the bundle is active. (The time range from the framework call
start() up until to the stop() is called )
o Gain access to two types of methods
o Related to deployment and lifecycle management.
o Related to bundle interaction via services.
o They should be treated as sensitive or private objects and not passed freely
among bundles
Bundle
o For each installed bundle, the framework creates a Bundle object
o From Bundle object, a bundle can identified by two additional forms
o Bundle Identifier
o Bundle Location
o Bundle object persist over the framework executions when the installed
bundles are reloaded from the framework’s cache.
Bundle cntd...
o Why we need two execution time identifiers?..
o Can’t we use Bundle Symbolic name and version to identify?..
History plays a role here. The notion of using a bundle’s symbolic name
and version to uniquely identify it didn’t exist in versions of the
specification prior to R4. Therefore, prior to R4, it made sense to
have internally and externally assigned identifiers. Now it makes less
sense, because the bundle’s symbolic name and version pair are
externally defined and explicitly recognized internally by the
framework.
The System Bundle
o Execution time framework is represented as a bundle, with Bundle ID set to 0
and it is called as the System Bundle.
o You don’t explicitly install the System Bundle, it always exists while the
framework is running
o Follows the same lifecycle as other Bundles in the framework, and you can
manipulate it with the same operations as normal bundles
o Lifecycle operations performed on the system bundle have special meanings
when compared to normal bundles
One example of the special meaning is evident when you stop the system
bundle. Intuitively, stopping the system bundle shuts down the framework
in a well behaved manner. It stops all other bundles first and then shuts
itself down completely.
Lifecycle State Diagram
Bundle Start
o Calls the Bundle.start() of the respective
Bundle Object
o If the Bundle is INSTALLED state, it transitions to
ACTIVE state via the RESOLVED and STARTING states.
o If the Bundle is UNINSTALLED, throws an
IllegalStateException.
o If the Bundle is in STARTING or STOPPING state
start() is blocked until it enters ACTIVE or RESOLVED.
o If the bundle is in ACTIVE state, calling start has no effect.
o If the Bundle can’t satisfy it’s dependencies, calling Start will result in
throwing a BundleException
o If a BundleActivator is specified, will call the start() in the
BundleActivator class
Bundle Stop
o Calls the Bundle.stop() of the respective
Bundle Object.
o If the Bundle is in UNINSTALLED state, throws an
IllegalStateException.
o If the Bundle is in STARTING or STOPPING state
stop() is blocked until it enters START or RESOLVED.
o If a BundleActivator is specified, will call the stop() in the
BundleActivator class
o If the stop() method in the BundleActivator class, throws an exception, a
BundleException is throws by the Bundle.stop() method
Update Command
o Bundle.update() comes in two forms
o Without parameters
o With parameter InputStream
o If the Bundle is in ACTIVE state, first the Bundle.stop()
Needs to be called by the framework.
o The update happens either in INSTALLED or RESOLVED state.
o If the Bundle is in UNINSTALLED state, the framework will
thrown an IllegalStateException.
Tips - Don’t use the Bundle-UpdateLocation MF
header.
Uninstall Command
o Calls the Bundle.uninstall() method in the framework.
o If the Bundle is in ACTIVE state, first the Bundle.stop()
Needs to be called by the framework.
o If the Bundle is already in UNINSTALLED state, the framework
will throw an IllegalStateException.
Tips - bundle shouldn’t attempt to stop, update, uninstall
itself (Bundle Suicide)
Bundle cache and framework restarts
o A Bundle can be installed in 2 ways
o Providing the url for the bundle
o Providing bundle as an inputstream
o Framework reads the bundle JAR file and saves a copy in a private area known
as the bundle cache
o Installing a bundle into the framework is a persistent operation
o After the bundle is installed, the framework no longer needs the
original copy of the bundle JAR file
Bundle cache and framework restarts cntd...
o Framework persists Bundle status too..
o Bundle start() is called, the framework persistently marked as STARTED
o Bundle stop() is called, the framework persistently marked as STOPPED
o What about update and uninstall?..
o Remove the existing bundle from the cache
o Install a totally new bundle in the persistent cache
Bundle Configuration Properties
o BundleContext.getProperty() method to retrieve the properties
o Avoid the global aspect of System.getProperty(), and provides per framework
instance properties
o If not found in the BundleContext scope search in the global System scope
o If you need to use these standard properties, you can use the constants
defined in the org.osgi.framework.Constants class
Listening for events
o OSGi framework supports two types of events: BundleEvents and FrameworkEvents
o The former event type reports changes in the lifecycle of bundles, whereas the
latter reports framework-related changes
o The BundleContext object has methods to register BundleListener and
FrameworkListener objects for receiving BundleEvent and FrameworkEvent
notifications, respectively
o How to implement BundleListener and FrameworkListener in your code?.
a. Create a new class which Implements BundleListener or FrameworkListener
b. Implement the bundleChanged(BundleEvent) or frameworkEvent(FrameworkEvent)
methods respectively.
c. Register by creating a new Object of the implemented class to the
BundleContext as a Listener using the bundleContext.addBundleListener() or
bundleContext.addFrameworkListener() respectively.
o No need to call the removeBundleListener() or removeFrameworkListener(), which will
automatically removed when the bundle is stopped.
Sample code for listening for events
public class MyListener implements BundleActivator , FrameworkListener , BundleListener{
@Override
public void start(BundleContext bundleContext) throws Exception {
bundleContext.addBundleListener(new MyListener ());
bundleContext.addFrameworkListener(new MyListener ());
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
}
@Override
public void bundleChanged(BundleEvent event) {
//TODO - implement
}
@Override
public void frameworkEvent(FrameworkEvent event) {
//TODO - implement
}
}
Framework events
o FrameworkEvent.STARTED —Indicates the framework has performed all
initialization and has finished starting up.
o FrameworkEvent.INFO —Indicates some information of general interest in
various
situations.
o FrameworkEvent.WARNING —Indicates a warning. Not crucial, but may indicate a
potential error.
o FrameworkEvent.ERROR —Indicates an error. Requires immediate attention.
o FrameworkEvent.PACKAGES_REFRESHED —Indicates the framework has refreshed
some shared packages.
o FrameworkEvent.STARTLEVEL_CHANGED —Indicates the framework has changed
its start level.
Bundle Events
o BundleEvent.INSTALLED — Indicates a bundle was installed
o BundleEvent.RESOLVED — Indicates a bundled was resolved
o BundleEvent.STARTED — Indicates a bundle was started
o BundleEvent.STOPPED — Indicates a bundle was stopped
o BundleEvent.UPDATED — Indicates a bundle was updated
o BundleEvent.UNINSTALLED — Indicates a bundle was uninstalled
o BundleEvent.UNRESOLVED — Indicates a bundle was unresolved
Following events are only send to SynchronousBundleListeners (listener is
notified during the processing of the event - HANDLE WITH CARE…!!!)
BundleEvent.STARTING — Indicates a bundle is about to be
started
BundleEvent.STOPPING — Indicates a bundle is about to be
DEMO
References
OSGi Alliance Specifications http://www.osgi.org/Specifications/HomePage
OSGI in Action - CREATING MODULAR APPLICATIONS IN JAVA
Sample - https://github.com/arunasujith/osgi-sample

Más contenido relacionado

La actualidad más candente

Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizersts_v_murthy
 
Inter thread communication & runnable interface
Inter thread communication & runnable interfaceInter thread communication & runnable interface
Inter thread communication & runnable interfacekeval_thummar
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Readingkishima7
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemRafael Winterhalter
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 

La actualidad más candente (20)

Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Inter thread communication & runnable interface
Inter thread communication & runnable interfaceInter thread communication & runnable interface
Inter thread communication & runnable interface
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Singleton
SingletonSingleton
Singleton
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Reading
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystem
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java7
Java7Java7
Java7
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 

Destacado

Introduction to OSGi
Introduction to OSGiIntroduction to OSGi
Introduction to OSGipradeepfn
 
OSGi-enabled Java EE applications in GlassFish
OSGi-enabled Java EE applications in GlassFishOSGi-enabled Java EE applications in GlassFish
OSGi-enabled Java EE applications in GlassFishArun Gupta
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's Howmrdon
 
OSGi Web Development in Action
OSGi Web Development in Action	OSGi Web Development in Action
OSGi Web Development in Action OSGiUsers
 
Building LinkedIn's Next Generation Architecture with OSGi
Building LinkedIn's Next Generation  Architecture with OSGiBuilding LinkedIn's Next Generation  Architecture with OSGi
Building LinkedIn's Next Generation Architecture with OSGiLinkedIn
 
Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)
Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)
Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)Savita Marwal
 

Destacado (6)

Introduction to OSGi
Introduction to OSGiIntroduction to OSGi
Introduction to OSGi
 
OSGi-enabled Java EE applications in GlassFish
OSGi-enabled Java EE applications in GlassFishOSGi-enabled Java EE applications in GlassFish
OSGi-enabled Java EE applications in GlassFish
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's How
 
OSGi Web Development in Action
OSGi Web Development in Action	OSGi Web Development in Action
OSGi Web Development in Action
 
Building LinkedIn's Next Generation Architecture with OSGi
Building LinkedIn's Next Generation  Architecture with OSGiBuilding LinkedIn's Next Generation  Architecture with OSGi
Building LinkedIn's Next Generation Architecture with OSGi
 
Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)
Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)
Payment and Settlement Systems(SWIFT,NEFT and Securities Cycle)
 

Similar a Deep dive into OSGi Lifecycle Layer

JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Intro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse VirgoIntro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse VirgoGordon Dickens
 
Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)Peter R. Egli
 
Eclipse_Building_Blocks
Eclipse_Building_BlocksEclipse_Building_Blocks
Eclipse_Building_BlocksRahul Shukla
 
OSGi Enablement For Apache Tuscany
OSGi Enablement For Apache TuscanyOSGi Enablement For Apache Tuscany
OSGi Enablement For Apache TuscanyRaymond Feng
 
More topics on Java
More topics on JavaMore topics on Java
More topics on JavaAhmed Misbah
 
Introduction to OSGi - Part-1
Introduction to OSGi - Part-1Introduction to OSGi - Part-1
Introduction to OSGi - Part-1kshanth2101
 
OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...
OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...
OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...mfrancis
 
A toolbox for statical analysis and transformation of OSGi bundles
A toolbox for statical analysis and transformation of OSGi bundlesA toolbox for statical analysis and transformation of OSGi bundles
A toolbox for statical analysis and transformation of OSGi bundlesOSGi User Group France
 
Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization toolsmukul bhardwaj
 
OSGi in 5 minutes
OSGi in 5 minutesOSGi in 5 minutes
OSGi in 5 minutesSerge Huber
 
Making Applications Work Together In Eclipse
Making Applications Work Together In EclipseMaking Applications Work Together In Eclipse
Making Applications Work Together In EclipseKaniska Mandal
 

Similar a Deep dive into OSGi Lifecycle Layer (20)

OSGI Modularity
OSGI ModularityOSGI Modularity
OSGI Modularity
 
Osgi
OsgiOsgi
Osgi
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Intro To OSGi
Intro To OSGiIntro To OSGi
Intro To OSGi
 
Intro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse VirgoIntro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse Virgo
 
Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)Open Services Gateway Initiative (OSGI)
Open Services Gateway Initiative (OSGI)
 
Eclipse_Building_Blocks
Eclipse_Building_BlocksEclipse_Building_Blocks
Eclipse_Building_Blocks
 
OSGi Enablement For Apache Tuscany
OSGi Enablement For Apache TuscanyOSGi Enablement For Apache Tuscany
OSGi Enablement For Apache Tuscany
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Introduction to OSGi - Part-1
Introduction to OSGi - Part-1Introduction to OSGi - Part-1
Introduction to OSGi - Part-1
 
Osgi Sun 20080820
Osgi Sun 20080820Osgi Sun 20080820
Osgi Sun 20080820
 
OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...
OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...
OSGi-friendly bytecode weaving – enhance your classes, not your dependency gr...
 
A toolbox for statical analysis and transformation of OSGi bundles
A toolbox for statical analysis and transformation of OSGi bundlesA toolbox for statical analysis and transformation of OSGi bundles
A toolbox for statical analysis and transformation of OSGi bundles
 
Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
 
OSGi in 5 minutes
OSGi in 5 minutesOSGi in 5 minutes
OSGi in 5 minutes
 
Making Applications Work Together In Eclipse
Making Applications Work Together In EclipseMaking Applications Work Together In Eclipse
Making Applications Work Together In Eclipse
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Java 9
Java 9Java 9
Java 9
 

Deep dive into OSGi Lifecycle Layer

  • 1. Deep Dive into OSGi (Lifecycle Layer) (Chapter 3) Aruna Karunarathna
  • 2. Discussion o Software Lifecycle Management o Lifecycle of a Bundle o The Lifecycle API o Explore relationship between modules and lifecycle layer o Demo (Sample Application)
  • 3. Software Lifecycle Management ● Installation ○ Along with the all dependencies ● Execution ○ Acquiring resources and start functionalities it suppose to do, if no longer needed stop application ● Update ○ Update application ● Uninstall ○ Remove application when no longer needed Note - Most Applications(e.g Standard Java app ) do above steps as whole; for modular applications, using fine grained lifecycle management it is possible for manage lifecycle of individual modules.
  • 4. OSGi Lifecycle Layer o Internal to your application The lifecycle layer precisely defines the bundle lifecycle operations. These lifecycle operations allow you to manage and evolve your application by dynamically changing the composition of bundles inside a running framework o External to your application The lifecycle layer defines how your bundles gain access to their execution context, which provides them with a way to interact with the OSGi framework and the facilities it provides at execution time
  • 5. OSGi Bundle Lifecycle o Modular Layer - Relies on Metadata provided by bundle o Lifecycle Layer - API provided by OSGi There is no other way to deal with the OSGi Life Cycle other than the provided API. ● Which is very powerful ● OSGi core framework doesn’t mandate any particular mechanism of interacting with the lifecycle API
  • 6. OSGi Framework role in Lifecycle - Installation o Standard Java - Place Jar files in classpath o OSGi Framework - Install bundles to framework
  • 7. OSGi Framework role in Lifecycle - Installation Cntd... o Inherent Dynamism The OSGi framework supports the full bundle lifecycle at execution time. This is similar to modifying what’s on the classpath dynamically in a Standard java app. o Persist the Cache This means the next time you start the framework, any previously installed bundles are automatically reloaded from the bundle cache, and the original JAR files are no longer necessary Note- You can disable the persist bundle cache if you need a fresh framework start.
  • 8. Bundle Activator Manifest Entry o Defines the bundle’s identity o Specifies the packages on which this bundle depends o Specifies the packages on which this bundle exports o Declares additional human-readable information Manifest-Version: 1.0 Bnd-LastModified: 1405099135557 Build-Jdk: 1.7.0_55 Built-By: aruna Bundle-Activator: org.sample.Activator Bundle-ManifestVersion: 2 Bundle-Name: sample Bundle-SymbolicName: sample Bundle-Vendor: WSO2 Inc Bundle-Version: 1.0.0 Created-By: Apache Maven Bundle Plugin Export-Package: org.sample;uses:="org.osgi.framework"; version="1.0.0" Import-Package: org.osgi.framework;version="[1.7,2)" Tool: Bnd-2.1.0.20130426-122213
  • 9. Bundle Activator Manifest Entry cntd... o Bundle Activator Manifest Entry is the hook to the Bundle execution entry point. o Similar to the Main Method of a Jar file?.. o Header value specifies the name of a reachable class o Either a class in an Imported Package o A class in the Bundle class path o This class implements the org.osgi.framework.BundleActivator interface, and implements the following two methods. o Can use these two methods to customize the behaviours when the bundle is started and stopped. public interface BundleActivator { void start(org.osgi.framework.BundleContext bundleContext) throws java.lang.Exception; void stop(org.osgi.framework.BundleContext bundleContext) throws java.lang.Exception; }
  • 10. Bundle Activator Manifest Entry cntd... o When the bundle installed and started, OSGi Framework creates an instance of Bundle Activator class and call the start() method. o When the bundle stop is initiated, OSGi Framework call the stop() method. o In practice when the stop is called, you should undo everything you did in the start method. o The activator instance on which start() is called is the same instance on which stop() is called. o The activator instance is discarded and isn’t used again, after stop() is called. o If the bundle is subsequently restarted after being stopped, a new activator instance is created, and the start() and stop() methods are invoked on it as appropriate.
  • 11. Bundle Activator vs Threading o OSGi is designed around the normal java thread abstraction. o The framework assumes that you handle the thread management and the programs are correctly synchronized and thread safe. o The OSGi libraries are thread safe, and callbacks are normally done in a thread safe manner o for. e.g The same thread called the start() method, is guaranteed by the framework to be called the stop() method in order not concurrently. o If threads are used in a bundle make sure that all threads are stopped when the stop() method returns.
  • 12. Bundle Context o Can be accessed via start() and stop() of Bundle Activator class o Bundle context object is its role as the unique execution context of its associated bundle o Valid while the bundle is active. (The time range from the framework call start() up until to the stop() is called ) o Gain access to two types of methods o Related to deployment and lifecycle management. o Related to bundle interaction via services. o They should be treated as sensitive or private objects and not passed freely among bundles
  • 13. Bundle o For each installed bundle, the framework creates a Bundle object o From Bundle object, a bundle can identified by two additional forms o Bundle Identifier o Bundle Location o Bundle object persist over the framework executions when the installed bundles are reloaded from the framework’s cache.
  • 14. Bundle cntd... o Why we need two execution time identifiers?.. o Can’t we use Bundle Symbolic name and version to identify?.. History plays a role here. The notion of using a bundle’s symbolic name and version to uniquely identify it didn’t exist in versions of the specification prior to R4. Therefore, prior to R4, it made sense to have internally and externally assigned identifiers. Now it makes less sense, because the bundle’s symbolic name and version pair are externally defined and explicitly recognized internally by the framework.
  • 15. The System Bundle o Execution time framework is represented as a bundle, with Bundle ID set to 0 and it is called as the System Bundle. o You don’t explicitly install the System Bundle, it always exists while the framework is running o Follows the same lifecycle as other Bundles in the framework, and you can manipulate it with the same operations as normal bundles o Lifecycle operations performed on the system bundle have special meanings when compared to normal bundles One example of the special meaning is evident when you stop the system bundle. Intuitively, stopping the system bundle shuts down the framework in a well behaved manner. It stops all other bundles first and then shuts itself down completely.
  • 17. Bundle Start o Calls the Bundle.start() of the respective Bundle Object o If the Bundle is INSTALLED state, it transitions to ACTIVE state via the RESOLVED and STARTING states. o If the Bundle is UNINSTALLED, throws an IllegalStateException. o If the Bundle is in STARTING or STOPPING state start() is blocked until it enters ACTIVE or RESOLVED. o If the bundle is in ACTIVE state, calling start has no effect. o If the Bundle can’t satisfy it’s dependencies, calling Start will result in throwing a BundleException o If a BundleActivator is specified, will call the start() in the BundleActivator class
  • 18. Bundle Stop o Calls the Bundle.stop() of the respective Bundle Object. o If the Bundle is in UNINSTALLED state, throws an IllegalStateException. o If the Bundle is in STARTING or STOPPING state stop() is blocked until it enters START or RESOLVED. o If a BundleActivator is specified, will call the stop() in the BundleActivator class o If the stop() method in the BundleActivator class, throws an exception, a BundleException is throws by the Bundle.stop() method
  • 19. Update Command o Bundle.update() comes in two forms o Without parameters o With parameter InputStream o If the Bundle is in ACTIVE state, first the Bundle.stop() Needs to be called by the framework. o The update happens either in INSTALLED or RESOLVED state. o If the Bundle is in UNINSTALLED state, the framework will thrown an IllegalStateException. Tips - Don’t use the Bundle-UpdateLocation MF header.
  • 20. Uninstall Command o Calls the Bundle.uninstall() method in the framework. o If the Bundle is in ACTIVE state, first the Bundle.stop() Needs to be called by the framework. o If the Bundle is already in UNINSTALLED state, the framework will throw an IllegalStateException. Tips - bundle shouldn’t attempt to stop, update, uninstall itself (Bundle Suicide)
  • 21. Bundle cache and framework restarts o A Bundle can be installed in 2 ways o Providing the url for the bundle o Providing bundle as an inputstream o Framework reads the bundle JAR file and saves a copy in a private area known as the bundle cache o Installing a bundle into the framework is a persistent operation o After the bundle is installed, the framework no longer needs the original copy of the bundle JAR file
  • 22. Bundle cache and framework restarts cntd... o Framework persists Bundle status too.. o Bundle start() is called, the framework persistently marked as STARTED o Bundle stop() is called, the framework persistently marked as STOPPED o What about update and uninstall?.. o Remove the existing bundle from the cache o Install a totally new bundle in the persistent cache
  • 23. Bundle Configuration Properties o BundleContext.getProperty() method to retrieve the properties o Avoid the global aspect of System.getProperty(), and provides per framework instance properties o If not found in the BundleContext scope search in the global System scope o If you need to use these standard properties, you can use the constants defined in the org.osgi.framework.Constants class
  • 24. Listening for events o OSGi framework supports two types of events: BundleEvents and FrameworkEvents o The former event type reports changes in the lifecycle of bundles, whereas the latter reports framework-related changes o The BundleContext object has methods to register BundleListener and FrameworkListener objects for receiving BundleEvent and FrameworkEvent notifications, respectively o How to implement BundleListener and FrameworkListener in your code?. a. Create a new class which Implements BundleListener or FrameworkListener b. Implement the bundleChanged(BundleEvent) or frameworkEvent(FrameworkEvent) methods respectively. c. Register by creating a new Object of the implemented class to the BundleContext as a Listener using the bundleContext.addBundleListener() or bundleContext.addFrameworkListener() respectively. o No need to call the removeBundleListener() or removeFrameworkListener(), which will automatically removed when the bundle is stopped.
  • 25. Sample code for listening for events public class MyListener implements BundleActivator , FrameworkListener , BundleListener{ @Override public void start(BundleContext bundleContext) throws Exception { bundleContext.addBundleListener(new MyListener ()); bundleContext.addFrameworkListener(new MyListener ()); } @Override public void stop(BundleContext bundleContext) throws Exception { } @Override public void bundleChanged(BundleEvent event) { //TODO - implement } @Override public void frameworkEvent(FrameworkEvent event) { //TODO - implement } }
  • 26. Framework events o FrameworkEvent.STARTED —Indicates the framework has performed all initialization and has finished starting up. o FrameworkEvent.INFO —Indicates some information of general interest in various situations. o FrameworkEvent.WARNING —Indicates a warning. Not crucial, but may indicate a potential error. o FrameworkEvent.ERROR —Indicates an error. Requires immediate attention. o FrameworkEvent.PACKAGES_REFRESHED —Indicates the framework has refreshed some shared packages. o FrameworkEvent.STARTLEVEL_CHANGED —Indicates the framework has changed its start level.
  • 27. Bundle Events o BundleEvent.INSTALLED — Indicates a bundle was installed o BundleEvent.RESOLVED — Indicates a bundled was resolved o BundleEvent.STARTED — Indicates a bundle was started o BundleEvent.STOPPED — Indicates a bundle was stopped o BundleEvent.UPDATED — Indicates a bundle was updated o BundleEvent.UNINSTALLED — Indicates a bundle was uninstalled o BundleEvent.UNRESOLVED — Indicates a bundle was unresolved Following events are only send to SynchronousBundleListeners (listener is notified during the processing of the event - HANDLE WITH CARE…!!!) BundleEvent.STARTING — Indicates a bundle is about to be started BundleEvent.STOPPING — Indicates a bundle is about to be
  • 28. DEMO
  • 29. References OSGi Alliance Specifications http://www.osgi.org/Specifications/HomePage OSGI in Action - CREATING MODULAR APPLICATIONS IN JAVA Sample - https://github.com/arunasujith/osgi-sample