IntroductionIntroduction toto OSGiOSGi

MatthewMatthew PerrinsPerrins IBMIBM SoftwareSoftware GroupGroup Executive IT Specialist MartinMartin GaleGale Certified IT Specialist OOpenpen SServiceservices GGatewayateway IInitiativenitiative

AgendaAgenda

WhyWhy isis OSGiOSGi technologytechnology important?important? WhatWhat isis OSGiOSGi technology?technology? OSGiOSGi™™ ComponentComponent ProgrammingProgramming WhatWhat changeschanges areare comingcoming inin thethe future?future? WhoWho isis thethe OSGiOSGi Alliance?Alliance? GranularityGranularity

WhileWhile ObjectObject OrientedOriented languageslanguages likelike JavaJava helphelp TheyThey onlyonly helphelp atat thethe objectobject andand classclass levellevel ThereThere areare nono higherhigher levelslevels ofof mm odularity odularity WhatWhat isis Modularity?Modularity?

““TheThe propertyproperty ofof aa systemsystem thatthat hashas beenbeen decomposeddecomposed intointo aa setset ofof cohesivecohesive andand looselyloosely coupledcoupled modules.”modules.” engronline.ee.memphis.edu/networkprogram/Lectures/Lecture3/object_terms.htm ““(Desirable)(Desirable) propertyproperty ofof aa system,system, suchsuch thatthat individualindividual componentscomponents cancan bebe examined,examined, modifiedmodified andand maintainedmaintained independentlyindependently ofof thethe remainderremainder ofof thethe system.system. ObjectiveObjective isis thatthat changeschanges inin oneone partpart ofof aa systemsystem shouldshould notnot leadlead toto unexpectedunexpected behaviorbehavior inin otherother parts.”parts.” www.maths.bath.ac.uk/~jap/MATH0015/glossary.html OpenOpen SourceSource ProliferationProliferation

OtherOther openopen sourcesource projectsprojects consumeconsume eacheach otherother CommercialCommercial softwaresoftware consumesconsumes themthem IntegratingIntegrating manymany OSOS projectsprojects isis veryvery difficultdifficult DifferentDifferent dependenciesdependencies ofof differentdifferent projectsprojects ConflictsConflicts andand unexpectedunexpected failuresfailures ModularizationModularization inin JavaJava AppsApps VisibilityVisibility

Jar JavaJava PlatformPlatform ModularityModularity Package

• ClassesClasses encapsulateencapsulate datadata Class Class Class • PackagesPackages containcontain classesclasses Package

• Jars contain packages Jars contain packages Class Class Class VisibilityVisibility AccessAccess Package

• private,private, packagepackage private,private, protected,protected, Class Class publicpublic Class

PackagesPackages looklook hierarchical,hierarchical, butbut areare notnot

JarsJars havehave nono modularizationmodularization characteristicscharacteristics 66 ModularizationModularization inin JavaJava AppsApps ClasspathClasspath

Java VM party com m on resolver axis xerces

rt assetm aint catalina m ail ezm orph xm lapis BB egin egin jce hhfacility base jenks servlets xm lrpc HH ere ere jsse pos. datafile jakarta jetty xmlgraphics

plugin content entity log4j looks

sunjce_prov. m anufact. widget httpunit jdbm

dnsns product … m x4j bsf .. bi rom e batik bsh ClassClass m arketing workflow jpos18 fop velocity NotNot

workeffort ecom m erce jcl tom cat ws-com m ons FoundFound Exception ebay oagis barcode4j poi geronim o Exception

m inerva … freem arker lucene ..

m inilang googlebase serializer jdom json

accounting order nam ing com m ons xalan

guiapp ofbiz derby wsdl4j JARJAR Hell!Hell! OSGiOSGi isis thethe SolutionSolution AA mature,mature, functionalfunctional andand ready-to-useready-to-use technologytechnology thatthat cancan addressaddress thesethese issuesissues OSGiOSGi ModularityModularity HigherHigher levellevel encapsulationencapsulation WellWell specifiedspecified couplingcoupling Explicit,Explicit, versionedversioned dependenciesdependencies ReducedReduced complexitycomplexity ComponentComponent reusereuse SolvesSolves JARJAR Hell!Hell! UsingUsing OSGiOSGi SimpleSimple format:format: JARJAR filefile withwith manifestmanifest entriesentries EasyEasy toto deploydeploy RunsRuns onon mostmost VMsVMs includingincluding olderolder versionsversions DynamicDynamic LikeLike thethe realreal worldworld OSGiOSGi isis MatureMature

1010 yearsyears ofof experienceexperience andand improvementsimprovements 66 releasesreleases TheThe dede factofacto choicechoice forfor JavaJava componentscomponents andand modularitymodularity UsedUsed byby ,Eclipse, IBM,IBM, Oracle,Oracle, SpringSource,SpringSource, Sun,Sun, Redhat,Redhat, …… MultipleMultiple openopen sourcesource implementationsimplementations OSGiOSGi AdoptionAdoption

IncreasingIncreasing tractiontraction inin manymany verticals:verticals:

• EnterpriseEnterprise

• VehicleVehicle

• MobileMobile

• ““Smart”Smart” homehome

• More…More…

• IndustrialIndustrial automationautomation

• Remote/HomeRemote/Home HealthcareHealthcare

• MissionMission CriticalCritical EmbeddedEmbedded SolutionsSolutions HistoryHistory

R4R4 V4.1V4.1 R4R4 V4.0.1V4.0.1

R4R4 V4.0V4.0

R3R3

R2R2

R1R1 20002000 20012001 20032003 20052005 20062006 20072007 AgendaAgenda

WhyWhy isis OSGiOSGi technologytechnology important?important? WhatWhat isis OSGiOSGi technology?technology? OSGiOSGi ™™ ComponentComponent ProgrammingProgramming WhatWhat changeschanges areare comingcoming inin thethe future?future? WhoWho isis thethe OSGiOSGi Alliance?Alliance? OSGiOSGi technologytechnology TheThe DynamicDynamic ModuleModule SystemSystem forfor JavaJava™™ OSGiOSGi isis

AA modulemodule systemsystem BundlesBundles VisibilityVisibility DependenciesDependencies VersioningVersioning OSGiOSGi isis

DynamicDynamic Installing,Installing, starting,starting, stopping,stopping, updating,updating, uninstallinguninstalling bundles,bundles, allall dynamicallydynamically atat runtimeruntime OSGiOSGi isis

ServiceService orientedoriented ServicesServices cancan bebe registeredregistered andand consumedconsumed insideinside aa VMVM AllAll dynamicallydynamically atat runtimeruntime OSGiOSGi ServiceService PlatformPlatform

AA setset ofof specificationsspecifications CoreCore specificationsspecifications CompendiumCompendium specificationsspecifications CompendiumCompendium specificationsspecifications areare allall optionaloptional CoreCore SpecificationsSpecifications TheThe OSGiOSGi FrameworkFramework NetworkedNetworked ClassClass LoadersLoaders onon “Steroids”“Steroids”

SystemSystem LoaderLoader BB u u n n dle dle AA ExtensionExtension LoaderLoader BundleBundle GG BB u u n n dle dle BB

OSGiOSGi AppApp AA BB u u n n dle dle CC FrameworFramewor OSGiOSGi LoaderLoader kk BB u u n n dle dle FF BB u u n n dle dle DD CustomCustom LoaderLoader BB u u n n dle dle EE

2222 LifecycleLifecycle LayerLayer

ProvidesProvides APIsAPIs toto controlcontrol thethe lifelife cyclecycle ofof bundlesbundles Install/Update/Uninstall/Start/StopInstall/Update/Uninstall/Start/Stop LifecycleLifecycle eventevent notificationsnotifications APIAPI providesprovides informationinformation onon statestate ofof modulemodule layerlayer SupportsSupports dynamicdynamic managementmanagement ofof bundlesbundles inin runningrunning VMVM ServiceService LayerLayer

DefinesDefines aa publish/find/bindpublish/find/bind serviceservice modelmodel FullyFully dynamicdynamic IntraIntra VMVM LifecycleLifecycle eventevent notificationsnotifications Non-durableNon-durable serviceservice registryregistry AA serviceservice isis aa POJOPOJO publishedpublished underunder oneone oror moremore JavaJava interfaceinterface (or(or class)class) namesnames withwith additionaladditional key/valuekey/value pairpair metadatametadata AgendaAgenda

WhyWhy isis OSGiOSGi technologytechnology important?important? WhatWhat isis OSGiOSGi technology?technology? OSGiOSGi™™ ComponentComponent ProgrammingProgramming WhatWhat changeschanges areare comingcoming inin thethe futurefuture ?? WhoWho isis thethe OSGiOSGi Alliance?Alliance? OSGiOSGi™™ ComponentComponent ProgrammingProgramming ComplexityComplexity ofof SoftwareSoftware

• AA DVDDVD playerplayer cancan containcontain 11 MillionMillion lineslines ofof codecode

• Comparison:Comparison: SpaceSpace ShuttleShuttle ~~ 0.50.5 MillionMillion • AA BMWBMW carcar cancan containcontain upup toto 5050 networkednetworked computerizedcomputerized devicesdevices • EclipseEclipse containscontains 2.52.5 millionmillion lineslines ofof codecode • AnAn averageaverage programmerprogrammer writeswrites anan averageaverage ofof 1010 lineslines aa dayday ……

• HoustonHouston …… wewe havehave aa problemproblem ComplexityComplexity ofof SoftwareSoftware

Service Oriented Programming

Structured Programming Productivity Productivity Assem bly

ComplexityComplexity andand SizeSize LimitsLimits ObjectObject OrientedOriented TechnologyTechnology

• ObjectsObjects areare great,great, butbut oh,oh, thethe tangledtangled webswebs wewe weaveweave ……

• CouplingCoupling severelyseverely limitslimits reusabilityreusability

• UsingUsing aa genericgeneric object,object, cancan dragdrag inin aa largelarge numbernumber ofof otherother objectsobjects

• CreatesCreates overlyoverly largelarge systemssystems afterafter aa certaincertain complexitycomplexity isis reachedreached

• FlexibilityFlexibility mustmust bebe builtbuilt inin byby thethe programmerprogrammer

• Plug-inPlug-in architecturesarchitectures ServiceService OrientedOriented ArchitecturesArchitectures

• SeparateSeparate thethe contractcontract fromfrom thethe implementationimplementation

• AllowsAllows alternatealternate Service Contract implementationsimplementations provides Component

• DynamicallyDynamically discoverdiscover uses andand bindbind availableavailable implementationsimplementations • BasedBased onon contractcontract (interface)(interface) • ComponentsComponents areare reusablereusable • NotNot coupledcoupled toto implementationimplementation detailsdetails LayeringLayering

ServicesServices

LifeLife CycleCycle Security Security

ModuleModule Applications Applications

ExecutionExecution EnvironmentEnvironment ExecutionExecution EnvironmentEnvironment

• OSGiOSGi APIsAPIs onlyonly useuse aa subsetsubset ofof J2SEJ2SE andand J2MEJ2ME CDCCDC

• OSGiOSGi MinimumMinimum EEEE CLDC/ MIDP • MatchesMatches mostmost profilesprofiles

• ImplementationsImplementations cancan useuse moremore thanthan thethe OSGiOSGi OSGi MinimumMinimum EEEE Min.

• SecuritySecurity isis notnot mandatorymandatory

• CLDCCLDC isis possiblepossible ifif classclass J2SE loadersloaders areare addedadded inin aa CDC/FP devicedevice specificspecific wayway ModuleModule LayerLayer • PackagingPackaging ofof applicationsapplications andand librarieslibraries inin BundlesBundles

• RawRaw JavaJava hashas significantsignificant deploymentdeployment issuesissues bundle

• ClassClass LoadingLoading modularizationmodularization bundle

• RawRaw JavaJava providesprovides thethe ClassClass PathPath asas anan orderedordered searchsearch bundle bundle list,list, whichwhich makesmakes itit hardhard toto bundle controlcontrol multiplemultiple applicationsapplications

• ProtectionProtection

bundle • RawRaw JavaJava cancan notnot protectprotect bundle certaincertain packagespackages andand classesclasses

• VersioningVersioning

• RawRaw JavaJava cancan notnot handlehandle multiplemultiple versionsversions ofof thethe samesame packagepackage LifeLife CycleCycle LayerLayer • SystemSystem BundleBundle representsrepresents thethe OSGiOSGi FrameworkFramework

• ProvidesProvides anan APIAPI forfor managingmanaging bundlesbundles System bundle • InstallInstall bundle M

• ResolveResolve Bundle • StartStart X-v2X

• StopStop

• Bundle RefreshRefresh Bundle B A • UpdateUpdate

• UninstallUninstall

• BasedBased onon thethe modulemodule layerlayer LifeLife CycleCycle LayerLayer

• BundleBundle isis startedstarted byby thethe BundleBundle ActivatorActivator classclass

• HeaderHeader inin ManifestManifest refersrefers toto thisthis classclass

INSTALLED STARTING • InterfaceInterface hashas 22 methodsmethods

start • Start:Start: InitializeInitialize andand returnreturn immediate immediate RESOLVED ACTIVE

• Stop:Stop: CleanupCleanup stop

• TheThe ActivatorActivator getsgets aa BundleBundle UNINSTALLED STOPPING ContextContext thatthat providesprovides accessaccess toto thethe FrameworkFramework functionsfunctions

• FrameworkFramework providesprovides StartStart LevelLevel serviceservice toto controlcontrol thethe start/stopstart/stop ofof groupsgroups ofof applicationsapplications ServiceService LayerLayer • ProvidesProvides anan in-VMin-VM serviceservice modelmodel

• DiscoverDiscover (and(and getget notifiednotified about)about) servicesservices basedbased onon theirtheir interfaceinterface oror propertiesproperties

• BindBind toto oneone oror moremore servicesservices byby

• programprogram control,control,

• defaultdefault rules,rules, oror

• deploymentdeployment configurationconfiguration

• SOASOA ConfusionConfusion

• WebWeb servicesservices bindbind andand discoverdiscover overover thethe netnet

• TheThe OSGiOSGi ServiceService PlatformPlatform bindsbinds andand discoversdiscovers insideinside aa JavaJava VMVM

• TheThe OSGiOSGi AllianceAlliance providesprovides manymany standardizedstandardized servicesservices BenefitsBenefits ofof UsingUsing thethe OSGiOSGi ServiceService PlatformPlatform • ComponentsComponents areare smallersmaller

• EasierEasier toto makemake

• ComponentsComponents areare notnot coupledcoupled toto otherother componentscomponents

• GivesGives reusabilityreusability

• ExcellentExcellent modelmodel forfor thethe myriadmyriad ofof customizationscustomizations andand variationvariation thatthat areare requiredrequired ofof today’stoday’s devicesdevices

• CollaborativeCollaborative modelmodel

• AllowsAllows reusereuse ofof otherother componentscomponents forfor mostmost problemsproblems Eclipse/EquinoxEclipse/Equinox WhatWhat isis EquinoxEquinox ??

• AnAn openopen sourcesource communitycommunity focusedfocused onon OSGiOSGi TechnologyTechnology

• DevelopDevelop OSGiOSGi specificationspecification implementationsimplementations

• PrototypePrototype ideasideas relatedrelated toto OSGiOSGi

• AnAn OSGiOSGi FrameworkFramework implementationimplementation

• CoreCore ofof thethe EclipseEclipse runtimeruntime

• ProvidesProvides thethe basebase forfor EclipseEclipse plug-inplug-in collaborationcollaboration

• FullyFully compatiblecompatible withwith thethe OSGiOSGi R4R4 specificationspecification

• NewNew forfor EclipseEclipse 3.23.2 –– OtherOther specificationspecification implementationsimplementations

• DeviceDevice Manager,Manager, DeclarativeDeclarative Services,Services, EventEvent Admin,Admin, HTTPHTTP Service,Service, LogLog Service,Service, MetatypeMetatype Service,Service, PreferencesPreferences Service,Service, UserUser Admin,Admin, WireWire AdminAdmin –– MoreMore onon thethe way!!way!! TheThe EquinoxEquinox TargetTarget EnvironmentEnvironment

• EclipseEclipse makesmakes itit easyeasy toto developdevelop forfor OSGiOSGi ServiceService PlatformsPlatforms BundleBundle AA {}{} • AA targettarget platformplatform

Install •ContainsContains aa setset ofof bundlesbundles

Bundle c •DefinesDefines runtimeruntime parametersparameters Bundle B {} {}

• Bundled ToTo DefineDefine thethe TargetTarget Platform,Platform, goto:goto: {} Bundle F {} • PreferencesPreferences ->Plug-in->Plug-in BundleG Bundle E {} {} DevelopmentDevelopment ->Target->Target PlatformPlatform TargetTarget OSGiOSGi FrameworkFramework •SelectSelect thethe targettarget projectproject inin youryour (Equinox)(Equinox) workspaceworkspace asas locationlocation FundamentalFundamental OSGiOSGi conceptsconcepts FrameworkFramework EntitiesEntities

OSGiOSGi FrameworkFramework

BundleBundle AA {}{} BundleBundle BB {}{}

BundleBundle CC == service,service, javajava interfaceinterface {}{} BundlesBundles

• AA bundlebundle isis thethe deliverabledeliverable applicationapplication

• LikeLike aa WindowsWindows EXEEXE filefile

• ContentContent isis aa JARJAR filefile

• AA bundlebundle registersregisters zerozero oror moremore servicesservices

• AA serviceservice isis specifiedspecified inin aa JavaJava interfaceinterface andand maymay bebe implementedimplemented byby multiplemultiple bundlesbundles

• ServicesServices areare boundbound toto thethe bundlebundle life-cyclelife-cycle

• SearchesSearches cancan bebe usedused toto findfind servicesservices registeredregistered byby otherother bundlesbundles

• QueryQuery languagelanguage WhatWhat isis inin aa Bundle?Bundle?

• A Bundle contains (normally in a JAR file):

• Manifest

• Code

• Resources

• The Framework: BundleBundle AA

• Reads the bundle’s manifest {}{}

• Installs the code and resources

• Resolves dependencies

• During Runtime:

• Calls the Bundle Activator to start the bundle

• Manages classpath

• Handles the service dependencies

• Calls the Bundle Activator to stop the bundle CreateCreate thethe HelloHello WorldWorld bundlebundle

Step 1.

Create new plug-in project

Step 2

Project name: helloworld Step 3 Step 4 an OSGi framework: standard Generate an activator Use the Hello OSGi Bundle

template RealReal code!code! HelloHello WorldWorld (and(and Goodbye)Goodbye)

• TheThe wizardwizard hashas HelloWorld.java package helloworld generatedgenerated thethe codecode public class HelloWorld on the left on the left implements BundleActivator { • ThisThis classclass implementsimplements public void start( thethe BundleActivatorBundleActivator BundleContext context) soso thatthat thethe throws Exception{ FrameworkFramework cancan System.out.println( "Hello world!!"); start/stopstart/stop thethe classclass }

• TheThe activatoractivator isis public void stop( referencedreferenced inin thethe BundleContext context) throws Exception { manifestmanifest System.out.println(

"Goodbye world!!"); }

} RealReal code!code! HelloHello WorldWorld (and(and Goodbye)Goodbye) • TheThe ManifestManifest (in(in META-META- META-INF/MANIFEST.MF INF/MANIFEST.MF)INF/MANIFEST.MF) isis alsoalso Manifest-Version: 1.0 generatedgenerated byby thethe wizardwizard Bundle-ManifestVersion: 2 • EclipseEclipse providesprovides Bundle-Name: Helloworld Plug-in convenient editors for the convenient editors for the Bundle-SymbolicName: helloworld manifestmanifest Bundle-Version: 1.0.0

• ForFor thethe source:source: clickclick onon Bundle-Localization: plugin MANIEST.MFMANIEST.MF Bundle-Activator: helloworld.Activator

• Notice:Notice: Import-Package:

org.osgi.framework;version="1.3.0" •Bundle-ActivatorBundle-Activator (used(used toto notifynotify thethe bundlebundle ofof lifecyclelifecycle changes)changes)

•Import-PackageImport-Package (dependencies)(dependencies) EclipseEclipse LaunchLaunch ConfigurationConfiguration

• TheThe LaunchLaunch ConfigurationConfiguration isis preparedprepared forfor youyou

• RunRun ->-> RunRun …… ->-> EclipseTutorialEclipseTutorial

• DeselectDeselect “Target“Target Platform”Platform” checkboxcheckbox

• ThisThis removesremoves allall possiblepossible bundlesbundles fromfrom thethe launchlaunch configurationconfiguration

• SelectSelect “Add“Add RequiredRequired Plug-ins”Plug-ins”

• ThisThis calculatescalculates fromfrom thethe dependencydependency information,information, whichwhich bundlesbundles areare requiredrequired toto runrun ourour helloworldhelloworld exampleexample

• PressPress RunRun

• TheThe FrameworkFramework isis aa consoleconsole applicationapplication EquinoxEquinox LaunchLaunch ConfigurationConfiguration RunRun thethe HelloHello WorldWorld bundlebundle

• TheThe FrameworkFramework nownow runsruns thethe helloworldhelloworld exampleexample

•SeeSee thethe printedprinted texttext

• It also runs a Framework console

•EquinoxEquinox specificspecific

• Type “ss” (show status)

•LookLook atat thethe activeactive bundlesbundles

•NoticeNotice thethe numbernumber forfor thethe helloworldhelloworld bundle.bundle. ThisThis isis thethe bundlebundle id.id.

• Type “stop ” || bundle number CreatingCreating deployabledeployable bundlesbundles –– howhow itit worksworks • TheThe build.propertiesbuild.properties filefile specifiesspecifies thethe contentcontent ofof thethe bundlebundle jarjar

•Specifies the source and output folders of the different libraries build.properties source.. = src/ •source.. – The source directory of the project. output.. = bin/ Used for compilation and resources. bin.includes = META-INF/,\ . •output.. – The output directory where class files and resources are copied to

•bin.includes – What is included in the JAR from the project directory

• ExportExport thethe contentcontent ofof aa projectproject intointo aa bundlebundle jarjar

•Bundle jars can be installed across multiple OSGi Framework implementations

•The Deployable plug-ins and fragments wizard can be used to generate a bundle jar from a project.

•File -> Export -> Deployable plug-ins and fragments ComponentComponent interactioninteraction andand collaborationcollaboration CollaborativeCollaborative modelmodel • OSGiOSGi isis moremore thanthan anan Applet,Applet, MIDlet,MIDlet, XletXlet runnerrunner

• BundlesBundles cancan collaboratecollaborate through:through:

• serviceservice objectsobjects

• packagepackage sharingsharing

• AA dynamicdynamic registryregistry allowsallows aa bundlebundle toto findfind andand tracktrack serviceservice objectsobjects

• FrameworkFramework fullyfully managesmanages thisthis collaborationcollaboration

• Dependencies,Dependencies, securitysecurity CollaborativeCollaborative modelmodel

OSGi Framework

Service registry B undle B undle packages packages

JAVA

Operating System

H ardware CollaborativeCollaborative modelmodel

Java Application M anager

No management bundles Service M idlet, registry M idlet, No collaboration , Xlet, or or Applet packages Applet packages No package management (versions!)

JAVA

Operating System No native code

H ardware ClasspathClasspath issuesissues • JavaJava applicationsapplications consistsconsists ofof classesclasses placedplaced inin packagespackages

• JavaJava searchessearches forfor aa packagepackage oror classclass inin differentdifferent jarjar filesfiles andand directoriesdirectories

• These are usually specified in the CLASSPATH environment variable

q q-1.0 • AnAn OSGiOSGi FrameworkFramework isis aa networknetwork p ofof classclass loaders.loaders. r p • Parameterized by the Manifest p headers q q-2.0

• AnyAny dependenciesdependencies betweenbetween bundlesbundles areare resolvedresolved byby thethe FrameworkFramework

• ItIt isis possiblepossible toto fetchfetch bundlesbundles onon Bundle Wire demanddemand Exported package Constraint Exported package • ComplicatedComplicated –– ButBut anan OSGiOSGi FrameworkFramework makesmakes itit painlesspainless toto useuse OSGiOSGi dependencydependency resolutionresolution

FrameworkFramework org.osgi.frameworkorg.osgi.framework org.osgi.service.httporg.osgi.service.http BundleBundle AA ExportExport org.osgi.service.logorg.osgi.service.log AA resolvedresolved com.ibm.service.logcom.ibm.service.log com.ibm.j9com.ibm.j9 ImportImport org.osgi.service.httporg.osgi.service.http javax.servlet.httpjavax.servlet.http BundleBundle BB ExportExport ericsson.osgiericsson.osgi BB resolvedresolved javax.servletjavax.servlet javax.servlet.httpjavax.servlet.http org.osgi.service.logorg.osgi.service.log ImportImport org.osgi.service.httporg.osgi.service.http org.osgi.service.logorg.osgi.service.log PackagePackage oror BundleBundle Dependencies?Dependencies?

• TheThe OSGiOSGi SpecificationsSpecifications supportssupports bothboth Require-BundleRequire-Bundle andand Import-Import- PackagePackage

• Require-BundleRequire-Bundle createscreates aa dependencydependency onon aa completecomplete bundlebundle

•Simple to use p Import-Package q •Imports packages that are not used r r • Import-PackageImport-Package createscreates aa s dependencydependency onon justjust aa packagepackage Require-Bundle •Creates less brittle bundles because of substitutability r

•More cumbersome to use (Tools!)

• InIn almostalmost allall cases,cases, Import-PackageImport-Package isis recommendedrecommended becausebecause itit easeseases deploymentdeployment andand versionversion migrationmigration

• TheThe specificationsspecifications detaildetail aa numbernumber ofof additionaladditional problemsproblems withwith Require-BundleRequire-Bundle ServiceService SpecificsSpecifics

• AA serviceservice isis anan objectobject registeredregistered discover withwith thethe FrameworkFramework byby aa bundlebundle toto bebe usedused byby otherother bundlesbundles bind register

• TheThe semanticssemantics andand syntaxsyntax ofof aa serviceservice areare specifiedspecified inin aa Java interfaceJava interface sseerrvviiccee

• AA bundlebundle cancan registerregister aa service.service. package org.osgi.service.log; import org.osgi.framework.ServiceReference; public interface LogService { • AA bundlebundle cancan useuse aa serviceservice (bind(bind public static final intLOG_ERROR= 1; to)to) public static final intLOG_WARNING= 2; public static final intLOG_INFO= 3; • 1..1 public static final intLOG_DEBUG= 4; public void log(int level, • 0..1 String message); public void log(int level, String message, Throwable exception); • 0..n public void log(ServiceReference sr, int level, String message); • AA serviceservice cancan bebe discovereddiscovered public void log(ServiceReference sr, dynamicallydynamically int level, String message, Throwable exception); } • ServicesServices cancan gogo awayaway atat anyany time!time! ManipulatingManipulating ServicesServices

• TheThe BundleContextBundleContext providesprovides thethe methodsmethods toto manipulatemanipulate thethe serviceservice registryregistry ServiceRegistration registerService( • ServicesServices registrationsregistrations areare String clss, Object srvc, handledhandled byby ServiceRegistrationServiceRegistration Dictionary prprts) objectsobjects ServiceReference[] getServiceReferences( • getServiceReferences( TheyThey cancan bebe usedused String clss, toto unregisterunregister aa String fltr) Object getService( serviceservice oror modifymodify ServiceReference reference)

itsits propertiesproperties boolean ungetService( ServiceReference rfrnc); • ServiceService ReferencesReferences givegive accessaccess toto thethe serviceservice asas wellwell asas toto thethe service’sservice’s propertiesproperties

• AccessAccess toto serviceservice objectsobjects isis throughthrough thethe getServicegetService method.method. TheseThese servicesservices shouldshould bebe returnedreturned withwith thethe ungetServiceungetService methodmethod ServiceService TrackingTracking TheThe CaseCase forfor thethe ServiceTrackerServiceTracker

• FindingFinding servicesservices forfor eacheach messagemessage isis kindkind ofof expensive.expensive.

• TheThe ServiceTrackerServiceTracker inin org.osgi.util.trackerorg.osgi.util.tracker packagepackage isis intendedintended toto simplifysimplify thisthis tasktask

• AA serviceservice trackertracker maintainsmaintains aa listlist ofof servicesservices basedbased on:on: • AA filterfilter • AA specificspecific classclass

• ItIt reportsreports anyany existingexisting oror newnew servicesservices asas wellwell asas anyany servicesservices thatthat becomebecome unregisteredunregistered

• ObjectObject addingServiceaddingService • voidvoid modifiedServicemodifiedService • voidvoid removedServiceremovedService

• TheThe serviceservice trackertracker isis usedused toto tracktrack channelschannels andand storestore themthem inin aa MapMap ServiceTracker:ServiceTracker: createcreate

FrameworkFramework BundleBundle AA

BundleBundle BB

BundleBundle CC ServiceTracker:ServiceTracker: openopen

FrameworkFramework BundleBundle addServiceListener AA

BundleBundle BB

BundleBundle CC

Object addingService(ServiceReference r){…} ServiceTracker:ServiceTracker: addingadding

FrameworkFramework BundleBundle addServiceListener AA

BundleBundle BB

BundleBundle CC

Object addingService(ServiceReference r){…} ServiceTracker:ServiceTracker: removingremoving

FrameworkFramework BundleBundle addServiceListener AA

BundleBundle BB

BundleBundle CC void removedService(ServiceReference r,Objecto){…} ServiceTracker:ServiceTracker: modifiedmodified

FrameworkFramework BundleBundle addServiceListener AA

BundleBundle BB

BundleBundle CC void modifiedService(ServiceReference r, Object o){…} ConclusionConclusion

• TheThe OSGiOSGi R4R4 SpecificationsSpecifications consistsconsists ofof considerableconsiderable moremore detailsdetails thanthan elucidatedelucidated inin thisthis tutorialtutorial

• ThereThere areare manymany independentindependent OSGiOSGi implementationsimplementations onon thethe market,market, bothboth commercialcommercial andand openopen sourcesource

• Apache Felix, Atinav, Eclipse Equinox, Espial, IBM SMF, Knopflerfish/Ubiserv of Gatespace, ProSyst, …

• TheThe OSGiOSGi specificationspecification areare todaytoday runningrunning onon mobilemobile phones,phones, PDAs,PDAs, embeddedembedded computers,computers, desktops,desktops, mainframesmainframes andand insideinside mostmost EnterpriseEnterprise ServersServers

• BothBoth inin managedmanaged andand unmanagedunmanaged configurationsconfigurations

• TheThe OSGiOSGi specificationsspecifications solvesolve realreal worldworld problemsproblems

• TheThe OSGiOSGi AllianceAlliance isis workingworking onon makingmaking thethe OSGiOSGi specificationsspecifications thethe standardstandard forfor portableportable applications.applications. JoinJoin us!us! AgendaAgenda

WhyWhy isis OSGiOSGi technologytechnology important?important? WhatWhat isis OSGiOSGi technology?technology? OSGiOSGi ™™ ComponentComponent ProgrammingProgramming WhatWhat changeschanges areare comingcoming inin thethe futurefuture ?? WhoWho isis thethe OSGiOSGi Alliance?Alliance? ReleaseRelease 44 VersionVersion 4.24.2 EnterpriseEnterprise FocusFocus HighlightsHighlights

RFCRFC 119119 DistributedDistributed OSGiOSGi RFCRFC 120120 PermissionPermission ManagementManagement EnhancementEnhancement RFCRFC 121121 BundleBundle TrackerTracker RFCRFC 124124 BlueprintBlueprint (Spring(Spring DynamicDynamic Modules)Modules) RFCRFC 126126 ServiceService HooksHooks RFCRFC 132132 FrameworkFramework launchinglaunching RFCRFC 138138 MultipleMultiple FrameworksFrameworks inin aa VMVM RFCRFC 119119 DistributedDistributed OSGiOSGi DiscoveringDiscovering andand usingusing servicesservices inin remoteremote OSGiOSGi frameworksframeworks ExposeExpose servicesservices forfor remoteremote useuse RFCRFC 120120 PermissionPermission ManagementManagement EnhancementEnhancement AllowAllow permissionpermission managementmanagement toto bebe simplifiedsimplified byby declaringdeclaring denieddenied permissionspermissions ALLOW/DENYALLOW/DENY modelmodel likelike ApacheApache httpdhttpd RFCRFC 121121 BundleBundle TrackerTracker

TrackTrack bundlesbundles basedbased uponupon bundlebundle statestate LikeLike ServiceTrackerServiceTracker butbut forfor bundlesbundles ForFor ExtenderExtender PatternPattern RFCRFC 124124 BlueprintBlueprint

AA richerricher DependencyDependency Injection(DI)Injection(DI) runtimeruntime forfor OSGiOSGi fromfrom SpringSpring DynamicDynamic ModulesModules ComplementsComplements DeclarativeDeclarative ServicesServices RFCRFC 126126 ServiceService HooksHooks

AA newnew mechanismmechanism toto observeobserve andand reactreact toto serviceservice operationsoperations Publish,Publish, Find,Find, ListenListen CanCan bebe usedused toto “hide”“hide” servicesservices fromfrom bundlesbundles UsedUsed byby RFCRFC 119119 RFCRFC 132132 FrameworkFramework LaunchingLaunching

Create,Create, configure,configure, launch,launch, managemanage andand shutdownshutdown anan OSGiOSGi frameworkframework instanceinstance RFCRFC 138138 MultipleMultiple FrameworksFrameworks inin aa VMVM AllowAllow multiplemultiple frameworksframeworks toto functionfunction inin aa singlesingle VMVM Peers(heterogeneouPeers(heterogeneou s),s), parent/childparent/child (homogeneous)(homogeneous) ScopingScoping forfor stackstack productsproducts andand applicationsapplications BeyondBeyond 4.24.2

FrameworkFramework 2.02.0 ModernizeModernize APIAPI JSRJSR 294294 supportsupport SupportSupport 1.x1.x bundlesbundles AgendaAgenda

WhyWhy isis OSGiOSGi technologytechnology important?important? WhatWhat isis OSGiOSGi technology?technology? TechnicalTechnical DeepDeep DiveDive WhatWhat changeschanges areare comingcoming inin thethe future?future? WhoWho isis thethe OSGiOSGi Alliance?Alliance? OSGiOSGi AllianceAlliance MembersMembers ThankThank you!you!