SlideShare a Scribd company logo
1 of 31
Practical OSGi
   Sten Roger Sandvik
       Enonic AS

    srs@enonic.com
What is OSGi?
• A module system for Java
  The Dynamic Module System for Java™.


• Dynamic modules (bundles)
  Installing, starting, stopping, updating and uninstalling modules at runtime.


• Service oriented
  Services can be registered and consumed at runtime.


• A worldwide standard
  OSGi Alliance. Release R1 in 2000. Currenty at release R4.1.
Key Benefits
• No more “JAR” hell
  Can have multiple versions of same library.


• Reuse packaged modules
  Allows 3rd party prepackaged modules to be installed.


• Less server restarts
  Update modules at runtime.


• Simplifies multi-team projects
  Can partition the application into smaller modules.
Key Benefits (2)
• Enables smaller systems
  By breaking it into smaller pieces (some optional).


• Multiple runtime options
  Standalone, Client, Server, Embedded.


• Multiple implementations
  Eclipse Equinox, Apache Felix, Knopflerfish.


• Very high adaption rate
  Apache, Sun, Oracle, IBM, BMW and Enonic are all using it.
Theory
Framework Layers
• L3 - Service                                               L3
  Publish/find/bind service model to decouple bundles.
                                                             L2
• L2 - Lifecycle                                             L1
  Independent lifecycle of bundles without JVM restarts.


• L1 - Module                                                L0
  A module (or bundle) uses classes from other
  bundles in a controlled way.


• L0 - Execution environment
  Well defined profiles (JavaSE, CDC) that define the JVM environment.
Module Layer
• Unit of deployment                         L3
  A module is called a bundle in OSGi.
                                             L2
• Standard JAR file with metadata             L1
  Metadata in META-INF/MANIFEST.MF


• Seperate classloader per bundle            L0
  Class sharing at the Java package level.


• Share only “interface” packages
  Share only API between bundles.
Module Layer (2)
• Multi-version support                           L3
  Different bundles can see different versions.
                                                  L2
• Manifest example                                L1
   Bundle-Name: Example
   Bundle-SymbolicName: net.foo.common
   Bundle-Version: 1.0.0
                                                  L0
   Import-Package:
     org.osgi.framework;version=”1.3”,
     net.foo.api;version=”1.0.0”
   Export-Package:
     net.foo.common;version=”1.0.0”
   Private-Package:
     net.foo.common.internal,
     net.foo.common.internal.codec
   Bundle-ManifestVersion: 2
Lifecycle Layer
• Managed lifecycle                                   L3
  Managed states for each bundle.
                                                      L2
• Update existing bundles                             L1
  Dynamically install, start, update and uninstall.

                                                      L0
Service Layer
• Service registry                                          L3
  Publish/find/bind services at runtime.
                                                            L2
• Bind interfaces                                           L1
  Bind interfaces - not implementations.

                                                            L0
                                     Registry

                       publish                   find


                      Provider                  Requester
                                     interact
Practice
Password Encoder
• Password encoder application
  Simple JVM client that uses password encoders.


• Encoders are pluggable
  Multiple implementations. Can be stopped/started at runtime.
Project Structure
• API Bundle                                                    API
  Holds all public avaliable APIs.
                                                           Encoder
• Encoder Bundle                                           Client
  Provides a password encoder implementation.
                                                       Parent
• Client Bundle
  Client bundle that uses one or more password encoders.
API Bundle
• Provides the API                                  API
  Simple PasswordEncoder interface.
                                                  Encoder
• Exports package                                 Client
  Export the API (net.foo.api) package so other
  bundles can see it.
Password Encoder
package net.foo.api;
                                                               API
/**
  * Simple interface that defines the password
                                                          Encoder
  * encoder.
  */
public interface PasswordEncoder
                                                              Client
{
   /**
     * Returns the name of this encoder.
     */
   public String getName();

    /**
     * Encode the password and return the encoded password.
     */
    public String encode(String password);
}
Manifest
• Exports the package                                   API
  Exports package (net.foo.api) with right version.
                                                      Encoder
     ...
     Bundle-Name: Example - API

                                                      Client
     Bundle-SymbolicName: net.foo.api
     Export-Package:
       net.foo.api;version=”1.0.0”
     ...
Encoder Bundle
• Uses the API                                                 API
  Imports proper API package (net.foo.api).
                                                           Encoder
• Registers a provider                                       Client
  Registers a PasswordEncoder provider implementation
  as a service.


• Hides the implementation
  Hides implementation from other bundles by using Private-Package.
Register a Service
• Use a BundleActivator                                          API
  Implement bundle activator that handle lifecycle.
                                                            Encoder
• Register on start                                             Client
  Register service on when bundle is started.


• Unregister at stop
  Unregister the service when bundle is stopped.


• Add proper metadata
  Do not forget to add Bundle-Activator metadata in manifest.
Bundle Activator
package net.foo.encoder;
                                                 API
import net.foo.api.*;
import org.osgi.framework.*;

                                               Encoder
public class Activator
  implements BundleActivator

                                               Client
{
  private ServiceRegistration reg;

    public void start(BundleContext context)
    {
      this.reg = context.registerService(
        PasswordEncoder.class.getName(),
        new ReversePasswordEncoder(), null);
    }

    public void stop(BundleContext context)
    {
      this.reg.unregister();
    }
}
Manifest
• Declare BundleActivator                                   API
  Set the bundle activator classname in manifest.
                                                          Encoder
• Import used packages                                    Client
  Import net.foo.api and org.osgi.framework
  packages with right version.


• Hide implementation package
  Declare net.foo.encoder package as a private package.
Manifest (2)
...

                                         API
Bundle-Name: Example - Encoder
Bundle-SymbolicName: net.foo.encoder
Bundle-Activator:

                                       Encoder
  net.foo.encoder.Activator
Import-Package:
  net.foo.api;version=”1.0.0”,
  org.osgi.framework;version=”1.3”
                                       Client
Private-Package:
  net.foo.encoder
...
Client Bundle
• Uses the API                    API
  Does not see the encoder implementation.
                                Encoder
• Track PasswordEncoder’s        Client
  Track available password encoder providers.


• Encodes password based on encoder
  Finds right encoder and encodes the password.
Locating Services
• Services are dynamic                                         API
  All services can be added and removed runtime.
                                                            Encoder
• Not always available on init                               Client
  Do not assume that you can always obtain a service
  during initialization.


• Use ServiceTracker
  Use ServiceTracker to track available services. Remember to open()
  and close() the tracker.
Using ServiceTracker
public class Activator
  implements BundleActivator
                                                                   API
{
  private ServiceTracker tracker;


                                                                 Encoder
  public void start(BundleContext context)
  {
    tracker = new ServiceTracker(

                                                                 Client
      context, PasswordEncoder.class.getName(), null);
    tracker.open();
  }

  public void stop(BundleContext context)
  {
    tracker.close();
  }                         public class MyConsumer
}                           {
                               private ServiceTracker tracker;

                               ...

                               public void consumeServices()
                               {
                                 Object[] services = tracker.getServices();
                               }
                           }
Client Implementation
public class Client
                                                                       API
{
  private ServiceTracker tracker;

                                                                 Encoder
    ...

    public String encode(String method, String password)
                                                                      Client
    {
       for (Object service : tracker.getServices()) {
         PasswordEncoder enc = (PasswordEncoder)service;

            if (enc.getName().equals(method)) {
              return enc.encode(password);
            }
        }

          throw new IllegalArgumentException(“Provider not found”);
    }
}
Manifest
...
                                          API
Bundle-Name: Example - Client
Bundle-SymbolicName: net.foo.client
Bundle-Activator:
                                        Encoder
  net.foo.client.Activator
Import-Package:
  net.foo.api;version=”1.0.0”,

                                        Client
  org.osgi.framework;version=”1.3”,
  org.osgi.util.tracker;version=”1.3”
Private-Package:
  net.foo.client
...
Improvements
• Use a declarative service model
  Hides OSGi details. Makes service tracking easy. Spring DM is one
  implementation.


• Use automatic manifest creation
  Use Maven Bundle Plugin (Apache Felix Project) to create and validate
  manifest entries at build time.
Demo
Tools Used
• Maven 2
  Build the project using Maven 2 using standard layout.


• Maven Bundle Plugin
  Creates and validates the MANIFEST.MF. Based on BND.


• Maven Pax Plugin
  Running the OSGi application using Pax Runner.


• Felix OSGi Container
  Implementation of R4.1 specification.
3rd Party Bundles
• Pax Web
  Web container based on Jetty. Implementation of HttpService.


• Pax Logging
  Logging abstraction and LogService implementation. Possible to use SLF4J,
  Commons Logging and Log4J in bundles.


• Felix WebConsole
  Web Console to visualize bundles and services.
Q?


srs@enonic.com

More Related Content

What's hot

Modules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemModules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemTim Ellison
 
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application DevelopmentOSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application DevelopmentSanjeeb Sahoo
 
Java Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily JiangJava Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily JiangJAX London
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New FeaturesAli BAKAN
 
OSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsOSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsArun Gupta
 
Java 9: Deep Dive into Modularity and Dealing with Migration Issues
Java 9: Deep Dive into Modularity and Dealing with Migration IssuesJava 9: Deep Dive into Modularity and Dealing with Migration Issues
Java 9: Deep Dive into Modularity and Dealing with Migration IssuesGlobalLogic Ukraine
 
Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...
Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...
Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...Milen Dyankov
 
JBI and PEtALS Presentation at SOA4ALL architecture meeting
JBI and PEtALS Presentation at SOA4ALL architecture meetingJBI and PEtALS Presentation at SOA4ALL architecture meeting
JBI and PEtALS Presentation at SOA4ALL architecture meetingChristophe Hamerling
 
OSGi in 5 minutes
OSGi in 5 minutesOSGi in 5 minutes
OSGi in 5 minutesSerge Huber
 
Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7Azilen Technologies Pvt. Ltd.
 
Managing Change
Managing ChangeManaging Change
Managing ChangeMirko Jahn
 
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
 

What's hot (20)

Modular Java
Modular JavaModular Java
Modular Java
 
Desiging for Modularity with Java 9
Desiging for Modularity with Java 9Desiging for Modularity with Java 9
Desiging for Modularity with Java 9
 
Osgi platform
Osgi platformOsgi platform
Osgi platform
 
Modules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemModules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module System
 
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application DevelopmentOSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
OSGi and Java EE: A Hybrid Approach to Enterprise Java Application Development
 
Comparison between Oracle JDK, Oracle OpenJDK, and Red Hat OpenJDK.v1.0.20191009
Comparison between Oracle JDK, Oracle OpenJDK, and Red Hat OpenJDK.v1.0.20191009Comparison between Oracle JDK, Oracle OpenJDK, and Red Hat OpenJDK.v1.0.20191009
Comparison between Oracle JDK, Oracle OpenJDK, and Red Hat OpenJDK.v1.0.20191009
 
Java Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily JiangJava Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily Jiang
 
Beyond OSGi Software Architecture
Beyond OSGi Software ArchitectureBeyond OSGi Software Architecture
Beyond OSGi Software Architecture
 
OSGi Presentation
OSGi PresentationOSGi Presentation
OSGi Presentation
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
 
OSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worldsOSGi & Java EE in GlassFish - Best of both worlds
OSGi & Java EE in GlassFish - Best of both worlds
 
Modules or microservices?
Modules or microservices?Modules or microservices?
Modules or microservices?
 
Java 9: Deep Dive into Modularity and Dealing with Migration Issues
Java 9: Deep Dive into Modularity and Dealing with Migration IssuesJava 9: Deep Dive into Modularity and Dealing with Migration Issues
Java 9: Deep Dive into Modularity and Dealing with Migration Issues
 
Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...
Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...
Moved to https://slidr.io/azzazzel/leveraging-osgi-to-create-extensible-plugi...
 
JBI and PEtALS Presentation at SOA4ALL architecture meeting
JBI and PEtALS Presentation at SOA4ALL architecture meetingJBI and PEtALS Presentation at SOA4ALL architecture meeting
JBI and PEtALS Presentation at SOA4ALL architecture meeting
 
OSGi in 5 minutes
OSGi in 5 minutesOSGi in 5 minutes
OSGi in 5 minutes
 
OSGi Blueprint Services
OSGi Blueprint ServicesOSGi Blueprint Services
OSGi Blueprint Services
 
Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7Step by step guide to create theme for liferay dxp 7
Step by step guide to create theme for liferay dxp 7
 
Managing Change
Managing ChangeManaging Change
Managing Change
 
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
 

Viewers also liked

Kemampanan bandar tempat tinggal saya
Kemampanan bandar tempat tinggal sayaKemampanan bandar tempat tinggal saya
Kemampanan bandar tempat tinggal sayazaira zue
 
Cостояние и перспективы машинного интеллекта
Cостояние и перспективы машинного интеллектаCостояние и перспективы машинного интеллекта
Cостояние и перспективы машинного интеллектаSkolkovo Robotics Center
 
Test Automation Without the Headache: Agile Tour Vienna 2015
Test Automation Without the Headache: Agile Tour Vienna 2015 Test Automation Without the Headache: Agile Tour Vienna 2015
Test Automation Without the Headache: Agile Tour Vienna 2015 gojkoadzic
 
How to build an effective IoT demo with OSGi - Derek Baum & Walt Bowers
How to build an effective IoT demo with OSGi - Derek Baum & Walt BowersHow to build an effective IoT demo with OSGi - Derek Baum & Walt Bowers
How to build an effective IoT demo with OSGi - Derek Baum & Walt Bowersmfrancis
 
Force Measurement - Best load cell calibration practices
Force Measurement - Best load cell calibration practices Force Measurement - Best load cell calibration practices
Force Measurement - Best load cell calibration practices Henry Zumbrun
 
441 presentation 5
441 presentation 5441 presentation 5
441 presentation 5Ashwin Fujii
 
Electromagnetic braking
Electromagnetic brakingElectromagnetic braking
Electromagnetic brakingSurya Prakash
 
Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...
Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...
Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...Super Professeur
 
Ppt on project_ELECTOMAGNETIC_BRAKING_SYSTEM
Ppt on project_ELECTOMAGNETIC_BRAKING_SYSTEMPpt on project_ELECTOMAGNETIC_BRAKING_SYSTEM
Ppt on project_ELECTOMAGNETIC_BRAKING_SYSTEMANUPAM SINGH
 
Django から各種チャットツールに通知するライブラリを作った話
Django から各種チャットツールに通知するライブラリを作った話Django から各種チャットツールに通知するライブラリを作った話
Django から各種チャットツールに通知するライブラリを作った話Yusuke Miyazaki
 
APIドキュメントの話 #sphinxjp
APIドキュメントの話 #sphinxjpAPIドキュメントの話 #sphinxjp
APIドキュメントの話 #sphinxjpTakeshi Komiya
 
Infinity OSD Overview
Infinity OSD OverviewInfinity OSD Overview
Infinity OSD Overviewcaleb7777
 
「Python言語」はじめの一歩 / First step of Python
「Python言語」はじめの一歩 / First step of Python「Python言語」はじめの一歩 / First step of Python
「Python言語」はじめの一歩 / First step of PythonTakanori Suzuki
 
Atomic hyrogen arc welding
Atomic hyrogen arc weldingAtomic hyrogen arc welding
Atomic hyrogen arc weldingIlyas Hussain
 

Viewers also liked (20)

A Sangue Frio
A Sangue FrioA Sangue Frio
A Sangue Frio
 
Ddp médico ocupacional v1
Ddp médico ocupacional v1Ddp médico ocupacional v1
Ddp médico ocupacional v1
 
Kemampanan bandar tempat tinggal saya
Kemampanan bandar tempat tinggal sayaKemampanan bandar tempat tinggal saya
Kemampanan bandar tempat tinggal saya
 
Faktor biofisiologis
Faktor biofisiologisFaktor biofisiologis
Faktor biofisiologis
 
Cостояние и перспективы машинного интеллекта
Cостояние и перспективы машинного интеллектаCостояние и перспективы машинного интеллекта
Cостояние и перспективы машинного интеллекта
 
Test Automation Without the Headache: Agile Tour Vienna 2015
Test Automation Without the Headache: Agile Tour Vienna 2015 Test Automation Without the Headache: Agile Tour Vienna 2015
Test Automation Without the Headache: Agile Tour Vienna 2015
 
BRAKE DAY2
BRAKE DAY2BRAKE DAY2
BRAKE DAY2
 
How to build an effective IoT demo with OSGi - Derek Baum & Walt Bowers
How to build an effective IoT demo with OSGi - Derek Baum & Walt BowersHow to build an effective IoT demo with OSGi - Derek Baum & Walt Bowers
How to build an effective IoT demo with OSGi - Derek Baum & Walt Bowers
 
Force Measurement - Best load cell calibration practices
Force Measurement - Best load cell calibration practices Force Measurement - Best load cell calibration practices
Force Measurement - Best load cell calibration practices
 
441 presentation 5
441 presentation 5441 presentation 5
441 presentation 5
 
Alfred preso 1
Alfred preso 1Alfred preso 1
Alfred preso 1
 
Electromagnetic braking
Electromagnetic brakingElectromagnetic braking
Electromagnetic braking
 
Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...
Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...
Etude de gestion BAC STMG 2017 – épreuve anticipée STMG en Sciences de gestio...
 
Ppt on project_ELECTOMAGNETIC_BRAKING_SYSTEM
Ppt on project_ELECTOMAGNETIC_BRAKING_SYSTEMPpt on project_ELECTOMAGNETIC_BRAKING_SYSTEM
Ppt on project_ELECTOMAGNETIC_BRAKING_SYSTEM
 
Django から各種チャットツールに通知するライブラリを作った話
Django から各種チャットツールに通知するライブラリを作った話Django から各種チャットツールに通知するライブラリを作った話
Django から各種チャットツールに通知するライブラリを作った話
 
APIドキュメントの話 #sphinxjp
APIドキュメントの話 #sphinxjpAPIドキュメントの話 #sphinxjp
APIドキュメントの話 #sphinxjp
 
Infinity OSD Overview
Infinity OSD OverviewInfinity OSD Overview
Infinity OSD Overview
 
「Python言語」はじめの一歩 / First step of Python
「Python言語」はじめの一歩 / First step of Python「Python言語」はじめの一歩 / First step of Python
「Python言語」はじめの一歩 / First step of Python
 
Automobile Chassis
Automobile Chassis  Automobile Chassis
Automobile Chassis
 
Atomic hyrogen arc welding
Atomic hyrogen arc weldingAtomic hyrogen arc welding
Atomic hyrogen arc welding
 

Similar to Practical OSGi

[apidays LIVE HONK KONG] - OAS to Managed API in Seconds
[apidays LIVE HONK KONG] - OAS to Managed API in Seconds[apidays LIVE HONK KONG] - OAS to Managed API in Seconds
[apidays LIVE HONK KONG] - OAS to Managed API in SecondsWSO2
 
Skype testing overview
Skype testing overviewSkype testing overview
Skype testing overviewQA Club Kiev
 
Skype testing overview
Skype testing overviewSkype testing overview
Skype testing overviewQA Club Kiev
 
Puppet Camp Phoenix 2015: Continuous Integration Using Puppet (Intermediate)
Puppet Camp Phoenix 2015:  Continuous Integration Using Puppet (Intermediate)Puppet Camp Phoenix 2015:  Continuous Integration Using Puppet (Intermediate)
Puppet Camp Phoenix 2015: Continuous Integration Using Puppet (Intermediate)Puppet
 
Continuous Integration with Puppet
Continuous Integration with PuppetContinuous Integration with Puppet
Continuous Integration with PuppetMiguel Zuniga
 
Five Steps to Add AppUp .NET SDK to Microsoft Visual Studio
Five Steps to Add AppUp .NET SDK to Microsoft Visual StudioFive Steps to Add AppUp .NET SDK to Microsoft Visual Studio
Five Steps to Add AppUp .NET SDK to Microsoft Visual Studioreadwritehack
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application DevelopmentRamesh Prasad
 
Eclipse Kura Shoot a-pi
Eclipse Kura Shoot a-piEclipse Kura Shoot a-pi
Eclipse Kura Shoot a-piEclipse Kura
 
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
 
OpenAPI Generator The Babel Fish of The API World - apidays Live Australia
OpenAPI Generator The Babel Fish of The API World - apidays Live AustraliaOpenAPI Generator The Babel Fish of The API World - apidays Live Australia
OpenAPI Generator The Babel Fish of The API World - apidays Live AustraliaCliffano Subagio
 
OpenAPI Generator The Babel Fish of The API World - apidays Live Paris
OpenAPI Generator The Babel Fish of The API World - apidays Live ParisOpenAPI Generator The Babel Fish of The API World - apidays Live Paris
OpenAPI Generator The Babel Fish of The API World - apidays Live ParisCliffano Subagio
 
Review: Apitrace and Vogl
Review: Apitrace and VoglReview: Apitrace and Vogl
Review: Apitrace and VoglGao Yunzhong
 
Intro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse VirgoIntro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse VirgoGordon Dickens
 
How to Dockerize Your .NET Core API
How to Dockerize Your .NET Core APIHow to Dockerize Your .NET Core API
How to Dockerize Your .NET Core APILakshman S
 
How to Install and Use Kubernetes by Weaveworks
How to Install and Use Kubernetes by Weaveworks How to Install and Use Kubernetes by Weaveworks
How to Install and Use Kubernetes by Weaveworks Weaveworks
 
Getting started with the NDK
Getting started with the NDKGetting started with the NDK
Getting started with the NDKKirill Kounik
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCTim Burks
 
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...BeMyApp
 

Similar to Practical OSGi (20)

[apidays LIVE HONK KONG] - OAS to Managed API in Seconds
[apidays LIVE HONK KONG] - OAS to Managed API in Seconds[apidays LIVE HONK KONG] - OAS to Managed API in Seconds
[apidays LIVE HONK KONG] - OAS to Managed API in Seconds
 
Skype testing overview
Skype testing overviewSkype testing overview
Skype testing overview
 
Skype testing overview
Skype testing overviewSkype testing overview
Skype testing overview
 
Puppet Camp Phoenix 2015: Continuous Integration Using Puppet (Intermediate)
Puppet Camp Phoenix 2015:  Continuous Integration Using Puppet (Intermediate)Puppet Camp Phoenix 2015:  Continuous Integration Using Puppet (Intermediate)
Puppet Camp Phoenix 2015: Continuous Integration Using Puppet (Intermediate)
 
Continuous Integration with Puppet
Continuous Integration with PuppetContinuous Integration with Puppet
Continuous Integration with Puppet
 
Five Steps to Add AppUp .NET SDK to Microsoft Visual Studio
Five Steps to Add AppUp .NET SDK to Microsoft Visual StudioFive Steps to Add AppUp .NET SDK to Microsoft Visual Studio
Five Steps to Add AppUp .NET SDK to Microsoft Visual Studio
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
Eclipse Kura Shoot a-pi
Eclipse Kura Shoot a-piEclipse Kura Shoot a-pi
Eclipse Kura Shoot a-pi
 
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...
 
OpenAPI Generator The Babel Fish of The API World - apidays Live Australia
OpenAPI Generator The Babel Fish of The API World - apidays Live AustraliaOpenAPI Generator The Babel Fish of The API World - apidays Live Australia
OpenAPI Generator The Babel Fish of The API World - apidays Live Australia
 
Mina2
Mina2Mina2
Mina2
 
Warum OSGi?
Warum OSGi?Warum OSGi?
Warum OSGi?
 
OpenAPI Generator The Babel Fish of The API World - apidays Live Paris
OpenAPI Generator The Babel Fish of The API World - apidays Live ParisOpenAPI Generator The Babel Fish of The API World - apidays Live Paris
OpenAPI Generator The Babel Fish of The API World - apidays Live Paris
 
Review: Apitrace and Vogl
Review: Apitrace and VoglReview: Apitrace and Vogl
Review: Apitrace and Vogl
 
Intro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse VirgoIntro to OSGi and Eclipse Virgo
Intro to OSGi and Eclipse Virgo
 
How to Dockerize Your .NET Core API
How to Dockerize Your .NET Core APIHow to Dockerize Your .NET Core API
How to Dockerize Your .NET Core API
 
How to Install and Use Kubernetes by Weaveworks
How to Install and Use Kubernetes by Weaveworks How to Install and Use Kubernetes by Weaveworks
How to Install and Use Kubernetes by Weaveworks
 
Getting started with the NDK
Getting started with the NDKGetting started with the NDK
Getting started with the NDK
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPC
 
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
 

Recently uploaded

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

Practical OSGi

  • 1. Practical OSGi Sten Roger Sandvik Enonic AS srs@enonic.com
  • 2. What is OSGi? • A module system for Java The Dynamic Module System for Java™. • Dynamic modules (bundles) Installing, starting, stopping, updating and uninstalling modules at runtime. • Service oriented Services can be registered and consumed at runtime. • A worldwide standard OSGi Alliance. Release R1 in 2000. Currenty at release R4.1.
  • 3. Key Benefits • No more “JAR” hell Can have multiple versions of same library. • Reuse packaged modules Allows 3rd party prepackaged modules to be installed. • Less server restarts Update modules at runtime. • Simplifies multi-team projects Can partition the application into smaller modules.
  • 4. Key Benefits (2) • Enables smaller systems By breaking it into smaller pieces (some optional). • Multiple runtime options Standalone, Client, Server, Embedded. • Multiple implementations Eclipse Equinox, Apache Felix, Knopflerfish. • Very high adaption rate Apache, Sun, Oracle, IBM, BMW and Enonic are all using it.
  • 6. Framework Layers • L3 - Service L3 Publish/find/bind service model to decouple bundles. L2 • L2 - Lifecycle L1 Independent lifecycle of bundles without JVM restarts. • L1 - Module L0 A module (or bundle) uses classes from other bundles in a controlled way. • L0 - Execution environment Well defined profiles (JavaSE, CDC) that define the JVM environment.
  • 7. Module Layer • Unit of deployment L3 A module is called a bundle in OSGi. L2 • Standard JAR file with metadata L1 Metadata in META-INF/MANIFEST.MF • Seperate classloader per bundle L0 Class sharing at the Java package level. • Share only “interface” packages Share only API between bundles.
  • 8. Module Layer (2) • Multi-version support L3 Different bundles can see different versions. L2 • Manifest example L1 Bundle-Name: Example Bundle-SymbolicName: net.foo.common Bundle-Version: 1.0.0 L0 Import-Package: org.osgi.framework;version=”1.3”, net.foo.api;version=”1.0.0” Export-Package: net.foo.common;version=”1.0.0” Private-Package: net.foo.common.internal, net.foo.common.internal.codec Bundle-ManifestVersion: 2
  • 9. Lifecycle Layer • Managed lifecycle L3 Managed states for each bundle. L2 • Update existing bundles L1 Dynamically install, start, update and uninstall. L0
  • 10. Service Layer • Service registry L3 Publish/find/bind services at runtime. L2 • Bind interfaces L1 Bind interfaces - not implementations. L0 Registry publish find Provider Requester interact
  • 12. Password Encoder • Password encoder application Simple JVM client that uses password encoders. • Encoders are pluggable Multiple implementations. Can be stopped/started at runtime.
  • 13. Project Structure • API Bundle API Holds all public avaliable APIs. Encoder • Encoder Bundle Client Provides a password encoder implementation. Parent • Client Bundle Client bundle that uses one or more password encoders.
  • 14. API Bundle • Provides the API API Simple PasswordEncoder interface. Encoder • Exports package Client Export the API (net.foo.api) package so other bundles can see it.
  • 15. Password Encoder package net.foo.api; API /** * Simple interface that defines the password Encoder * encoder. */ public interface PasswordEncoder Client { /** * Returns the name of this encoder. */ public String getName(); /** * Encode the password and return the encoded password. */ public String encode(String password); }
  • 16. Manifest • Exports the package API Exports package (net.foo.api) with right version. Encoder ... Bundle-Name: Example - API Client Bundle-SymbolicName: net.foo.api Export-Package: net.foo.api;version=”1.0.0” ...
  • 17. Encoder Bundle • Uses the API API Imports proper API package (net.foo.api). Encoder • Registers a provider Client Registers a PasswordEncoder provider implementation as a service. • Hides the implementation Hides implementation from other bundles by using Private-Package.
  • 18. Register a Service • Use a BundleActivator API Implement bundle activator that handle lifecycle. Encoder • Register on start Client Register service on when bundle is started. • Unregister at stop Unregister the service when bundle is stopped. • Add proper metadata Do not forget to add Bundle-Activator metadata in manifest.
  • 19. Bundle Activator package net.foo.encoder; API import net.foo.api.*; import org.osgi.framework.*; Encoder public class Activator implements BundleActivator Client { private ServiceRegistration reg; public void start(BundleContext context) { this.reg = context.registerService( PasswordEncoder.class.getName(), new ReversePasswordEncoder(), null); } public void stop(BundleContext context) { this.reg.unregister(); } }
  • 20. Manifest • Declare BundleActivator API Set the bundle activator classname in manifest. Encoder • Import used packages Client Import net.foo.api and org.osgi.framework packages with right version. • Hide implementation package Declare net.foo.encoder package as a private package.
  • 21. Manifest (2) ... API Bundle-Name: Example - Encoder Bundle-SymbolicName: net.foo.encoder Bundle-Activator: Encoder net.foo.encoder.Activator Import-Package: net.foo.api;version=”1.0.0”, org.osgi.framework;version=”1.3” Client Private-Package: net.foo.encoder ...
  • 22. Client Bundle • Uses the API API Does not see the encoder implementation. Encoder • Track PasswordEncoder’s Client Track available password encoder providers. • Encodes password based on encoder Finds right encoder and encodes the password.
  • 23. Locating Services • Services are dynamic API All services can be added and removed runtime. Encoder • Not always available on init Client Do not assume that you can always obtain a service during initialization. • Use ServiceTracker Use ServiceTracker to track available services. Remember to open() and close() the tracker.
  • 24. Using ServiceTracker public class Activator implements BundleActivator API { private ServiceTracker tracker; Encoder public void start(BundleContext context) { tracker = new ServiceTracker( Client context, PasswordEncoder.class.getName(), null); tracker.open(); } public void stop(BundleContext context) { tracker.close(); } public class MyConsumer } { private ServiceTracker tracker; ... public void consumeServices() { Object[] services = tracker.getServices(); } }
  • 25. Client Implementation public class Client API { private ServiceTracker tracker; Encoder ... public String encode(String method, String password) Client { for (Object service : tracker.getServices()) { PasswordEncoder enc = (PasswordEncoder)service; if (enc.getName().equals(method)) { return enc.encode(password); } } throw new IllegalArgumentException(“Provider not found”); } }
  • 26. Manifest ... API Bundle-Name: Example - Client Bundle-SymbolicName: net.foo.client Bundle-Activator: Encoder net.foo.client.Activator Import-Package: net.foo.api;version=”1.0.0”, Client org.osgi.framework;version=”1.3”, org.osgi.util.tracker;version=”1.3” Private-Package: net.foo.client ...
  • 27. Improvements • Use a declarative service model Hides OSGi details. Makes service tracking easy. Spring DM is one implementation. • Use automatic manifest creation Use Maven Bundle Plugin (Apache Felix Project) to create and validate manifest entries at build time.
  • 28. Demo
  • 29. Tools Used • Maven 2 Build the project using Maven 2 using standard layout. • Maven Bundle Plugin Creates and validates the MANIFEST.MF. Based on BND. • Maven Pax Plugin Running the OSGi application using Pax Runner. • Felix OSGi Container Implementation of R4.1 specification.
  • 30. 3rd Party Bundles • Pax Web Web container based on Jetty. Implementation of HttpService. • Pax Logging Logging abstraction and LogService implementation. Possible to use SLF4J, Commons Logging and Log4J in bundles. • Felix WebConsole Web Console to visualize bundles and services.

Editor's Notes