osgi service platform core specificationsmarthome.cs.iastate.edu/documents/manuals and...

276
OSGi Service Platform Core Specification The OSGi Alliance Release 4 August 2005

Upload: vudat

Post on 15-Mar-2018

231 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

OSGi Service PlatformCore SpecificationThe OSGi Alliance

Release 4August 2005

Page 2: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Copyright © 2005, 2000 OSGi AllianceAll Rights Reserved

OSGi Specification License, Version 1.0

The OSGi Alliance (“OSGi Alliance”) hereby grants you a fully-paid, non-exclusive, non-transferable, worldwide, limited license (without the right to sublicense), under the OSGi Alliance's applicable intellectual property rights to view, download, and reproduce the OSGi Specification (“Specification”) which follows this License Agreement (“Agreement”). You are not authorized to create any derivative work of the Specification. The OSGi Alliance also grants you a perpetual, non-exclusive, worldwide, fully paid-up, royalty free, limited license (without the right to sublicense) under any applicable copyrights, to create and/or distribute an implementation of the Specification that: (i) fully implements the Specification including all its required interfaces and functionality; (ii) does not modify, subset, superset or otherwise extend the OSGi Name Space, or include any public or protected packages, classes, Java interfaces, fields or methods within the OSGi Name Space other than those required and authorized by the Specification. An implementation that does not satisfy limitations (i)-(ii) is not considered an implementation of the Specification, does not receive the benefits of this license, and must not be described as an implementation of the Specification. An implementation of the Specification must not claim to be a compliant implementation of the Specification unless it passes the OSGi Alliance Compliance Tests for the Specification in accordance with OSGi Alliance processes. “OSGi Name Space” shall mean the public class or interface declarations whose names begin with “org.osgi” or any recognized successors or replacements thereof.

THE SPECIFICATION IS PROVIDED “AS IS,” AND THE OSGi ALLIANCE, ITS MEMBERS AND ANY OTHER AUTHORS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OF THE SPECIFICATION ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. THE OSGi ALLIANCE, ITS MEMBERS AND ANY OTHER AUTHORS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SPECIFICATION OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.

The name and trademarks of the OSGi Alliance or any other Authors may NOT be used in any manner, including advertising or publicity pertaining to the Specification or its contents without specific, written prior permission. Title to copyright in the Specification will at all times remain with the Authors.

No other rights are granted by implication, estoppel or otherwise.

TrademarksOSGi™ is a trademark, registered trademark, or service mark of the OSGi Alliance in the US and other countries. Java is a trademark, registered trade-mark, or service mark of Sun Microsystems, Inc. in the US and other coun-tries. All other trademarks, registered trademarks, or service marks used in this document are the property of their respective owners and are hereby recognized.

FeedbackThis specification can be downloaded from the OSGi web site:

http://www.osgi.org

Comments about this specification can be mailed to:

[email protected]

i-268 OSGi Service Platform Release 4

Page 3: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

OSGi Member CompaniesAlpine Electronics Europe Gmbh, Aplix Corporation, Belgacom, BMW Group, Cablevision Systems, Computer Associates, Deutsche Telekom AG, Echelon Corporation, Electricité de France (EDF), Ericsson Mobile Platforms AB, Esmertec, Espial Group, Inc., ETRI Electronics and Telecommunications Research Institute, France Telecom, Gatespace Telematics AB, Gemplus, Harman/Becker Automotive Systems GmbH, Hitachi, Ltd., IBM Corpora-tion, Industrial Technology Research Institute, Insignia Solutions, Intel Cor-poration, KDDI R&D Laboratories, Inc., KT Corporation, Mitsubishi Electric Corporation, Motorola, Inc., NEC Corporation, Nokia Corporation, NTT, Oracle Corporation, Panasonic Technologies, Inc., Philips Consumer Elec-tronics, ProSyst Software GmbH, Robert Bosch Gmbh, Samsung Electronics Co., Ltd., SavaJe Technologies, Inc., Sharp Corporation, Siemens AG, Sun Microsystems, Inc., Telcordia Technologies, Inc., Telefonica I+D, TeliaSon-era, Toshiba Corporation, Vodafone Group Services Limited

OSGi Service Platform Release 4 ii-268

Page 4: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

OSGi Board of Directors and Officers

Director,VP Americas

Dan Bandera Program Director, WebSphere Standards, IBM Corporation

Director,President

John R. Barr Director, Standards Realization, Corporate Offices, Motorola, Inc.

Director Hans-Werner Bitzer Head of Section Smart Home Solutions,Deutsche Telekom AG

Director Jon Bostrom Chief Java Architect,Nokia Corporation

CTO, CPEG chair,OSGi Fellow

BJ Hargrave Senior Software Engineer,IBM Corporation

Executive Director Deepak Kamlani CEO, Founder,Global Inventures, Inc.

Director Ryutaro Kawamura Senior Manager,NTT

Director Chung-Kon Ko Vice President,Samsung Electronics Co., Ltd.

Technical Director, Editor,OSGi Fellow

Peter Kriens Managing Director,aQute

Director Andre Kruetzfeldt Principal Architect,Sun Microsystems, Inc.

Director,Treasurer

Jeff Lund Vice President, Business Development & Corporate Marketing,Echelon Corporation

Director, VP Europe, Middle East and Africa

Daniel Meirsman Principal Technology Strategist,Philips Consumer Electronics

Director Hans-Ulrich Michel Project Manager Information, Communica-tion and Telematics,BMW

Director,Secretary

Stan Moyer Executive Director, Strategic Research Pro-gram,Telcordia Technologies, Inc.

Director Olivier Pavé Software Architect, Siemens AG

Director,VP Marketing

Susan Schwarze Marketing Director,ProSyst Software GmbH

VP Asia Pacific Jae Gun (JG) Wee Korea Rep. Director of Echelon APJ,Echelon Corporation

iii-268 OSGi Service Platform Release 4

Page 5: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Table Of Contents

1 Introduction 31.1 OSGi Framework Overview ..................................................................................... 3

1.2 What Is New ............................................................................................................ 4

1.3 Reader Level ............................................................................................................ 5

1.4 Conventions and Terms .......................................................................................... 6

1.5 Version Information .............................................................................................. 10

1.6 References ............................................................................................................. 11

2 Security Layer 132.1 Introduction ........................................................................................................... 13

2.2 Security Overview ................................................................................................. 13

2.3 Digitally Signed JAR Files ....................................................................................... 14

2.4 References ............................................................................................................. 24

3 Module Layer 273.1 Introduction ........................................................................................................... 27

3.2 Bundles .................................................................................................................. 27

3.3 Execution Environment ......................................................................................... 33

3.4 Class Loading Architecture ................................................................................... 34

3.5 Resolving Metadata ............................................................................................... 37

3.6 Constraint Solving ................................................................................................. 41

3.7 Resolving Process .................................................................................................. 50

3.8 Runtime Class Loading .......................................................................................... 51

3.9 Loading Native Code Libraries .............................................................................. 59

3.10 Localization ........................................................................................................... 64

3.11 Bundle Validity ...................................................................................................... 65

3.12 Optional ................................................................................................................ 66

3.13 Requiring Bundles .................................................................................................. 66

3.14 Fragment Bundles .................................................................................................. 69

3.15 Extension Bundles ................................................................................................. 72

3.16 Security ................................................................................................................. 74

3.17 References ............................................................................................................. 77

4 Life Cycle Layer 794.1 Introduction ........................................................................................................... 79

4.2 Bundles .................................................................................................................. 80

4.3 The Bundle Object ................................................................................................. 81

4.4 The Bundle Context ............................................................................................... 89

4.5 The System Bundle ................................................................................................ 92

OSGi Service Platform Release 4 iv-268

Page 6: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

4.6 Events .................................................................................................................... 93

4.7 Framework Startup and Shutdown .......................................................................96

4.8 Security .................................................................................................................. 97

4.9 References ........................................................................................................... 100

5 Service Layer 1035.1 Introduction ......................................................................................................... 103

5.2 Services ................................................................................................................ 104

5.3 Service Events ..................................................................................................... 111

5.4 Stale References .................................................................................................. 112

5.5 Filters ................................................................................................................... 112

5.6 Service Factory .................................................................................................... 113

5.7 Releasing Services ............................................................................................... 114

5.8 Unregistering Services ........................................................................................ 115

5.9 Multiple Version Export Considerations ............................................................. 115

5.10 Security ................................................................................................................ 116

6 Framework API 1196.1 org.osgi.framework ............................................................................................. 119

7 Package Admin Service Specification 1857.1 Introduction ......................................................................................................... 185

7.2 Package Admin .................................................................................................... 186

7.3 Security ................................................................................................................ 188

7.4 Changes ............................................................................................................... 188

7.5 org.osgi.service.packageadmin ........................................................................... 188

8 Start Level Service Specification 1958.1 Introduction ......................................................................................................... 195

8.2 Start Level Service ............................................................................................... 196

8.3 Compatibility Mode ............................................................................................ 200

8.4 Example Applications ......................................................................................... 200

8.5 Security ................................................................................................................ 201

8.6 org.osgi.service.startlevel ................................................................................... 201

9 Conditional Permission Admin Specification 2079.1 Introduction .........................................................................................................207

9.2 Permission Management Model .......................................................................... 210

9.3 Effective Permissions ........................................................................................... 216

9.4 Conditional Permissions ...................................................................................... 217

9.5 The Permission Check ......................................................................................... 219

9.6 Permission Management ..................................................................................... 228

9.7 Conditions ...........................................................................................................230

v-268 OSGi Service Platform Release 4

Page 7: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

9.8 Standard Conditions ........................................................................................... 234

9.9 Bundle Permission Resource ............................................................................... 235

9.10 Relation to Permission Admin ............................................................................. 236

9.11 Security ............................................................................................................... 236

9.12 org.osgi.service.condpermadmin ........................................................................ 237

9.13 References ........................................................................................................... 243

10 Permission Admin Service Specification 24510.1 Introduction ......................................................................................................... 245

10.2 Permission Admin service ................................................................................... 246

10.3 Security ............................................................................................................... 248

10.4 Changes ............................................................................................................... 248

10.5 org.osgi.service.permissionadmin ....................................................................... 248

11 URL Handlers Service Specification 25311.1 Introduction ......................................................................................................... 253

11.2 Factories in java.net ............................................................................................ 256

11.3 Framework Procedures ........................................................................................ 257

11.4 Providing a New Scheme ..................................................................................... 261

11.5 Providing a Content Handler ............................................................................... 262

11.6 Security Considerations ...................................................................................... 262

11.7 org.osgi.service.url .............................................................................................. 263

11.8 References ........................................................................................................... 266

OSGi Service Platform Release 4 vi-268

Page 8: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

vii-268 OSGi Service Platform Release 4

Page 9: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

ForewordThe OSGi Alliance is pleased to present the OSGi Service Platform Core Specification, Release 4. This document culminates more than two years of cooperative effort by the members of the OSGi Alliance, building on our experience of using the previous releases. With the support of the OSGi Alli-ance member companies, an army of volunteers have contributed their time and expertise to make this release and the success of the OSGi Alliance pos-sible. We are honored to have such high caliber people involved.

The OSGi Alliance released the first OSGi Service Platform Specification in May 2000, and Release 2 came in October 2001. We announced the OSGi Compliance Program in May 2002. Release 3 was published in April 2003. Along the way we changed our name to the OSGi Alliance.

Our original intention was to create a specification to allow services to be remotely deployed onto home network gateways - devices like set-top boxes and DSL modems. The first release of the specification targeted this market. That specification was extremely successful with many companies, creating compatible frameworks. Building upon the experiences gained from the first release, our second release introduced methods for improving security, remotely managing service platforms, and making it easier to implement complex applications. OSGi Service Platform, Release 2 became more of a horizontal platform. Release 3 was the first release to focus on a specific application: automotive information and entertainment platforms. This was done with the cooperation of the Automotive Multimedia Interface Collaboration (AMI-C) and the ERTICO 3GT project. Several automotive manufacturers have adopted Release 3 as the core middleware platform for their high-end information and entertainment systems. Release 4 is a response to several developments: specific requirements highlighted by our member companies involved with the mobile devices business; additional framework improvements to support increasingly complex systems; and continued improvements to support additional automotive requirements. This release was done with the cooperation of the ERTICO GST project, the JSR-232 expert group in the Java Community Process, the Eclipse Founda-tion, and the Open Mobile Alliance Device Management group.

The OSGi Alliance exists to create open specifications for the network deliv-ery of managed services to devices in the home, car, mobile, and other envi-ronments. OSGi principles are applicable in any environment where managed lifecycles, long uptimes, and highly resilient, remotely managed platforms are required. The automotive industry added the requirement to keep the applications using that platform current with the latest consumer electronics systems, which may have multiple product life cycles during the typical ownership period of an automobile. The mobile device industry drove the development of a programming environment supporting the increasing capabilities of the device formerly known as a cellular phone. Release 4 has benefited from broad industry cooperation. Now companies can take advantage of the years of expertise represented in the specification to create compelling products meeting today's needs for network-connected devices.

OSGi Service Platform Release 4 1-268

Page 10: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

We've been very careful to not alienate our early adopters, so you will find a minimum of incompatibilities between this specification and earlier ones. As we continue expanding the specification, developers can rest assured we'll give the same attention to backwards compatibility in the future. This priority will come to be even more important as other standards organiza-tions adopt the OSGi Service Platform specification. Again, we're privileged to have world class people working on the OSGi specifications. This docu-ment is the product of the OSGi Expert Groups, and those people deserve a special pat on the back for their efforts. Finally, we really do mean the “Open” in our name: so if the OSGi mission is important to you then please come and join us - together we'll make future releases even better...

So, here it is, the OSGi Service Platform Core Specification, Release 4. Enjoy…

John BarrPresident, OSGi Alliance

2-268 OSGi Service Platform Release 4

Page 11: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction OSGi Framework Overview

1 IntroductionThe OSGi™ Alliance was founded in March 1999. Its mission is to create open specifications for the network delivery of managed services to local networks and devices. The OSGi organization is the leading standard for next-generation Internet services to homes, cars, mobile phones, desktops, small offices, and other environments.

The OSGi Service Platform specification delivers an open, common architec-ture for service providers, developers, software vendors, gateway operators and equipment vendors to develop, deploy and manage services in a coordi-nated fashion. It enables an entirely new category of smart devices due to its flexible and managed deployment of services. OSGi specifications target set-top boxes, service gateways, cable modems, consumer electronics, PCs, industrial computers, cars, mobile phones, and more. Devices that imple-ment the OSGi specifications will enable service providers like telcos, cable operators, utilities, and others to deliver differentiated and valuable services over their networks.

This is the fourth release of the OSGi Service Platform specification devel-oped by representatives from OSGi member companies. The OSGi Service Platform Release 4 mostly extends the existing APIs into new areas. The few modifications to existing APIs are backward compatible so that applications for previous releases should run unmodified on Release 4 Frameworks. The built-in version management mechanisms allow bundles written for the new release to adapt to the old Framework implementations, if necessary.

1.1 OSGi Framework OverviewThe Framework forms the core of the OSGi Service Platform Specifications. It provides a general-purpose, secure, and managed Java framework that supports the deployment of extensible and downloadable applications known as bundles.

OSGi-compliant devices can download and install OSGi bundles, and remove them when they are no longer required. The Framework manages the installation and update of bundles in an OSGi environment in a dynamic and scalable fashion. To achieve this, it manages the dependencies between bundles and services in detail.

It provides the bundle developer with the resources necessary to take advan-tage of Java’s platform independence and dynamic code-loading capability in order to easily develop services for small-memory devices that can be deployed on a large scale.

The functionality of the Framework is divided in the following layers:

• Security Layer• Module Layer• Life Cycle Layer• Service Layer• Actual Services

OSGi Service Platform Release 4 3-268

Page 12: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

What Is New Introduction

The Security Layer is based on Java 2 security but adds a number of con-straints and fills in some of the blanks that standard Java leaves open. The Security Layer is described in Security Layer on page 13.

The Module Layer defines a modularization model for Java. It addresses some of the shortcomings of Java’s deployment model. The modularization layer has strict rules for sharing Java packages between bundles or hiding packages from other bundles. The Module Layer can be used without the life cycle and Service Layer. The Life Cycle Layer provides an API to manage the bundles in the Module Layer, while the Service Layer provides a commu-nication model for the bundles. The Module Layer is described in Module Layer on page 27.

The Life Cycle Layer provides a life cycle API to bundles. This API provides a runtime model for bundles. It defines how bundles are started and stopped as well as how bundles are installed, updated and uninstalled. Additionally, it provides a comprehensive event API to allow a management bundle to control the operations of the service platform. The Life Cycle Layer requires the Module Layer but the Security Layer is optional. A more extensive description of the Life Cycle layer can be found at Life Cycle Layer on page 79

The Service Layer provides a dynamic, concise and consistent programming model for Java bundle developers, simplifying the development and deploy-ment of service bundles by de-coupling the service’s specification (Java interface) from its implementations. This model allows bundle developers to bind to services only using their interface specifications. The selection of a specific implementation, optimized for a specific need or from a specific vendor, can thus be deferred to run-time.

A consistent programming model helps bundle developers cope with scal-ability issues in many different dimensions – critical because the Frame-work is intended to run on a variety of devices whose differing hardware characteristics may affect many aspects of a service implementation. Con-sistent interfaces insure that the software components can be mixed and matched and still result in stable systems.

The Framework allows bundles to select an available implementation at run-time through the Framework service registry. Bundles register new ser-vices, receive notifications about the state of services, or look up existing services to adapt to the current capabilities of the device. This aspect of the Framework makes an installed bundle extensible after deployment: new bundles can be installed for added features or existing bundles can be modi-fied and updated without requiring the system to be restarted.

The Service Layer is described in Service Layer on page 103.

1.2 What Is NewThe Framework specification has been completely rewritten because the changes made to the core Framework were large as well as the desire to sep-arate the specification into layers. These changes were so large that it is not possible to give a detailed list of changes; a coarser list must suffice.

• Improved modularization support – The Framework now supports the loading of multiple versions of the same package. To support the

4-268 OSGi Service Platform Release 4

Page 13: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction Reader Level

matching process, a number of attributes and directives are defined on the Import-Package and Export-Package headers. See Class Loading Archi-tecture on page 34.

• Optional linking on bundle level – Bundles can now directly import all the exports of another bundle, without explicitly mentioning these as imports. This is discussed in Requiring Bundles on page 66.

• Optional fragment bundles – Fragments are bundles without a class loader, they are attached to a host bundle, which provides the class loader. See Fragment Bundles on page 69.

• Extension bundles – An extension bundle extends the boot class path or the Framework class path. They are discussed in Extension Bundles on page 72.

• Manifest localization – Entries in the manifest can now be localized for dif-ferent markets. This is described in Localization on page 64.

• Signed bundles – A replacement for Package Admin is introduced called Conditional Permission Admin; it supports signed bundles. See Condi-tional Permission Admin Specification on page 207.

• Finer grained Admin Permission – The AdminPermiss ion class has been extended with a number of actions to support finer grained control. See Admin Permission on page 97.

• Bundle Permission – A new BundlePermiss ion class is introduced to capture the permission to access the classes and resources of other bundles. See Bundle Permission on page 74.

• Native code model – Some minor changes were made to the native code handling to support more complicated use cases. See Loading Native Code Libraries on page 59.

• Additional Event Types – Event types were introduced to signal the resolving and unresolving of bundles as well as other events. See Events on page 93.

• Bundle-Classpath extension – Bundle-Classpath headers now support direc-tories and not just JAR resources. See Bundle Class Path on page 51.

• Bundle resource URLs – This release now defines how URLs are con-structed that refer to resources. See Resource Loading on page 57.

1.3 Reader LevelThis specification is written for the following audiences:

• Application developers • Framework and system service developers (system developers)• Architects

The OSGi Specifications assume that the reader has at least one year of prac-tical experience in writing Java programs. Experience with embedded sys-tems and server environments is a plus. Application developers must be aware that the OSGi environment is significantly more dynamic than tradi-tional desktop or server environments.

OSGi Service Platform Release 4 5-268

Page 14: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conventions and Terms Introduction

System developers require a very deep understanding of Java. At least three years of Java coding experience in a system environment is recommended. A Framework implementation will use areas of Java that are not normally encountered in traditional applications. Detailed understanding is required of class loaders, garbage collection, Java 2 security, and Java native library loading.

Architects should focus on the introduction of each subject. This introduc-tion contains a general overview of the subject, the requirements that influ-enced its design, and a short description of its operation as well as the entities that are used. The introductory sections require knowledge of Java concepts like classes and interfaces, but should not require coding experi-ence.

Most of these specifications are equally applicable to application developers and system developers.

1.4 Conventions and Terms

1.4.1 TypographyA fixed width, non-serif typeface (sample) indicates the term is a Java pack-age, class, interface, or member name. Text written in this typeface is always related to coding.

Emphasis (sample) is used the first time an important concept is introduced. Its explanation usually follows directly after the introduction.

When an example contains a line that must be broken into multiple lines, the « character is used. Spaces must be ignored in this case. For example:

http://www.acme.com/sp/ «file?abc=12

is equivalent to:

http://www.acme.com/sp/file?abc=12

1.4.2 General Syntax DefinitionsIn many cases in these specifications, a syntax must be described. This syn-tax is based on the following symbols:

* Repetition of the previous element zero or more times, e.g. ( ’,’ element ) *

+ Repetition one or more times? Previous element is optional( ... ) Grouping’...’ Literal| Or[...] Set (one of).. list, e.g. 1..5 is the list 1 2 3 4 5<...> Externally defined token

The following tokens are pre defined and used throughout the specifica-tions:

6-268 OSGi Service Platform Release 4

Page 15: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction Conventions and Terms

digit ::= [0..9]alpha ::= [a..zA..Z]alphanum ::= alpha | digittoken ::= ( alphanum | ’_’ | ’-’ )*number ::= digit+jletter ::= <see [5] Lexical Structure Java Language for

JavaLetter>jletterordigit::= <See [5] Lexical Structure Java Language for

JavaLetterOrDigit >

qname ::= /* See [5] Lexical Structure Java Language forfully qualified class names */

identifier ::= jletter jletterordigit *quoted-string ::= ’"’ ( [^"\#x0D#x0A#x00] | ’\"’|’\\’)* ’"’argument ::= token | quoted-string parameter ::= directive | attributedirective ::= token ’:=’ argumentattribute ::= token ’=’ argument

unique-name ::= identifier ( ’.’ identifier )*symbolic-name :: = token('.'token)*package-name ::= unique-name

path ::= path-unquoted | (’"’ path-unquoted ’"’)path-unquoted ::= path-sep | path-sep? path-element

(path-sep path-element)*path-element ::= [^/"\#x0D#x0A#x00]+path-sep ::= ’/’

The is JavaIdent i f ierStart and i s JavaIdent if ierPart methods of the Character class are not included in the Minimum Execution Environment. This can make it difficult or expensive for an embedded device to conform to this specification. Therefore, it is allowed to assume that any character having a code of more than \u00FF is a j letterordig it or j letter .

Spaces (’ ’ \u0020) are ignored unless specifically noted.

1.4.3 Object Oriented TerminologyConcepts like classes, interfaces, objects, and services are distinct but subtly different. For example, “LogService” could mean an instance of the class LogService , could refer to the class LogService , or could indicate the func-tionality of the overall Log Service. Experts usually understand the meaning from the context, but this understanding requires mental effort. To high-light these subtle differences, the following conventions are used.

When the class is intended, its name is spelled exactly as in the Java source code and displayed in a fixed-width typeface: for example, the “HttpService class”, “a method in the HttpContext c lass” or “a javax.servlet .Servlet object”. A class name is used in its fully qualified form, like javax .servlet.Servlet , when the package is not obvious from the context, nor is it in one of the well known java packages like java. lang , java. io , java.ut i l and java.net . Otherwise, the package is omitted like in Str ing .

OSGi Service Platform Release 4 7-268

Page 16: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conventions and Terms Introduction

Exception and permission classes are not followed by the word “object”. Readability is improved when the “object” suffix is avoided. For example, “to throw a Security Exception” and to “to have File Permission” is more read-able then “to have a Fi lePermission object”.

Permissions can further be qualified with their actions. ServicePermission[com.acme.*,GET|REGISTER] means a ServicePermission with the action GET and REGISTER for all service names starting with com.acme . A ServicePermission[Producer |Consumer , REGISTER] means the ServicePermiss ion for the Producer or Consumer class with REGISTER action.

When discussing functionality of a class rather than the implementation details, the class name is written as normal text. This convention is often used when discussing services. For example, “the User Admin service” is more readable.

Some services have the word “Service” embedded in their class name. In those cases, the word “service” is only used once but is written with an upper case S. For example, “the Log Service performs”.

Service objects are registered with the OSGi Framework. Registration con-sists of the service object, a set of properties, and a list of classes and inter-faces implemented by this service object. The classes and interfaces are used for type safety and naming. Therefore, it is said that a service object is regis-tered under a class/interface. For example, “This service object is registered under PermissionAdmin .”

1.4.4 DiagramsThe diagrams in this document illustrate the specification and are not nor-mative. Their purpose is to provide a high-level overview on a single page. The following paragraphs describe the symbols and conventions used in these diagrams.

Classes or interfaces are depicted as rectangles, as in Figure 1. Interfaces are indicated with the qualifier <<inter face>> as the first line. The name of the class/interface is indicated in bold when it is part of the specification. Imple-mentation classes are sometimes shown to demonstrate a possible imple-mentation. Implementation class names are shown in plain text. In certain cases class names are abbreviated. This is indicated by ending the abbrevia-tion with a period.

Figure 1 Class and interface symbol

If an interface or class is used as a service object, it will have a black triangle in the bottom right corner.

<<interface>>BundleContext

<<class>>AdminPermission

UserAdminImplementation

class interface implementation class

8-268 OSGi Service Platform Release 4

Page 17: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction Conventions and Terms

Figure 2 Service symbol

Inheritance (the extends or implements keyword in Java class definitions) is indicated with an arrow. Figure 3 shows that the AdminPermission class implements or extends the Permission class.

Figure 3 Inheritance (implements or extends) symbol

Relations are depicted with a line. The cardinality of the relation is given explicitly when relevant. Figure 4 shows that each (1) BundleContext object is related to 0 or more BundleListener objects, and that each BundleListener object is related to a single BundleContext object. Relations usually have some description associated with them. This description should be read from left to right and top to bottom, and includes the classes on both sides. For example: “A BundleContext object delivers bundle events to zero or more BundleListener objects.”

Figure 4 Relations symbol

Associations are depicted with a dashed line. Associations are between classes, and an association can be placed on a relation. For example, “every ServiceRegistrat ion object has an associated ServiceReference object.” This association does not have to be a hard relationship, but could be derived in some way.

When a relationship is qualified by a name or an object, it is indicated by drawing a dotted line perpendicular to the relation and connecting this line to a class box or a description. Figure 5 shows that the relationship between a UserAdmin class and a Role class is qualified by a name. Such an associa-tion is usually implemented with a Dictionary object.

Figure 5 Associations symbol

Bundles are entities that are visible in normal application programming. For example, when a bundle is stopped, all its services will be unregistered. Therefore, the classes/interfaces that are grouped in bundles are shown on a grey rectangle as is shown in Figure 6.

<<interface>>PermissionAdmin

<<class>> Permission

<<class>>Admin Permission

<<interface>>BundleListener

<<interface>>BundleContext

0..*1 delivers bundle events

<<interface>>Role

<<interface>>UserAdmin 0..*1

name

OSGi Service Platform Release 4 9-268

Page 18: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Version Information Introduction

Figure 6 Bundles

1.4.5 Key WordsThis specification consistently uses the words may, should, and must. Their meaning is well-defined in [1] Bradner, S., Key words for use in RFCs to Indicate Requirement Levels. A summary follows.

• must – An absolute requirement. Both the Framework implementation and bundles have obligations that are required to be fulfilled to conform to this specification.

• should – Recommended. It is strongly recommended to follow the description, but reasons may exist to deviate from this recommendation.

• may or can – Optional. Implementations must still be interoperable when these items are not implemented.

1.5 Version InformationThis document specifies OSGi Service Platform Core Specification, Release 4. This specification is backward compatible to releases 1, 2, and 3.

All Security, Module, Life Cycle and Service Layers are part of the Frame-work Specification

Components in this specification have their own specification version, independent of the document release number. The following table summa-rizes the packages and specification versions for the different subjects.

When a component is represented in a bundle, a version is needed in the declaration of the Import-Package or Export-Package manifest headers.

<<interface>>Role

<<interface>>UserAdmin 0.n1 has

name

UserAdminImpl RoleImplImplementationbundle

Permission

0..n

1

Table 1 Packages and versionsItem Package VersionFramework Spec i f ication (a l l layers) org.osgi .f ramework Version 1 .39 Condit ional Permission Admin Spec if ica-t ion

org.osgi .service .condpermission-admin

Version 1 .0

7 Package Admin Service Speci f ication org.osgi .service.packageadmin Version 1 .210 Permission Admin Service Speci f icat ion org.osgi .service.permissionadmin Version 1 .28 Start Level Service Spec i f ication org.osgi .service.start level Version 1 .011 URL Handlers Service Spec i f ication org.osgi .service.url Version 1 .0

10-268 OSGi Service Platform Release 4

Page 19: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction References

1.6 References[1] Bradner, S., Key words for use in RFCs to Indicate Requirement Levels

http://www.ietf.org/rfc/rfc2119.txt, March 1997.

[2] OSGi Service Gateway Specification 1.0, May 2000http://www.osgi.org/resources/spec_download.asp

[3] OSGi Service Platform, Release 2, October 2001http://www.osgi.org/resources/spec_download.asp

[4] OSGi Service Platform, Release 3, March 2003http://www.osgi.org/resources/spec_download.asp

[5] Lexical Structure Java Languagehttp://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html

OSGi Service Platform Release 4 11-268

Page 20: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Introduction

12-268 OSGi Service Platform Release 4

Page 21: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 Introduction

2 Security LayerVersion 1.3

2.1 IntroductionThe OSGi Security Layer is an optional layer that underlies the OSGi Service Platform. The layer is based on the Java 2 security architecture. It provides the infrastructure to deploy and manage applications that must run in fine-grained controlled environments.

2.1.1 Essentials• Fine-grained – The control of applications running in an OSGi

Framework must allow for detailed control of those applications.• Manageable – The security layer itself does not define an API to control

the applications. The management of the security layer is left to the life cycle layer.

• Optional – The security layer is optional.

2.2 Security OverviewThe Framework security model is based on the Java 2 specification. If secu-rity checks are performed, they must be done according to [8] Java 2 Security Architecture. It is assumed that the reader is familiar with this specification. The security layer is optional, see Optional Security on page 14.

2.2.1 Code AuthenticationThe OSGi Service Platform can authenticate code in the following ways:

• By location• By signer

At higher layers there are defined services that can manage the permissions that are associated with the authenticated unit of code. These services are:

• Permission Admin service – Manages the permission based on full location strings.

• Conditional Permission Admin service – Manages the permissions based on a comprehensive conditional model, where the conditions can test for location or signer.

For signing, this requires the JAR files to be signed; this is described in Digi-tally Signed JAR Files on page 14.

OSGi Service Platform Release 4 13-268

Page 22: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Digitally Signed JAR Files Security Layer Version 1.3

2.2.2 Optional SecurityThe Java platform on which the Framework runs must provide the Java Security APIs necessary for Java 2 permissions. On resource-constrained platforms, these Java Security APIs may be stubs that allow the bundle classes to be loaded and executed, but the stubs never actually perform the security checks. The behavior of these stubs must be as follows:

• checkPermission – Return without throwing a Secur ityExcept ion .• checkGuard – Return without throwing a SecurityException .• implies – Return true .

This behavior allows code to run as if all bundles have Al lPermiss ion .

2.3 Digitally Signed JAR FilesThis section defines in detail how JAR files must be signed. This section therefore overlaps with the different JAR file specifications that are part of the different versions of Java. The reason for this duplication is that there are many aspects left as optional or not well-defined in these specifications. A reference was therefore insufficient.

Digitally signing is a security feature that verifies the following:

• Authenticates the signer• Ensures that the content has not been modified after it was signed by the

principal.

In an OSGi Framework, the principals that signed a JAR become associated with that JAR. This association is then used to:

• Grant permissions to a JAR based on the authenticated principal• Target a set of bundles by principal for a permission to operate on or

with those bundles

For example, an Operator can grant the ACME company the right to use net-working on their devices. The ACME company can then use networking in every bundle they digitally sign and deploy on the Operator’s device. Also, a specific bundle can be granted permission to only manage the life cycle of bundles that are signed by the ACME company.

Signing provides a powerful delegation model. It allows an Operator to grant a restricted set of permissions to a company, after which the company can create JARs that can use those permissions, without requiring any inter-vention of, or communication with, the Operator for each particular JAR. This delegation model is shown graphically in Figure 7.

14-268 OSGi Service Platform Release 4

Page 23: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 Digitally Signed JAR Files

Figure 7 Delegation model

Digital signing is based on public key cryptography. Public key cryptography uses a system where there are two mathematically related keys: a public and a private key. The public key is shared with the world and can be dispersed freely, usually in the form of a certificate. The private key must be kept a secret.

Messages signed with the private key can only be verified correctly with the public key. This can be used to authenticate the signer of a message (assum-ing the public key is trusted, this is discussed in Certificates on page 18).

The digital signing process used is based on Java 2 JAR signing. The process of signing is repeated, restricted and augmented here to improve the interoperability of OSGi bundles.

2.3.1 JAR Structure and ManifestA JAR can be signed by multiple signers. Each signer must store two resources in the JAR file. These resources are:

• A signature instruction resource that has a similar format like the Man-ifest. It must have a .SF extension. This file provides digests for the com-plete manifest file.

• A PKCS#7 resource that contains the digital signature of the signature instruction resource. See [16] Public Key Cryptography Standard #7 for information about its format.

These JAR file signing resources must be placed in the META-INF directory. For signing, the META-INF directory is special because files in there are not signed in the normal way. These signing resources must come directly after the MANIFEST.MF file, and before any other resources in a JAR stream. If this is not the case, then a Framework should not accept the signatures and must treat the bundle as unsigned. This ordering is important because it allows the receiver of the JAR file to stream the contents without buffering. All the security information is available before any resources are loaded. This model is shown in Figure 8.

Developer

Operator

Enterprise

OSGi Service PlatformEmployee

grantsuses

provides

installs

permissions

OSGi Service Platform Release 4 15-268

Page 24: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Digitally Signed JAR Files Security Layer Version 1.3

Figure 8 Signer files in JAR

The signature instruction resource contains digests of the Manifest resource, not the actual resource data itself. A digest is a one way function that computes a value from the bytes of a resource in such a way that it is very difficult to create a set of bytes that matches that digest value.

The JAR Manifest must therefore contain one or more digests of the actual resources. These digests must be placed in their name section of the mani-fest. The name of the digest header is constructed with its algorithm fol-lowed by -Digest . An example is the SHA1-Digest . It is recommended that OSGi Framework implementations support the following digest algo-rithms.

• MD5 – Message Digest 5, an improved version of MD4. It generates a 128-bit hash. It is described at page 436 in [12] RFC 1321 The MD5 Message-Digest Algorithm.

• SHA1 – An improved version of SHA, delivers a 160 bit hash. It is defined in [11] Secure Hash Algorithm 1.

The hash must be encoded with a Base 64 encoding. Base 64 encoding is defined in [13] RFC 1421 Privacy Enhancement for Internet Electronic Mail.

For example, a manifest could look like:

Manifest-Version: 1.0Bundle-Name: DisplayManifest↵Name: x/A.classSHA1-Digest: RJpDp+igoJ1kxs8CSFeDtMbMq78=↵Name: x/B.classSHA1-Digest: 3EuIPcx414w2QfFSXSZEBfLgKYA=↵

Graphically this looks like Figure 9.

Figure 9 Signer files in JAR

META-INF/MANIFEST.MFACME.SFACME.RSADAFFY.SFDAFFY.DSA

... other files

META-INF/

MANIFEST.MF

... other files

Manifest-Version: 1.0

Name: x/A.classSHA1-Digest:RJpDp+igoJ1k...

Name: x/B.classSHA1-Digest: 3EuIPcx414w2...

x/A.class

x/B.class

16-268 OSGi Service Platform Release 4

Page 25: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 Digitally Signed JAR Files

OSGi JARs must be signed by one or more signers that sign all resources except the ones in the META-INF directory; the default behavior of the jar-signer tool. This is a restriction with respect to standard Java JAR signing; there is no partial signing for an OSGi JAR. The OSGi specification only sup-ports fully signed bundles. The reason for this restriction is because partially signing can break the protection of private packages. It also simplifies the security API because all code of a bundle is using the same protection domain.

Signature files in nested JAR files (For example JARs on the Bundle-Classpath) must be ignored. These nested JAR files must share the same pro-tection domain as their containing bundle. They must be treated as if their resources were stored directly in the outer JAR.

Each signature is based on two resources. The first file is the signature instruction file; this file must have a file name with an extension .SF . A sig-nature file has the same syntax as the manifest, except that it starts with Signature-Version: 1 .0 instead of Manifest-Vers ion: 1 .0 .

The only relevant part of the signature resource is the digest of the Manifest resource. The name of the header must be the name algorithm (e.g. SHA1) followed by -Digest-Manifest . For example:

Signature-Vers ion: 1 .0SHA1-Digest-Manifest: RJpDp+igoJ1kxs8CSFeDtMbMq78=MD5-Digest-Manifest: IIsI6HranRNHMY27SK8M5qMunR4=

The signature resource can contain name sections as well. However, these name sections should be ignored.

If there are multiple signers, then their signature instruction resources can be identical if they use the same digest algorithms. However, each signer must still have its own signature instruction file. That is, it is not allowed to share the signature resource between signers.

The indirection of the signature instruction files digests is depicted in Fig-ure 10 for two signers: ACME and DAFFY .

Figure 10 Manifest, signature instruction files and digests in JAR

META-INF/

MANIFEST.MF

... other files

ACME.SF

DAFFY.SFDigest functionsManifest entry

certificates

signaturewith private key

certificates

signaturewith private key

ACME.RSA

DAFFY.DSA

Resource

OSGi Service Platform Release 4 17-268

Page 26: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Digitally Signed JAR Files Security Layer Version 1.3

2.3.2 Java JAR File RestrictionsOSGi bundles are always valid JAR files. However, there are a few restric-tions that apply to bundles that do not apply to JAR files.

• Bundles do not support partially signed bundles. The manifest must contain name sections for all resources except the resources in the META-INF directory.

• The name sections in the signature files are ignored. Only the Manifest digest is used.

2.3.3 Signing AlgorithmsSeveral different available algorithms can perform digital signing. OSGi Framework implementations should support the following algorithms:

• DSA – The Digital Signature Algorithm. This standard is defined in [14] DSA. This is a USA government standard for Digital Signature Standard. The signature resource name must have an extension of .DSA .

• RSA – Rivest, Shamir and Adleman. A public key algorithm that is very popular. It is defined in [15] RSA. The extension of the signature resource name must be .RSA .

The signature files for RSA and DSA are stored in a PCKS#7 format. This is a format that has a structure as defined in [16] Public Key Cryptography Stan-dard #7. The PKCS#7 standard provides access to the algorithm specific sign-ing information as well as the certificate with the public key of the signer. The verification algorithm uses the public key to verify that:

• The digital signature matches the signature instruction resource.• The signature was created with the private key associated with the certif-

icate.

The complete signing structure is shown in Figure 10.

2.3.4 CertificatesA certificate is a general term for a signed document containing a name and public key information. Such a certificate can take many forms but the OSGi JAR signing is based on the X.509 certificate format. It has been around for many years and is part of the OSI group of standards. X.509 is defined in [7] X.509 Certificates.

An X.509 certificate contains the following elements:

• Subject Name – The subject name is a unique identifier for the object being certified. In the case of a person this might include the name, nationality and e-mail address, the organization, and the department within that organization. This identifier is a Distinguished Name, which is defined in Distinguished Names on page 20.

• Issuer Name – The Issuer name is a Distinguished Name for the principal that signed this certificate.

• Certificate Extensions – A certificate can also include pictures, codification of fingerprints, passport number, and other extensions.

• Public Key Information – A public key can be used with an encryption technique that requires its private counterpart to decrypt, and vice versa. The public key can be shared freely, the private key must be kept secret.

18-268 OSGi Service Platform Release 4

Page 27: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 Digitally Signed JAR Files

The public key information specifies an algorithm identifier (such as DSA or RSA) and the subject's public key.

• Validity – A Certificate can be valid for only a limited time.• Certifying Authority Signature – The Certificate Authority signs the first

elements and thereby adds credibility to the certificate. The receiver of a certificate can check the signature against a set of trusted certifying authorities. If the receiver trusts that certifying authority, it can trust the statement that the certificate makes.

The structure of a certificate is depicted in Figure 11.

Figure 11 Structure of a certificate

Certificates can be freely dispersed; they do not contain any secret informa-tion. Therefore, the PKCS#7 resource contains the signing certificate. It can-not be trusted at face value because the certificate is carried in the bundle itself. A perpetrator can easily create its own certificate with any content. The receiver can only verify that the certificate was signed by the owner of the public key (the issuer) and that it has not been tampered with. However, before the statement in the certificate can be trusted, it is necessary to authenticate the certificate itself. It is therefore necessary to establish a trust model.

One trust model, supported but not required by the OSGi specifications, is placing the signing certificate in a repository. Any certificate in this reposi-tory is treated as trusted by default. However, placing all possible certificates in this repository does not scale well. In an open model, a device would have to contain hundreds of thousands of certificates. The management of the certificates could easily become overwhelming.

The solution is to sign a certificate by another certificate, and this process can be repeated several times. This delegation process forms a chain of certifi-cates. All certificates for this chain are carried in the PKCS#7 file: if one of those certificates can be found in the trusted repository, the other depen-dent ones can be trusted, on the condition that all the certificates are valid. This model scales very well because only a few certificates of trusted signers need to be maintained. This is the model used in web browsers, as depicted in Figure 12.

private key from other certificate

subject DN

public key

issuer DN

signature

extensions

validitydigest

digital signing algorithm

OSGi Service Platform Release 4 19-268

Page 28: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Digitally Signed JAR Files Security Layer Version 1.3

Figure 12 Certificate authorities fan out

This specification does not specify access to the trusted repository. It is implementation specific how this repository is populated and maintained.

2.3.5 Distinguished NamesAn X.509 name is a Distinguished Name (DN). A DN is a highly structured name, officially identifying a node in an hierarchical name space. The DN concept was developed for the X.500 directory service which envisioned a world wide name space managed by PTTs. Today, the DN is used as an iden-tifier in a local name space, as in a name space designed by an Operator. For example, given a name space that looks like Figure 13, the DN identifying Bugs looks like:

cn=Bug,o=ACME,c=US

Figure 13 Country, Company, Person based name space.

The traversal of the name space is reversed from the order in the DN, the first part specifies the least significant but most specific part. That is, the order of the attribute assertions is significant. Two DNs with the same attributes but different order are different DNs.

ThawteSigning

AppCert

ThawteRoot

Trusted Repository

Signs

c=US

o=ACME

cn=Bugs

Root

US

ACME

FR

Obelix

Bugs

Root

C = Country

O = OrganizationO = Organization

CN = Common Name

1*

1*

1*

20-268 OSGi Service Platform Release 4

Page 29: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 Digitally Signed JAR Files

In the example, a node is searched in the root that has an attribute c (countryName) with a value that is US . This node is searched for a child that has an attribute o (organizationName) with a value of ACME . And the ACME node is searched for a child node with an attribute cn (commonName) that has a value "Bugs Bunny" .

The tree based model is the official definition of a DN from the X.500 stan-dards. However, in practice today, many DNs contain attributes that have no relation to a tree. For example, many DNs contain comments and copy-rights in the ou (organizationa lUnit) attribute.

The DN from an X.509 certificate is expressed in a binary structure defined by ASN.1 (a type language defined by ISO). However, the Distinguished Name is often used in interaction with humans. Sometimes, users of a sys-tem have to acknowledge the use of a certificate or an employee of an Oper-ator must grant permissions based on a Distinguished Name of a customer. It is therefore paramount that the Distinguished Name has a good human readable string representation. The expressiveness of the ASN.1 type lan-guage makes this non-trivial. This specification only uses DN strings as defined in [6] RFC 2253 with a number of extensions that are specified by the javax .secur i ty .auth.x500.X500Pr incipal class in CANONICAL form.

However, the complexity of the encoding/decoding is caused by the use of rarely used types and features (binary data, multi-valued RDNs, foreign alphabets, and attributes that have special matching rules). These features must be supported by a compliant implementation but should be avoided by users. In practice, these features are rarely used today.

The format of a string DN is as follows:

dn ::= rdn ( ’,’ rdn ) *rdn ::= attribute ( ’+’ attribute ) *attribute ::= name ’=’ valuename ::= readable | oidoid ::= number ( ’.’ number ) * // See 1.4.2readable ::= <see attribute table>value ::= <escaped string>

Spaces before and after the separators are ignored, spaces inside a value are significant but multiple embedded spaces are collapsed into a single space. Wildcard characters (’*’ \u002A ) are not allowed in a value part. The fol-lowing characters must be escaped with a back slash:

comma ’,’ \u002Cplus ’+’ \u002Bdouble quote ’"’ \u0022back slash ’\’ \u005Cless then ’<’ \u003Cgreater then ’>’ \u003Esemicolon ’;’ \u003B

Backslashes must already be escaped in Java strings, requiring 2 backslashes in Java source code. For example:

DN: cn = Bugs Bunny, o = ACME++, C=USCanonical form: cn=bugs bunny,o=acme\+\+,c=usJava String: "cn=bugs bunny,o=acme\\+\\+,c=us"

OSGi Service Platform Release 4 21-268

Page 30: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Digitally Signed JAR Files Security Layer Version 1.3

The full unicode character set is available and can be used in DNs. String objects must be normalized and put in canonical form before being com-pared.

DN: cn = Bugs Bunny, o = Ð Þ, C=USCanonical form: cn=bugs bunny,o=ð þ,c=usJava String: "cn = Bugs Bunny, o = Ð Þ, C=US"

The names of attributes (attributes types as they are also called) are actually translated into an Object IDentifier (OID). An OID is a dotted decimal num-ber, like 2.5.4.3 for the cn (commonName) attribute name. It is therefore not possible to use any attribute name because the implementation must know the aliasing as well as the comparison rules. Therefore only the attributes that are listed in the following table are allowed (in short or long form):

commonName cn 2.5.4.3 ITU X.520surName sn 2.5.4.4 countryName c 2.5.4.6localityName l 2.5.4.7 stateOrProvinceName st 2.5.4.8organizationName o 2.5.4.10 organizationalUnitName ou 2.5.4.11title 2.5.4.12 givenName 2.5.4.42 initials 2.5.4.43 generationQualifier 2.5.4.44 dnQualifier 2.5.4.46

streetAddress street RFC 2256domainComponent dc RFC 1274userid uid RFC 1274/2798?emailAddress RFC 2985serialNumber RFC 2985

The following DN:

2.5.4.3=Bugs Bunny,organizationName=ACME,2.5.4.6=US

Is therefore identical to:

cn=Bugs Bunny,o=ACME,c=US

The attribute types officially define a matching rule, potentially allowing cases sensitive and case insensitive. The attributes in the previous list all match case insensitive. Therefore, an OSGi DN must not depend on case sen-sitivity.

The X.500 standard supports multi-valued RDNs, however, their use is not recommended. See [18] Understanding and Deploying LDAP Directory Services for the rationale of this recommendation. Multi-valued RDNs separate their constituents with a plus sign (’+ ’ \u002B). Their order is not significant. For example:

cn=Bugs Bunny+dc=x.com+title=Manager,o=ACME,c=US

Which is the same as

dc=x.com+cn=Bug Bunny+title=Manager, o=ACME, c=US"

22-268 OSGi Service Platform Release 4

Page 31: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 Digitally Signed JAR Files

2.3.6 Certificate MatchingCertificates are matched by their Subject DN. Before matching, DNs, they must first be put in canonical form according to the algorithm specified in javax .secur i ty .auth.x500.X500Pr incipal .

DNs can also be compared using wildcards. A wildcard (’*’ \u002A) replaces all possible values. Due to the structure of the DN, the comparison is more complicated than string-based wildcard matching.

A wildcard can stand for a number of RDNs, or the value of a single RDN. DNs with a wildcard must be canonicalized before they are compared. This means, among other things, that spaces must be ignored, except in values.

The format of a wildcard DN match is:

CertificateMatch::= dn-match ( ’;’ dn-match ) *dn-match ::= ( ’*’ | rdn-match )

( ’,’ rdn-match ) * | ’-’ rdn-match ::= name ’=’ value-matchvalue-match ::= ’*’ | value-starvalue-star ::= < value, requires escaped ’*’ and ’-’ >

The most simple case is a single wildcard; it must match any DN. A wildcard can also replace the first list of RDNs of a DN. The first RDNs are the least significant. Such lists of matched RDNs can be empty.

For example, a DN with a wildcard that matches all nodes descendant from the ACME node in Figure 13 on page 20, looks like:

*, o=ACME, c=US

This wildcard DN matches the following DNs:

cn = Bugs Bunny, o = ACME, c = USou = Carots, cn=Daffy Duck, o=ACME, c=USstreet = 9C\, Avenue St. Drézéry, o=ACME, c=USdc=www, dc=acme, dc=com, o=ACME, c=USo=ACME, c=US

The following DNs must not match:

street = 9C\, Avenue St. Drézéry, o=ACME, c=FRdc=www, dc=acme, dc=com, c=US

If a wildcard is used for a value of an RDN, the value must be exactly * . The wildcard must match any value, and no substring matching must be done. For example:

cn=*,o=ACME,c=*

This DN with wildcard must match the following DNs:

cn=Bugs Bunny,o=ACME,c=UScn = Daffy Duck , o = ACME , c = UScn=Road Runner, o=ACME, c=NL

But not:

o=ACME, c=NLdc=acme.com, cn=Bugs Bunny, o=ACME, c=US

OSGi Service Platform Release 4 23-268

Page 32: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Security Layer Version 1.3

Both forms of wildcard usage can be combined in a single matching DN. For example, to match any DN that is from the ACME company worldwide, use:

*, o=ACME, c=*

Matching of a DN takes place in the context of a certificate. This certificate is part of a certificate chain, see Certificates on page 18. Each certificate has a Subject DN and an Issuer DN. The Issuer DN is the Subject DN used to sign the first certificate of the chain. DN matching can therefore be extended to match the signer. The semicolon (’;’ \u003B) must be used to separate DNs in a chain.

The following example matches a certificate signed by Tweety Inc . in the US.

* ; ou=S & V, o=Tweety Inc., c=US

The wildcard matches zero or one certificates,

however, sometimes it is necessary to match a longer chain. The minus sign (’ - ’ \u002D ) represents zero or more certificates, whereas the asterisk only represents a single certificate. For example, to match a certificate where the Tweety Inc . is in the certificate chain, use the following expression:

- ; *, o=Tweety Inc., c=US

The previous example matched if the Tweety Inc . certificate was trusted, or was signed by a trusted certificate. Certain certificates are trusted because they are known by the Framework, how they are known is implementation-defined.

2.4 References[6] RFC 2253

http://www.ietf.org/rfc/rfc2253.txt

[7] X.509 Certificateshttp://www.ietf.org/rfc/rfc2459.txt

[8] Java 2 Security ArchitectureVersion 1.2, Sun Microsystems, March 2002

[9] The Java 2 Package Versioning Specificationhttp://java.sun.com/j2se/1.4/docs/guide/versioning/index.html

[10] Manifest Format http://java.sun.com/j2se/1.4/docs/guide/jar/jar.html#JAR%20Manifest

[11] Secure Hash Algorithm 1http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf

[12] RFC 1321 The MD5 Message-Digest Algorithm http://www.ietf.org/rfc/rfc1321.txt

[13] RFC 1421 Privacy Enhancement for Internet Electronic Mailhttp://www.ietf.org/rfc/rfc1421.txt

[14] DSAhttp://www.itl.nist.gov/fipspubs/fip186.htm

24-268 OSGi Service Platform Release 4

Page 33: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Layer Version 1.3 References

[15] RSAhttp://www.ietf.org/rfc/rfc2313.txt which is superseded byhttp://www.ietf.org/rfc/rfc2437.txt

[16] Public Key Cryptography Standard #7http://www.rsasecurity.com/rsalabs/node.asp?id=2129

[17] Unicode Normalization UAX # 15http://www.unicode.org/reports/tr15/

[18] Understanding and Deploying LDAP Directory ServicesISBN 1-57870-070-1

OSGi Service Platform Release 4 25-268

Page 34: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Security Layer Version 1.3

26-268 OSGi Service Platform Release 4

Page 35: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Introduction

3 Module LayerVersion 1.3

3.1 IntroductionThe standard Java platform provides only limited support for packaging, deploying, and validating Java-based applications and components. Because of this, many Java-based projects, such as JBoss and NetBeans, have resorted to creating custom module-oriented layers with specialized class loaders for packaging, deploying, and validating applications and components. The OSGi Framework provides a generic and standardized solution for Java mod-ularization.

3.2 BundlesThe Framework defines a unit of modularization, called a bundle. A bundle is comprised of Java classes and other resources, which together can provide functions to end users. Bundles can share Java packages among an exporter bundle and an importer bundle in a well-defined way.

In the OSGi Service Platform, bundles are the only entities for deploying Java-based applications.

A bundle is deployed as a Java ARchive (JAR) file. JAR files are used to store applications and their resources in a standard ZIP-based file format. This for-mat is defined by [27] Zip File Format.

A bundle is a JAR file that:

• Contains the resources necessary to provide some functionality. These resources may be class files for the Java programming language, as well as other data such as HTML files, help files, icons, and so on. A bundle JAR file can also embed additional JAR files that are available as resources and classes. This is however not recursive.

• Contains a manifest file describing the contents of the JAR file and pro-viding information about the bundle. This file uses headers to specify information that the Framework needs to install correctly and activate a bundle. For example, it states dependencies on other resources, such as Java packages, that must be available to the bundle before it can run.

• Can contain optional documentation in the OSGI-OPT directory of the JAR file or one of its sub-directories. Any information in this directory is optional. For example, the OSGI-OPT directory is useful to store the source code of a bundle. Management systems may remove this infor-mation to save storage space in the OSGi Service Platform.

Once a bundle is started, its functionality is provided and services are exposed to other bundles installed in the OSGi Service Platform.

OSGi Service Platform Release 4 27-268

Page 36: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Bundles Module Layer Version 1.3

3.2.1 Bundle Manifest HeadersA bundle can carry descriptive information about itself in the manifest file that is contained in its JAR file under the name of META-INF/MANIFEST.MF .

The Framework defines OSGi manifest headers such as Export-Package and Bundle-Classpath, which bundle developers use to supply descriptive infor-mation about a bundle. Manifest headers must strictly follow the rules for manifest headers as defined in [28] Manifest Format.

A Framework implementation must:

• Process the main section of the manifest. Individual sections of the man-ifest are only used during bundle signature verification.

• Ignore unrecognized manifest headers. The bundle developer can define additional manifest headers as needed.

• Ignore unknown attributes and directives.

All specified manifest headers are listed in the following sections. All head-ers are optional, unless specifically indicated.

3.2.1.1 Bundle-Activator: com.acme.fw.ActivatorThe Bundle-Activator header specifies the name of the class used to start and stop the bundle.

3.2.1.2 Bundle-Category: osgi, test, nurseryThe Bundle-Category header holds a comma-separated list of category names.

3.2.1.3 Bundle-Classpath: /jar/http.jar,.The Bundle-Classpath header defines a comma-separated list of JAR file path names or directories (inside the bundle) containing classes and resources. The period (’.’) specifies the root directory of the bundle’s JAR. The period is also the default. See Bundle Class Path on page 51.

3.2.1.4 Bundle-ContactAddress: 2400 Oswego Road, Austin, TX 74563The Bundle-ContactAddress header provides the contact address of the ven-dor.

3.2.1.5 Bundle-Copyright: OSGi (c) 2002The Bundle-Copyright header contains the copyright specification for this bundle.

3.2.1.6 Bundle-Description: Network FirewallThe Bundle-Description header defines a short description of this bundle.

3.2.1.7 Bundle-DocURL: http:/www.acme.com/Firewall/docThe Bundle-DocURL headers must contain a URL pointing to documenta-tion about this bundle.

3.2.1.8 Bundle-Localization: OSGI-INF/l10n/bundle

The Bundle-Location header contains the location in the bundle where localization files can be found. The default value is OSGI-INF/l10n/bundle .

3.2.1.9 Bundle-ManifestVersion: 2The Bundle-ManifestVersion header defines that the bundle follows the rules of this specification. The Bundle-ManifestVersion header determines whether the bundle follows the rules of this specification. It is 1 (the default) for Release 3 Bundles, 2 for Release 4 and later. Future version of the

28-268 OSGi Service Platform Release 4

Page 37: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Bundles

OSGi Service Platform can define higher numbers for this header.

3.2.1.10 Bundle-Name: FirewallThe Bundle-Name header defines a readable name for this bundle. This should be a short, human-readable name containing no spaces.

3.2.1.11 Bundle-NativeCode: /lib/http.DLL; osname = QNX; osversion = 3.1The Bundle-NativeCode header contains a specification of native code libraries contained in this bundle. See Loading Native Code Libraries on page59.

3.2.1.12 Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0The Bundle-RequiredExecutionEnvironment contains a comma-separated list of execution environments that must be present on the Service Platform. See Execution Environment on page 33.

3.2.1.13 Bundle-SymbolicName: com.acme.daffyThe Bundle-SymbolicName header specifies a unique, non-localizable name for this bundle. This name should be based on the reverse domain name convention, see Bundle-SymbolicName on page 37. This header must be set.

3.2.1.14 Bundle-UpdateLocation: http://www.acme.com/Firewall/bundle.jarThe Bundle-UpdateLocation header specifies a URL where an update for this bundle should come from. If the bundle is updated, this location should be used, if present, to retrieve the updated JAR file.

3.2.1.15 Bundle-Vendor: OSGi AllianceThe Bundle-Vendor header contains a human-readable description of the bundle vendor.

3.2.1.16 Bundle-Version: 1.1The Bundle-Version header specifies the version of this bundle. See Version on page 30. The default value is 0.0 .0

3.2.1.17 DynamicImport-Package: com.acme.plugin.*The DynamicImport-Package header contains a comma-separated list of package names that should be dynamically imported when needed. See Dynamic Import Package on page 52.

3.2.1.18 Export-Package: org.osgi.util.tracker;version=1.3The Export-Package header contains a declaration of exported packages. See Export-Package on page 39.

3.2.1.19 Export-Service: org.osgi.service.log.LogServiceDeprecated.

3.2.1.20 Fragment-Host: org.eclipse.swt; bundle-version="[3.0.0,4.0.0)"The Fragment-Host header defines the host bundle for this fragment. See Fragment-Host on page 70

3.2.1.21 Import-Package: org.osgi.util.tracker,org.osgi.service.io;version=1.4 The Import-Package header declares the imported packages for this bundle. See Import-Package Header on page 38.

3.2.1.22 Import-Service: org.osgi.service.log.LogServiceDeprecated

3.2.1.23 Require-Bundle: com.acme.chessThe Require-Bundle header specifies the required exports from another bun-dle. Require-Bundle on page 67

OSGi Service Platform Release 4 29-268

Page 38: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Bundles Module Layer Version 1.3

3.2.2 Header Value SyntaxEach Manifest header has its own syntax. In all descriptions, the syntax is defined with [29] W3C EBNF. These following sections define a number of commonly used tokens.

3.2.3 Common Header SyntaxMany Manifest header values share a common syntax. This syntax consists of:

header ::= clause ( ’,’ clause ) *clause ::= path ( ’;’ path ) *

( ’;’ parameter ) * // See 1.4.2

A parameter can be either a directive or an attribute. A directive is an instruc-tion that has some implied semantics for the Framework. An attribute is used for matching and comparison purposes.

3.2.4 VersionVersion specifications are used in several places. A version token has the fol-lowing grammar:

version ::= major( '.' minor ( '.' micro ( '.' qualifier )? )? )?

major ::= number // See 1.4.2minor ::= numbermicro ::= numberqualifier ::= ( alphanum | ’_’ | '-' )+

A version token must not contain any white space. The default value for a version is 0.0 .0 .

3.2.5 Version RangesA version range describes a range of versions using a mathematical interval notation. See [31] Mathematical Convention for Interval Notation.

The syntax of a version range is:

version-range ::= interval | atleastinterval ::= ( '[' | '(' ) floor ',' ceiling ( ']' | ')' )atleast ::= versionfloor ::= versionceiling ::= version

If a version range is specified as a single version, it must be interpreted as the range [vers ion,∞) . The default for a non-specified version range is 0, which maps to [0 .0.0 ,∞) .

Note that the use of a comma in the version range requires it to be enclosed in double quotes. For example:

Import-Package: com.acme.foo;version="[1.23, 2)", com.acme.bar;version="[4.0, 5.0)"

30-268 OSGi Service Platform Release 4

Page 39: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Bundles

In the following table, for each specified range in the left-hand column, a version x is considered to be a member of the range if the predicate in the right-hand column is true.

3.2.6 Filter SyntaxThe OSGi specifications use filter expressions extensively. Filter expressions allow for a concise description of a constraint.

The syntax of a filter string is based upon the string representation of LDAP search filters as defined in [23] A String Representation of LDAP Search Filters. It should be noted that RFC 2254: A String Representation of LDAP Search Filters supersedes RFC 1960, but only adds extensible matching and is not applicable to this OSGi Framework API.

The string representation of an LDAP search filter uses a prefix format and is defined by the following grammar:

filter ::= ’(’ filter-comp ’)’filter-comp ::= and | or | not | operationand ::= ’&’ filter-listor ::= ’|’ filter-listnot ::= ’!’ filterfilter-list ::= filter | filter filter-listoperation ::= simple | present | substringsimple ::= attr filter-type valuefilter-type ::= equal | approx | greater | lessequal ::= ’=’approx ::= ’~=’greater ::= ’>=’less ::= ’<=’present ::= attr ’=*’substring ::= attr ’=’ initial any finalinital ::= () | valueany ::= ’*’ star-valuestar-value ::= () | value ’*’ star-valuefinal ::= () | valuevalue ::= <see text>

att r is a string representing an attribute, or key, in the properties. Attribute names are not case sensitive; that is, cn and CN both refer to the same attribute. att r must not contain the characters '=', '>', '<', '~', '(' or ')'. attr may contain embedded spaces but leading and trailing spaces must be ignored.

value is a string representing the value, or part of one, which will be com-pared against a value in the filtered properties.

Table 2 Examples of version rangesExample Predicate

[1 .2 .3 , 4 .5.6) 1.2 .3 <= x < 4.5 .6

[1 .2 .3 , 4 .5.6] 1.2 .3 <= x <= 4 .5.6

(1.2 .3 , 4.5.6) 1.2 .3 < x < 4 .5.6

(1.2 .3 , 4.5.6] 1.2 .3 < x <= 4.5 .6

1.2 .3 1.2 .3 <= x

OSGi Service Platform Release 4 31-268

Page 40: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Bundles Module Layer Version 1.3

If value must contain one of the characters '*', ’(’ or ')', then these characters should be preceded with the backslash (’\’) character. Spaces are significant in value . Space characters are defined by Character . isWhiteSpace() .

Although both the substr ing and present productions can produce the att r=* construct, this construct is used only to denote a presence filter.

The evaluation of the approximate match (’~= ’) filter type is implementa-tion specific but should at least ignore case and white space differences. Codes such as soundex or other smart closeness comparisons may be used.

Values specified in the filter are compared to values in the properties against which the filter is evaluated. The comparison of these values is not straightforward. Strings compare differently than numbers, and it is also possible for a property to have multiple values. Property keys must always be Str ing objects so that a case insensitive attr can be used to obtain the property value.

The object class of the property's value defines the comparison type. The properties values should be of the following types:

type ::= scalar | primitive | vector | arrayscalar ::= String | Integer | Long | Float

| Double | Byte | Short | Character | Boolean

primitive ::= int | long | float | double | byte | short | char | booleanarray ::= <Array of primitive>

| <Array of scalar>vector ::= Vector of scalar

The following rules apply for comparison:

• String – Use String comparison• Integer, Long, Float, Double, Byte, Short, Character objects and primitives –

Use numerical comparison• Boolean objects – Use equality comparison• Array or Vector elements – Comparison is determined by the object type

of the element

Array and Vector elements may be a mix of scalar types. Array and Vector elements may also be nul l .

If the type of the property value is not one of the above types, and the type has a constructor taking a single Str ing argument, then the Framework must construct an object to compare with the property value by passing value to the single String argument constructor according to the following comparison rules:

• Comparable objects – Comparison through the Comparable interface• Other objects – Equality comparison

If none of the above comparison rules apply, then the result of the compari-son is fa lse .

A filter matches a property with multiple values if it matches at least one of those values.

For example:

32-268 OSGi Service Platform Release 4

Page 41: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Execution Environment

Dictionary dict = new Hashtable();dict.put( "cn", new String[] { "a", "b", "c" } );

The dict will match against a filter with (cn=a) as well as (cn=b) .

3.3 Execution EnvironmentA bundle that is restricted to one or more execution environments must carry a header in its manifest file to indicate this dependency. This header is Bundle-RequiredExecutionEnvironment. The syntax of this header is a list of comma-separated names of execution environments.

Bundle-RequiredExecutionEnvironment ::= ee-name ( ’,’ ee-name )*

ee-name ::= <defined execution environment name>

For example:

Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0, OSGi/Minimum-1.1

If a bundle includes this header in the manifest then the bundle must only use methods with signatures that are contained within a proper subset of all mentioned execution environments. Bundles should list all (known) execu-tion environments on which it can run the bundle.

3.3.1 Naming of Execution EnvironmentsExecution environments require a proper name so that:

• A bundle can require that a Framework provides a certain execution environment before it is installed

• To provide information about which execution environments a Framework provides.

Execution environment names consist of any set of characters except white space characters and the comma character (’ , ’ , or \u002C ). The OSGi Alli-ance has defined a number of execution environments.

The naming scheme further uses J2ME configuration and profile names. There is no clear definition for this naming scheme but similar names are used in different specifications.

The J2ME scheme uses a configuration and a profile name to designate an execution environment. The OSGi Alliance naming combines those two names into a single execution environment name.

There already exist a number of Execution Environments from J2ME that are likely available in Service Platform Servers. The value for the execution environment header must be compatible with these specifications.

A J2ME execution environment name is a combination of a configuration and a profile name. In J2ME, these are two different system properties. These properties are:

microedition.configuration microedition.profiles

OSGi Service Platform Release 4 33-268

Page 42: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Class Loading Architecture Module Layer Version 1.3

For example, Foundation Profile has an execution environment name of CDC-1.0/Foundation-1.0 . The structure of the name obeys the following rules:

ee-name = [ <configuration> ’-’ <version> ’/’ ]<profile> ’-’ <version>

Configuration and profile names are defined by the JCP or OSGi Alliance. If an execution environment does not have a configuration or profile, the pro-file part is the name identifying the execution environment. These guide-lines are not normative.

Table 3 on page 34, contains a number of examples of the most common execution environments.

The org.osg i . framework.executionenvironment property from BundleContext.getProperty(Str ing) must contain a comma-separated list of execution environment names implemented by the Framework. This prop-erty is defined as volatile. A Framework implementation must not cache this information because bundles may change this system property at any time. The purpose of this volatility is testing and possible extension of the execu-tion environments at run-time.

3.4 Class Loading ArchitectureMany bundles can share a single virtual machine (VM). Within this VM, bundles can hide packages and classes from other bundles, as well as share packages with other bundles.

The key mechanism to hide and share packages is the Java class loader that loads classes from a sub-set of the bundle-space using well-defined rules. Each bundle has a single class loader. That class loader forms a class loading delegation network with other bundles as shown in Figure 14.

Table 3 Sample EE namesName Description

CDC-1.0/Foundation-1.0 Equal to J2ME Foundation Profile

OSGi/Minimum-1.1 OSGi EE that is a minimal set that allows the implementation of an OSGi Framework.

JRE-1.1 Java 1.1.x

J2SE-1.2 Java 2 SE 1.2.x

J2SE-1.3 Java 2 SE 1.3.x

J2SE-1.4 Java 2 SE 1.4.x

Personal Java-1.1 Personal Java 1.1

Personal Java-1.2 Personal Java 1.2

CDC-1.0/PersonalBas is-1.0

J2ME Personal Basis Profile

CDC-1.0/Personal Java-1.0 J2ME Personal Java Profile

34-268 OSGi Service Platform Release 4

Page 43: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Class Loading Architecture

Figure 14 Class Loader Delegation model

The class loader can load classes and resources from:

• Boot class path – The boot class path contains the java.* packages and its implementation packages.

• Framework class path – The Framework usually has a separate class loader for the Framework implementation classes as well as key service interface classes.

• Bundle Space – The bundle space consists of the JAR file that is associated with the bundle, plus any additional JAR that are closely tied to the bundle, like fragments, see Fragment Bundles on page 69.

A class space is then all classes reachable from a given bundle’s class loader. Thus, a class space for a given bundle can contain classes from:

• The parent class loader (normally java.* packages from the boot class path)

• Imported packages• Required bundles• The bundle's class path (private packages)• Attached fragments

A class space must be consistent, such that it never contains two classes with the same fully qualified name (to prevent Class Cast Exceptions). However, separate class spaces in an OSGi Platform may contain classes with the same fully qualified name. The modularization layer supports a model where multiple versions of the same class are loaded in the same VM.

Bundleclass loader

Bundleclass loader

Bundleclass loader

Bundleclass loader

exporterimporter

Parent/System class loader

System Bundle class loader

OSGi Service Platform Release 4 35-268

Page 44: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Class Loading Architecture Module Layer Version 1.3

Figure 15 Class Space

The Framework therefore has a number of responsibilities related to class loading. Before a bundle is used, it must resolve the constraints that a set of bundles place on the sharing of packages. Then select the best possibilities to create a wiring. See Resolving Process on page 50 for further information. The runtime aspects are described in Runtime Class Loading on page 51.

3.4.1 ResolvingThe Framework must resolve bundles. Resolving is the process where importers are wired to exporters. Resolving is a process of satisfying con-straints. This process must take place before any code from a bundle can be loaded or executed

A wire is an actual connection between an exporter and an importer, which are both bundles. A wire is associated with a number of constraints that are defined by its importer’s and exporter’s manifest headers. A valid wire is a wire that has satisfied all its constraints. Figure 16 depicts the class structure of the wiring model.

Figure 16 Example class structure of wiring

privatepublic

public

private

public

exported

private

publicBundle A

Bundle B

Bundle C

Class Space for bundle A

Bundle Wire Constraint

Package Instance

imports

exports

1 *

1 *constrained by1 *

1

*for

......

36-268 OSGi Service Platform Release 4

Page 45: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Resolving Metadata

3.5 Resolving MetadataThe following sections define the manifest headers that provide the meta-data for the resolver.

3.5.1 Bundle-ManifestVersionA bundle manifest must express the version of the OSGi manifest header syntax in the Bundle-ManifestVersion header. Bundles exploiting this ver-sion of the Framework specification (or later) must specify this header. The syntax of this header is as follows:

Bundle-ManifestVersion ::= number // See 1.4.2

The Framework version 1.3 bundle manifest version must be’2’. Bundle manifests written to previous specifications’ manifest syntax are taken to have a bundle manifest version of '1', although there is no way to express this in such manifests. Therefore, any other value than ’2’ for this header is invalid unless the Framework explicitly supports such a later version.

OSGi Framework implementations should support bundle manifests with-out a Bundle-ManifestVersion header and assume Framework 1.2 compati-bility at the appropriate places.

Version 2 bundle manifests must specify the bundle symbolic name. They need not specify the bundle version since this has a default value.

3.5.2 Bundle-SymbolicNameThe Bundle-SymbolicName manifest header is a mandatory header. The bundle symbolic name and bundle version allow a bundle to be uniquely identified in the Framework. That is, a bundle with a given symbolic name and version is treated as equal to another bundle with the same symbolic name and version.

The installation of a bundle with a Bundle-SymbolicName and Bundle-Ver-sion identical to an existing bundle must fail.

A bundle gets its unique Bundle-SymbolicName from the developer (The Bundle-Name manifest header provides a human-readable name for a bun-dle and is therefore not replaced by this header).

The Bundle-SymbolicName manifest header must conform to the following syntax:

Bundle-SymbolicName ::= symbolic-name ( ';' parameter ) * // See 1.4.2

The framework must recognize the following directives for the Bundle-Sym-bolicName header:

• s ingleton – Indicates that the bundle can only have a single version resolved. A value of true indicates that the bundle is a singleton bundle. The default value is fa lse . The Framework must resolve at most one bundle when multiple versions of a singleton bundle with the same sym-bolic name are installed. Singleton bundles do not affect the resolution of non-singleton bundles with the same symbolic name.

OSGi Service Platform Release 4 37-268

Page 46: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Resolving Metadata Module Layer Version 1.3

• f ragment-attachment – Defines what fragments are allowed to be attached, see the optional fragments in Fragment Bundles on page 69. The following values are valid for this directive:• always – Fragments can attach at any time while the host is resolved

or during the process of resolving.• never – No fragments are allowed.• resolve-t ime – Fragments must only be attached during resolving.

For example:

Bundle-SymbolicName: com.acme.foo;singleton:=true

3.5.3 Bundle-VersionBundle-Version is an optional header; the default value is 0.0.0 .

Bundle-Version ::= version // See 3.2.4

If the minor or micro version components are not specified, they have a default value of 0 . If the qualifier component is not specified, it has a default value of the empty string ("").

Versions are comparable. Their comparison is done numerically and sequentially on the major , minor , and micro components and lastly using the String class compareTo method for the qual i f ier .

A version is considered equal to another version if the major, minor, micro, and the qualifier components are equal (using Str ing method compareTo).

Example:

Bundle-Version: 22.3.58.build-345678

3.5.4 Import-Package HeaderThe Import-Package header defines the constraints on the imports of shared packages. The syntax of the Import-Package header is:

Import-Package ::= import ( ',' import )*import ::= package-names ( ';' parameter )*package-names ::= package-name

( ';' package-name )* // See 1.4.2

The header allows many packages to be imported. An import definition is the description of a single package for a bundle.

Import package directives are:

• resolution – Indicates that the packages must be resolved if the value is mandatory, which is the default. If mandatory packages cannot be resolved, then the bundle must fail to resolve. A value of optiona l indi-cates that the packages are optional. See Optional Packages on page 43.

The developer can specify arbitrary matching attributes. See Attribute Match-ing on page 47. The following arbitrary matching attributes are predefined:

• version – A version-range to select the exporter's package version. The syntax must follow Version Ranges on page 30. For more information on version selection, see Version Matching on page 42. If this attribute is not specified, it is assumed to be [0.0 .0, ∞) .

38-268 OSGi Service Platform Release 4

Page 47: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Resolving Metadata

• speci f ication-version – This attribute is an alias of the version attribute only to ease migration from earlier versions. If the version attribute is present, the values must be equal.

• bundle-symbol ic-name – The bundle symbolic name of the exporting bundle.

• bundle-vers ion – A version-range to select the bundle version of the exporting bundle. The default value is [0 .0.0 , ∞) . See Version Matching on page 42.

In order to be allowed to import a package (except for packages starting with java.), a bundle must have PackagePermiss ion[<package-name>, IMPORT] . See PackagePermission for more information.

An error aborts an installation or update when:

• A directive or attribute appears multiple times, or• There are multiple import definitions for the same package.

Example of a correct definition:

Import-Package: com.acme.foo;com.acme.bar;version="[1.23,1.24]";resolution:=mandatory

3.5.5 Export-Package The syntax of the Export-Package header is similar to the Import-Package header; only the directives and attributes are different.

Export-Package ::= export ( ’,’ export )*export ::= package-names ( ’;’ parameter )*package-names ::= package-name // See 1.4.2

( ';' package-name )*

The header allows many packages to be exported. An export definition is the description of a single package export for a bundle. Multiple export defini-tions for the same package are allowed for example, when different attributes are needed for different importers.

Export directives are:

• uses – A comma-separated list of package names that are used by the exported package. Note that the use of a comma in the value requires it to be enclosed in double quotes. If this exported package is chosen as an export, then the resolver must ensure that importers of this package wire to the same versions of the package in this list. See Package Constraints on page 44.

• mandatory - A comma-separated list of attribute names. Note that the use of a comma in the value requires it to be enclosed in double quotes. A bundle importing the package must specify the mandatory attributes, with a value that matches, to resolve to the exported package. See Man-datory Attributes on page 47.

• inc lude – A comma-separated list of class names that must be visible to an importer. Note that the use of a comma in the value requires it to be enclosed in double quotes. For class filtering, see Class Filtering on page48.

OSGi Service Platform Release 4 39-268

Page 48: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Resolving Metadata Module Layer Version 1.3

• exc lude -A comma-separated list of class or resource names that must be invisible to an importer. Note that the use of a comma in the value requires it to be enclosed in double quotes. For class/resource filtering, see Class Filtering on page 48.

The following attribute is part of this specification:

• version – The version of the named packages with syntax as defined in Version on page 30. It defines the version of the associated packages. The default value is 0.0.0 .

• speci f ication-version – An alias for the version attribute only to ease migration from earlier versions. If the vers ion attribute is present, the values must be equal.

Additionally, arbitrary matching attributes may be specified. See Attribute Matching on page 47.

The Framework will automatically associate each package export definition with the following attributes:

• bundle-symbol ic-name – The bundle symbolic name of the exporting bundle.

• bundle-vers ion – The bundle version of the exporting bundle.

An installation or update must be aborted when any of the following condi-tions is true:

• a directive or attribute appears multiple times• the bundle-symbolic-name or bundle-vers ion attribute is specified in

the Export-Package header.

An export definition does not imply an automatic import definition. A bun-dle that exports a package and does not import that package will get that package via its bundle class path. Such an exported only package can be used by other bundles, but the exporting bundle does not accept a substitu-tion for this package from another bundle.

In order to export a package, a bundle must have PackagePermission[<package>, EXPORT] .

Example:

Export-Package: com.acme.foo;com.acme.bar;version=1.23

3.5.6 Exporting and Importing a PackageExporting a package does not imply the import of that same package (in Release 3, an export did imply an import). The reason for this separation is that it enables a bundle to provide a package to other bundles without hav-ing to take into account that the exported package could be substituted by the resolver with the same package from another bundle. This is a common case when an application consists of a set of closely intertwined bundles where implementation packages are provided to other bundles.

40-268 OSGi Service Platform Release 4

Page 49: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Constraint Solving

The substitution of packages is crucial for the interoperability of bundles. In Java, bundles can only inter-operate when they use the same class loaders for the same classes. Therefore, two bundles that both export the same pack-age, but do not import it, cannot share objects from that package. This is very important for a collaboration mechanism like the Service Layer. Bun-dles can only use the same service objects if their classes and interfaces come from the same class loaders.

Bundles should import exported packages, allowing the resolver to substi-tute packages that contain interfaces and other shared types. This substitu-tion allows bundles to inter-operate through the service registry and other mechanisms. Additionally, the import should be as unconstrained as possi-ble to allow the resolver maximum flexibility.

3.5.7 Interpretation of Legacy BundlesBundles that are not marked with a Bundle-ManifestVersion that equals 2 or more must treat the headers according the definitions in the Release 3. More specifically, the Framework must map the Release 3 headers to the appropri-ate Release 4 headers:

• Import-Package – An import definition must change the speci f ication-version attribute to the version attribute. An import definition without a specification version needs no replacement since the default version value of 0.0.0 gives the same semantics as Release 3.

• Export-Package – An export definition must change the speci f ication-version attribute to the version attribute. The export definition must be appended with the uses directive. The uses directive must contain all imported and exported packages for the given bundle. Additionally, if there is no import definition for this package, then an import definition for this package with the given version must be added.

• DynamicImport-Package – A dynamic import definition is unmodified.

A bundle manifest which mixes legacy syntax with bundle manifest version 2 syntax is in error and must cause the containing bundle to fail to install.

The speci f ication-version attribute is a deprecated synonym for the version attribute in bundle manifest version 2 headers.

3.6 Constraint SolvingThe OSGi Framework package resolver provides a number of mechanisms to match imports to exports. The following sections describe these mecha-nisms in detail.

3.6.1 Diagrams and SyntaxWires create a graph of nodes. Both the wires as well as nodes (bundles) carry a significant amount of information. In the next sections, the follow-ing conventions are used to explain the many details.

OSGi Service Platform Release 4 41-268

Page 50: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Constraint Solving Module Layer Version 1.3

Bundles are named A , B , C, ... That is, uppercase characters starting from the character A . Packages are named p , q , r , s , t , ... In other words, lower case char-acters starting from p . If a version is important, it is indicated with a dash followed by the version: q-1.0 . The syntax A.p means the package defini-tion (either import or export) of package p by bundle A .

Import definitions are graphically shown by a white box. Export definitions are displayed with a black box. Packages that are not exported or imported are called private packages. They are indicated with diagonal lines.

Bundles are a set of connected boxes. Constraints are written on the wires, which are represented by lines.

Figure 17 Legend of wiring instance diagrams, and example

For example:

A: Import-Package: p; version="[1,2)" Export-Package: q; version=2.2.2; uses:=p

Require-Bundle: CB: Export-Package: p; version=1.5.1C: Export-Package: r

Figure 18 shows the same setup graphically.

Figure 18 Example bundle diagram

3.6.2 Version MatchingVersion constraints are a mechanism whereby an import definition can declare a precise version or a version range for matching an export defini-tion.

export

wire

B bundle name

p-1.2.3

version=[1,2)

importuses

p optional import

p private package

require bundle

q-2.2.2

bundlefragment host

q-2.2.2

p

B

A

version=[1,2)

p-1.5.1

sCr

42-268 OSGi Service Platform Release 4

Page 51: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Constraint Solving

Version ranges encode the assumptions about compatibility. This specifica-tion does not define any compatibility policy; the policy decision is left to the importer that specifies a version range. A version range embeds such a policy.

However, the most common version compatibility policies are:

• major – An incompatible update• minor – A backward compatible update• micro – A change that does not affect the interface: for example, a bug fix

An import definition must specify a version range as the value for its ver-sion attribute, and the exporter must specify a version as the value for its version attribute. Matching is done with the rules for version range matches as described in Version Ranges on page 30.

For example, the following import and export definition resolve correctly because the version range in the import definition matches the version in the export definition:

A: Import-Package: p; version="[1,2)"B: Export-Package: p; version=1.5.1

Figure 19 graphically shows how a constraint can exclude an exporter.

Figure 19 Version Constrained

3.6.3 Optional PackagesA bundle can indicate that it does not require a package to resolve correctly, but it may use the package if it is available. For example, logging is impor-tant, but the absence of a log service should not prevent a bundle from run-ning.

Optional imports can be specified in the following ways:

• Dynamic Imports – The DynamicImport-Package header is intended to look for an exported package when that the package is needed. The key use case for dynamic import is the Class forName method when a bundle does not know in advance the class name it may be requested to load.

• Resolution Directive – The resolution directive on an import definition specifying the value optiona l . A bundle may successfully resolve if a suitable optional package is not present.

The key differences between these two mechanisms are:

• Optional versus Dynamic – An attempt is made to establish a wire for a dynamic import every time there is an attempt to load a class in that

BA

C

version=[1,2)p p-1.5.1

p-2.4.3

OSGi Service Platform Release 4 43-268

Page 52: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Constraint Solving Module Layer Version 1.3

package, whereas the wire for a resolution optional package may only be established when the bundle is resolved.

The resolution directive of the import definition can take the value mandatory or optional .

• mandatory – (Default) Indicates that the package must be wired for the bundle to resolve.

• optional – Indicates that the importing bundle may resolve without the package being wired.

The following example will resolve even though bundle B does not provide the correct version (the package will not be available to the code when bun-dle A is resolved).

A: Import-Package: p;resolution:=optional;

version=1.6B: Export-Package: p;

q; version=1.5.0

Figure 20 Optional import

The implementation of a bundle that uses optional packages must be pre-pared to handle the fact that the packages may not be available: that is, an exception can be thrown when there is a reference to a class from a missing package.

3.6.4 Package ConstraintsClasses can depend on classes in other packages. For example, when they extend classes from another package, or these other classes appear in method signatures. It can therefore be said that a package uses other pack-ages. These inter-package dependencies are modeled with the uses directive on the Export-Package header.

For example, org .osg i .service .http depends on the package javax.servlet because it is used in the API. The export definition of the org .osg i .serv ice .http must therefore contain the uses directive with the javax .servlet package as its value.

Class space consistency can only be ensured if a bundle has only one exporter for each package.

For example, the Http Service implementation requires servlets to extend the javax .servlet .http.HttpServlet base class. If the Http Service bundle would import version 2.4 and the client bundle would import version 2.1 then a class cast is bound to happen. This is depicted in Figure 21.

BA p p-1.5.0

q-1.5.0

version=1..6

44-268 OSGi Service Platform Release 4

Page 53: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Constraint Solving

Figure 21 Uses directive in B, forces A to use javax.servlet from D

If a bundle imports a package from an exporter then the export definition of that package can imply constraints on a number of other packages through the uses directive. The uses directive lists the packages that the exporter depends upon and therefore constrains the resolver for imports. These con-straints ensure that a set of bundles share the same class loader for the same package.

When an importer imports a package with implied constraints, the resolver must wire the import to the exporter implied by the constraint. This exporter may in turn imply additional constraints, and so on. The act of wir-ing a single import of a package to an exporter can therefore imply a large set of constraints. The term implied package constraints refers to the complete set of constraints constructed from recursively traversing the wires. Implied package constraints are not automatic imports; rather, implied package con-straints only constrain how an import definition must be resolved.

For example, in Figure 22, bundle A imports package p . Assume this import definition is wired to bundle B . Due to the uses directive (the ellipse sym-bols indicates the uses directive) this implies a constraint on package q .

Further, assuming that the import for package q is wired to bundle C , then this implies a constraint on the import of package r and s . Continuing, assuming C.s and C.r are wired to bundle D and E respectively. These bun-dles both add package t to the set of implied packages for bundle A.

org.osgi.service.http

javax.servlet.httpB

javax.servlet.http; 2.4 Djavax.servlet.http; 2.1C

p

A org.osgi.service.http

javax.servlet.http

OSGi Service Platform Release 4 45-268

Page 54: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Constraint Solving Module Layer Version 1.3

Figure 22 Implied Packages

To maintain class space consistency, the Framework must ensure that none of its bundle imports conflicts with any of that bundle’s implied packages.

For the example, this means that the Framework must ensure that the import definition of A.t is wired to package D.t . Wiring this import defini-tion to package F .t violates the class space consistency. This violation occurs because bundle A could be confronted with objects with the same class name but from the class loaders of bundle D and F . This would potentially create ClassCastExceptions . Alternatively, if all bundles are wired to F.t , then the problem also goes away.

Another scenario with this case is depicted in Figure 21. Bundle A imports the Http Service classes from bundle B . Bundle B has grouped the org .osg i .serv ice .http and the javax. servlet and bundle A is therefore con-strained to wire javax.servlet to the same exporter as bundle B .

As an example of a situation where the uses directive makes resolving impossible consider the following setup that is correctly resolved:

A: Import-Package: q; version="[1.0,1.0]" Export-Package: p; uses:="q,r"B: Export-Package: q; version=1.0C: Export-Package: q; version=2.0

These specific constraints can be resolved because the import A.q can be wired to the export B.q but not C.q due to the version constraint.

Adding a bundle D will now not be possible:

D: Import-Package: p, q; version=2.0

Package D.p must be wired to package A.p because bundle A is the only exporter. However, this implies the use of package q due the uses directive in the package A.q import. Package A.q is wired to B.q-1.0 . However, import package D.q requires version 2.0 and can therefore not be resolved without violating the class space constraint.

This scenario is depicted in Figure 23.

p

q

p

t

q

r

s

s

t

r

t

t

t

A B

C

D EF

46-268 OSGi Service Platform Release 4

Page 55: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Constraint Solving

Figure 23 Uses directive and resolving

3.6.5 Attribute MatchingAttribute matching is a generic mechanism to allow the importer and exporter to influence the matching process in a declarative way. In order for an import definition to be resolved to an export definition, the values of the attributes specified by the import definition must match the values of the attributes of the export definition. By default, a match is not prevented if the export definition contains attributes that do not occur in the import defini-tion. The mandatory directive in the export definition can reverse this by listing all attributes that the Framework must match in the import defini-tion. Any information specified in the DynamicImport-Package is ignored during the resolve phase.

For example, the following statements will match.

A: Import-Package: com.acme.foo;company=ACMEB: Export-Package: com.acme.foo; company="ACME"; security=false

Attribute values are compared string wise except for the version and bun-dle-version attributes which use version range comparisons. Leading and trailing white space in attribute values must be ignored.

3.6.6 Mandatory AttributesThere are two types of attributes: mandatory and optional. Mandatory attributes must be specified in the import definition to match. Optional attributes are ignored when they are not referenced by the importer. Attributes are optional by default.

The exporter can specify mandatory attributes with the mandatory direc-tive in the export definition. This directive contains a comma-separated list of attribute names that must be specified by the importer to match.

For example, the following import definition must not match the export definition because securi ty is a mandatory attribute:

A: Import-Package: com.acme.foo;company=ACME

B: Export-Package: com.acme.foo; company="ACME"; security=false; mandatory:=security

BA

p

q-1.0q

Crq-2.0

p

q

D

version=1.0

version=2

OSGi Service Platform Release 4 47-268

Page 56: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Constraint Solving Module Layer Version 1.3

3.6.7 Class FilteringAn exporter can limit the visibility of the classes in a package with the include and exclude directives on the export definition. The value of each of these directives is a comma-separated list of class names. Note that the use of a comma in the value requires it to be enclosed in double quotes.

Class names must not include their package name and do not end with .c lass . That is, the class com.acme.foo.Daffy is named Daffy in either list. The class name can include multiple wildcards (’*’).

The default for the include directive is’*’ (wildcard matching all names), and for the exclude directive, so that no classes or resources are excluded, an empty list that matches no names. If inc lude or exc lude directive are speci-fied, the corresponding default is overridden.

A class is only visible if it is:

• Matched with an entry in the included list, and• Not matched with an entry in the exc luded list.

In all other cases, loading or finding fails, and a Class Not Found Exception is thrown for a class load. The ordering of include and exc lude is not signifi-cant.

The following example shows an export statement, and a list of files with their visibility status.

Export-Package: com.acme.foo; include:="Qux*,BarImpl"; exclude:=QuxImpl

com/acme/foo QuxFoo visible QuxBar visible QuxImpl excluded BarImpl visible

Care must be taken when using filters. For example, a new version of a mod-ule that is intended to be backward compatible with an earlier version should not filter out classes or resources that were not filtered out by the earlier version. In addition, when modularizing existing code, filtering out classes or resources from an exported package may break users of the pack-age.

For example, packages defined by standard bodies often require an imple-mentation class in the standardized package to have package access to the specification classes.

package org.acme.open;public class Specified {

static Specified implementation;public void foo() { implementation.foo(); }

}

package org.acme.open;public class Implementation {

public void initialize(Specified implementation) {Specified.implementation = implementation;

48-268 OSGi Service Platform Release 4

Page 57: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Constraint Solving

}}

The Implementat ion class must not be available to external bundles because it allows the implementation to be set. By excluding the Implementation class, only the exporting bundle can see this class. The export definition for this header could look like:

Export-Package: org.acme.open; exclude:=Implementation

3.6.8 Provider SelectionProvider selection allows the importer to select which bundles can be con-sidered as exporters. Provider selection is used when there is no specifica-tion contract between the importer and the exporter. The importer tightly couples itself to a specific exporter, typically the bundle that was used for testing. To make the wiring less brittle, the importer can optionally specify a range of bundle versions that will match.

An importer can select an exporter with the import attributes bundle-symbol ic-name and bundle-vers ion . The Framework automatically pro-vides these attributes for each export definition. These attributes must not be specified in an export definition.

The export definition bundle-symbol ic-name attribute will contain the bundle symbolic name as specified in the Bundle-Symbol icName header without any parameters. The export definition bundle-version attribute is set to the value of the Bundle-Vers ion header or its default of 0.0.0 when absent.

The bundle-symbol ic-name is matched as an attribute. The bundle-vers ion attribute is matched using the version range rules as defined in Version Ranges on page 30. The import definition must be a version range and the export definition is a version.

For example, the following definitions will match:

A: Bundle-SymbolicName: A Import-Package: com.acme.foo; bundle-symbolic-name=B; bundle-version="[1.41,2.0.0)"

B: Bundle-SymbolicName: B Bundle-Version: 1.41 Export-Package: com.acme.foo

The following statements will not match because B does not specify a ver-sion and thus defaults to 0.0.0:

A: Bundle-SymbolicName: A Import-Package: com.acme.foo; bundle-symbolic-name=B; bundle-version="[1.41,2.0.0)"

B: Bundle-SymbolicName: B Export-Package: com.acme.foo;version=1.42

OSGi Service Platform Release 4 49-268

Page 58: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Resolving Process Module Layer Version 1.3

Selecting an exporter by symbolic name can result in brittleness because of hard coupling of the package to the bundle. For example, if the exporter eventually needs to be refactored into multiple separate bundles, all import-ers must be changed. Other arbitrary matching attributes do not have this disadvantage as they can be specified independently of the exporting bun-dle.

The brittleness problem of the bundle symbolic name in bundle refactoring can be partly overcome by writing a façade bundle using the same bundle symbolic name as the original bundle.

3.7 Resolving ProcessResolving is the process that creates a wiring between bundles. Constraints on the wires are statically defined by:

• Import and export packages (the DynamicImport-Package header is ignored in this phase)

• Required bundles, which import all exported packages from a bundle as defined in Requiring Bundles on page 66.

• Fragments, which provide their contents and definitions to the host as defined in Fragment Bundles on page 69

Before a bundle is resolved, all its Fragments must be attached. The resolv-ing process is then a constraint-solving algorithm that can be described in terms of requirements on wiring relations. The resolving process is an itera-tive process that searches through the solution space.

If a module has both import and export definitions for the same package, then the Framework needs to decide which to choose.

It must first try to resolve the overlapping import definition. The following outcomes are possible:

• External – If this resolves to an export statement in another bundle, then the overlapping export definition in this bundle is discarded.

• Internal – If it is resolved to an export statement in this module, then the overlapping import definition in this module is discarded.

• Unresolved – There is no matching export definition. This is however a developer error because it means the overlapping export definition of the bundle is not compatible with the overlapping import definition.

A bundle can be resolved if the following conditions are met:

• All its mandatory imports are wired• All its mandatory required bundles are available and their exports wired

A wire is only created when the following conditions are met:

• The importer’s version range matches the exporter’s version. See Version Matching on page 42.

• The importer specifies all mandatory attributes from the exporter. See Mandatory Attributes on page 47.

• All the importer’s attributes match the attributes of the corresponding exporter. See Attribute Matching on page 47

• Implied packages referring to the same package as the wire are wired to the same exporter. See Package Constraints on page 44.

50-268 OSGi Service Platform Release 4

Page 59: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Runtime Class Loading

• The wire is connected to a valid exporter.

The following list defines the preferences, if multiple choices are possible, in order of decreasing priority:

• A resolved exporter must be preferred over an unresolved exporter.• An exporter with a higher version is preferred over an exporter with a

lower version.• An exporter with a lower bundle ID is preferred over a bundle with a

higher ID.

3.8 Runtime Class LoadingEach bundle installed in the Framework must not have an associated class loader until after it is resolved. After a bundle is resolved, the Framework must create one class loader for each bundle that is not a fragment. The framework may delay creation of the class loader until it is actually needed.

One class loader per bundle allows all resources within a bundle to have package level access to all other resources in the bundle within the same package. This class loader provides each bundle with its own name space, to avoid name conflicts, and allows resource sharing with other bundles.

This class loader must use the wiring as calculated in the resolving process to find the appropriate exporters. If a class is not found in the imports, addi-tional headers in the manifest can control the searching of classes and resources in additional places.

The following sections define the factors that influence the runtime class loading and then define the exact search order the Framework must follow when a class or resource is loaded.

3.8.1 Bundle Class PathIntra bundle class path dependencies are declared in the Bundle-Classpath manifest header. This declaration allows a bundle to declare its embedded class path using one or more JAR files or directories that are contained in the bundle’s JAR file.

The Bundle-Classpath manifest header is a list of comma-separated file names. A file name can be either:

• The dot (’ . ’ \u002E), representing the bundle’s JAR file itself, is the default value if no Bundle-Classpath is specified.

• A path to a JAR file contained in the bundle’s JAR file. • A path to a directory contained in the bundle’s JAR file.

The Bundle-Classpath manifest header must conform to the following syn-tax:

Bundle-Classpath::= entry ( ’,’ entry )*entry ::= target ( ’;’ target )*

( ’;’ parameter ) *target ::= path | ’.’ // See 1.4.2

The Framework must ignore any unrecognized parameters.

OSGi Service Platform Release 4 51-268

Page 60: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Runtime Class Loading Module Layer Version 1.3

The Framework must ignore a target in the Bundle-Classpath header if the target (directory or JAR file) cannot be located when it is needed, which can happen at any time after the bundle is resolved. However, in this case the Framework should publish a Framework Event of type INFO with an appro-priate message for each entry that cannot be located.

When locating a class path entry in a bundle, the Framework must attempt to locate the class path entry relative to the root of the bundle’s JAR. If a class path entry cannot be located in the bundle, then the Framework must attempt to locate the class path entry in each of the attached fragment bun-dles. The attached fragment bundles are searched in ascending bundle ID order. This allows a fragment to supply entries that are inserted into the host's Bundle-Classpath

The following example illustrates this:

A: Bundle-SymbolicName: A Bundle-Classpath: required.jar,optional.jar,default.jar content ... required.jar default.jarB: Bundle-SymbolicName: B Bundle-Classpath: fragment.jar Fragment-Host: A content ... optional.jar fragment.jar

In this example, bundle A has a Bundle-Classpath header with three entries (required.jar, optional.jar, and default.jar). The required.jar class path entry may contain the classes and resources that must be present for the bundle to function. The optional.jar class path entry may contain classes and resources that the bundle will use if present.

The default.jar class path entry may contain classes and resources that the bundle will use if the optional.jar is not available, but the classes and resources from default.jar can be overridden by classes and resources in the optional.jar (from the fragment) class path entries. Bundle A has only the required.jar and default.jar entries packaged with it. This allows a fragment bundle B to be installed that can supply the optional.jar for bundle A.

The fragment bundle B has a Bundle-Classpath with one entry (frag-ment.jar). When bundle A is resolved and the fragment bundle B is attached then the bundle class path for the bundle A is:

required.jar, optional.jar, default.jar, fragment.jar

3.8.2 Dynamic Import PackageDynamic imports are matched to export definitions (to form package wir-ings) during class loading, and therefore do not affect module resolution. Dynamic imports apply only to packages for which no wire has been estab-lished and no definition could be found in any other way. Dynamic import is used as last resort.

DynamicImport-Package ::= dynamic-description ( ',' dynamic-description )*

52-268 OSGi Service Platform Release 4

Page 61: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Runtime Class Loading

dynamic-description::= wildcard-names ( ';' parameter )*wildcard-names ::= wildcard-name ( ';' wildcard-name )*wildcard-name ::= package-name

| ( package-name '.*' ) // See 1.4.2| '*'

No directives are architected by the Framework for DynamicImport-Pack-age. Arbitrary matching attributes may be specified. The following arbitrary matching attributes are architected by the Framework:

• version -- A version range to select the version of an export definition. The default value is 0.0.0 .

• bundle-symbol ic-name – The bundle symbolic name of the exporting bundle.

• bundle-vers ion – a version range to select the bundle version of the exporting bundle. The default value is 0.0.0 .

Packages may be named explicitly or by using wild-carded expressions such as org.foo.* and * . The wildcard can stand for any suffix, including multiple sub-packages.

Dynamic imports must be searched in the order in which they are specified. The order is particularly important when package names with wildcards are used. The order will then determine the order in which matching occurs. This means that the more specific package specifications should appear before the broader specifications. For example, the following DynamicIm-port-Package header indicates a preference for packages supplied by ACME:

DynamicImport-Package: *;vendor=acme, *

If multiple packages need to be dynamically imported with identical param-eters, the syntax permits a list of packages, separated by semicolons, to be specified before the parameters.

During class loading, the package of the class being loaded is compared against the specified list of (possibly wild-carded) package names. Each matching package name is used in turn to attempt to wire to an export using the same rules as Import-Package. If a wiring attempt is successful (taking any uses constraints into account), the search is forwarded to the exporter’s class loader where class loading continues. The wiring must not subsequently be modified, even if the class cannot be loaded. This implies that once a package is dynamically resolved, subsequent attempts to load classes or resources from that package are treated as normal imports.

In order for a DynamicImport-Package to be resolved to an export state-ment, all attributes of the dynamic import definition must match the attributes of the export statement. All mandatory arbitrary attributes (as specified by the exporter, see Mandatory Attributes on page 47) must be spec-ified in the dynamic import definition and match.

Once a wire is established, any uses constraints from the exporter must be obeyed for further dynamic imports.

Dynamic imports are very similar to optional packages, see Optional Pack-ages on page 43, but differ in the fact that they are handled after the bundle is resolved.

OSGi Service Platform Release 4 53-268

Page 62: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Runtime Class Loading Module Layer Version 1.3

3.8.3 Parent DelegationThe Framework must always delegate any package that starts with java. to the parent class loader.

Certain Java virtual machines, also SUN’s VMs, appear to make the errone-ous assumption that the delegation to the parent class loader always occurs. This implicit assumption of strictly hierarchical class loader delegation can result in NoClassDefFoundErrors . This happens if the virtual machine implementation expects to find its own implementation classes from any arbitrary class loader, requiring that packages loaded from the boot class loader not be restricted to only the java.* packages.

Other packages that must be loaded from the boot class loader can therefore be specified with the System property:

org.osgi.framework.bootdelegation

This property must contain a list with the following format:

org.osgi.framework.bootdelegation ::= boot-description ( ',' boot-description )*

boot-description::= package-name // See 1.4.2| ( package-name '.*' ) | '*'

The .* wildcard means deep matching. Packages that match this list must be loaded from the parent class loader. The java.* prefix is always implied; it does not have to be specified.

The single wildcard means that the Framework must always delegate to the parent class loader first, which is the same as the Release 3 behavior. For example, when running on a SUN JVM, it may be necessary to specify a value like:

org.osgi.framework.bootdelegation=sun.*,com.sun.*

With such a property value, the Framework must delegate all java .* , sun.* , and com.sun.* packages to the parent class loader.

3.8.4 Overall Search OrderFrameworks must adhere to the following rules for class or resource load-ing. When a bundle’s class loader is requested to load a class or find a resource, the search must be performed in the following order:

1 If the class or resource is in a java.* package, the request is delegated to the parent class loader; otherwise, the search continues with the next step. If the request is delegated to the parent class loader and the class or resource is not found, then the search terminates and the request fails.

2 If the class or resource is from a package included in the boot delegation list (org.osg i. f ramework.bootdelegat ion), then the request is delegated to the parent class loader. If the class or resource is found there, the search ends.

3 If the class or resource is in a package that is imported using Import-Package or was imported dynamically in a previous load, then the request is delegated to the exporting bundle’s class loader; otherwise the search continues with the next step. If the request is delegated to an

54-268 OSGi Service Platform Release 4

Page 63: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Runtime Class Loading

exporting class loader and the class or resource is not found, then the search terminates and the request fails.

4 If the class or resource is in a package that is imported from one or more other bundles using Require-Bundle, the request is delegated to the class loaders of the other bundles, in the order in which they are specified in this bundle’s manifest. If the class or resource is not found, then the search continues with the next step.

5 The bundle’s own internal bundle class path is searched. If the class or resource is not found, then the search continues with the next step.

6 Each attached fragment’s internal bundle class path is searched. The frag-ments are searched in ascending bundle ID order. If the class or resource is not found, then the search continues with the next step.

7 If the class or resource is in a package that is exported by the bundle or the package is imported by the bundle (using Import-Package or Require-Bundle), then the search ends and the class or resource is not found.

8 Otherwise, if the class or resource is in a package that is imported using DynamicImport-Package, then a dynamic import of the package is now attempted. An exporter must conform to any implied package con-straints. If an appropriate exporter is found, a wire is established so that future loads of the package are handled in Step 3. If a dynamic wire is not established, then the request fails.

9 If the dynamic import of the package is established, the request is dele-gated to the exporting bundle’s class loader. If the request is delegated to an exporting class loader and the class or resource is not found, then the search terminates and the request fails.

When delegating to another bundle class loader, the delegated request enters this algorithm at Step 3.

The following non-normative flow chart illustrates the search order described above:

OSGi Service Platform Release 4 55-268

Page 64: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Runtime Class Loading Module Layer Version 1.3

Figure 24 Flow chart for class loading (non-normative)

java.*?Delegate toparent class loader

yes

imported?Delegate towire’s exporter

yes

no

dynamic

no

import?

Search Requiredbundles found?

Search bundleclass path

yes

no

found? yes

found?

no

yes

found?

no

yes

no

Start

Failure

Success

Search fragmentsbundle class path

found?

no

yes

no

Delegate towire’s exporter found yes

no

bootdelegation?

Delegate toparent class loader

yes found? yes

no

1

2

3

4

5

6

8

9

no

packageexported?

7 yes

56-268 OSGi Service Platform Release 4

Page 65: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Runtime Class Loading

3.8.5 Parent Class LoaderThe set of implicitly imported packages are all java.* packages, since these packages are required by the Java runtime, and using multiple versions at the same time is not easy. For example, all objects must extend the same Object class.

A bundle must not declare imports or exports for java.* packages; doing so is an error and any such bundle must fail to install. All other packages avail-able through the parent class loader must be hidden from executing bun-dles.

However, the Framework must explicitly export relevant packages from the parent class loader. The system property

org .osg i. framework.system.packages

contains the export packages descriptions for the system bundle. This prop-erty employs the standard Export-Package manifest header syntax:

org.osgi.framework.system.packages ::= package-description ( ',' package-description )*

Some classes on the boot class path assume that they can use any class loader to load other classes on the boot class path, which is not true for a bundle class loader. Framework implementations should attempt to load these classes from the boot class path.

The system bundle (bundle ID zero) is used to export non-java.* packages from the parent class loader. Export definitions from the system bundle are treated like normal exports, meaning that they can have version numbers, and are used to resolve import definitions as part of the normal bundle resolving process. Other bundles may provide alternative implementations of the same packages.

The set of export definitions for the parent class loader can either be set by this property or calculated by the Framework. The export definitions must have the implementation specific bundle symbolic name and version value of the system bundle.

Exposing packages from the parent class loader in this fashion must also take into account any uses directives of the underlying packages. For exam-ple, the definition of javax .crypto.spec must declare its usage of javax .crypto. interfaces and javax .crypto .

3.8.6 Resource LoadingA resource in a bundle can be accessed through the class loader of that bun-dle but it can also be accessed with the getResource, getEntry or f indEntr ies methods. All these methods return a URL object or an Enumeration object of URL objects. The URLs are called bundle entry URLs. The schemes for the URLs returned by these methods can differ and are implementation depen-dent.

Bundle entry URLs are normally created by the Framework, however, in cer-tain cases bundles need to manipulate the URL to find related resources. The Framework is therefore required to ensure that:

OSGi Service Platform Release 4 57-268

Page 66: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Runtime Class Loading Module Layer Version 1.3

• Bundle entry URLs must be hierarchical (See [32] Uniform Resource Identi-fiers URI: Generic Syntax)

• Usable as a context for constructing another URL.• The java.net.URLStreamHandler class used for a bundle entry URL must

be available to the java.net .URL class to setup a URL that uses the pro-tocol scheme defined by the Framework.

• The getPath method for a bundle entry URL must return an absolute path (a path that starts with '/') to a resource or entry in a bundle. For example, the URL returned from getEntry("myimages/test .gi f ") must have a path of /myimages/test .g i f .

For example, a class can take a URL to an index .html bundle resource and map URLs in this resource to other files in the same JAR directory.

public class BundleResource implements HttpContext {URL root; // to index.html in bundleURL getResource( String resource ) {

return new URL( root, resource );}...

}

3.8.7 Bundle CyclesMultiple required bundles can export the same package. Bundles which export the same package involved in a require bundle cycle can lead to lookup cycles when searching for classes and resources from the package. Consider the following definitions:

A: Require-Bundle: B, CC: Require-Bundle: D

These definitions are depicted in Figure 25.

Figure 25 Depth First search with Require Bundle

Each of the bundles exports the package p . In this example, bundle A requires bundle B , and bundle C requires bundle D . When bundle A loads a class or resource from package p , then the required bundle search order is the following: B , D , C , A . This is a depth first search order. The depth first search order can introduce endless search cycles if the dependency graph has a cycle in it.

A

B C

D

p

p p

p

58-268 OSGi Service Platform Release 4

Page 67: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Loading Native Code Libraries

Using the previous setup, a cycle can be introduced if bundle D requires bundle A as depicted in Figure 26.

D: Require-Bundle: A

Figure 26 Cycles

When the class loader for bundle A loads a class or resource from package p then the bundle search order would be the following: B, B, B,... if cycles were not taken into account.

Since a cycle was introduced each time bundle D is reached the search will recurs back to A and start over. The framework must prevent such depen-dency cycles from causing endless recursive lookups.

To avoid endless looping, the Framework must mark each bundle upon first visiting it and not explore the required bundles of a previously visited bun-dle. Using the visited pattern on the dependency graph above will result in the following bundle search order: B , D , C , A .

3.8.8 Code Executed Before StartedPackages exported from a bundle are exposed to other bundles as soon as the bundle has been resolved. This condition could mean that another bundle could call methods in an exported package before the bundle exporting the package is started.

3.9 Loading Native Code LibrariesWhen a class loaded by a bundle's class loader attempts to load a native library, by calling System.loadLibrary , the f indLibrary method of the bun-dle’s class loader must be called to return the file path name in which the Framework has made the requested native library available. The bundle's class loader must attempt to find the native library by examining the selected native code clauses, if any, of the bundle associated with the class loader and each attached fragment. Fragments are examined in ascending bundle ID order. If the library is not referenced in any of the selected native code clauses then nul l must be returned which allows the parent class loader to search for the native library.

The bundle must have the required RuntimePermiss ion [loadLibrary.<

l ib ra ry name>] in order to load native code in the OSGi Service Platform.

A

B C

D

p

p p

p

OSGi Service Platform Release 4 59-268

Page 68: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Loading Native Code Libraries Module Layer Version 1.3

The Bundle-NativeCode manifest header must conform to the following syntax:

Bundle-NativeCode ::= nativecode ( ',' nativecode )* ( ’,’ optional) ?

nativecode ::= path ( ';' path )* // See 1.4.2( ';' parameter )+

optional ::= ’*’

When locating a path in a bundle the Framework must attempt to locate the path relative to the root of the bundle that contains the corresponding native code clause in its manifest header.

The following attributes are architected:

• osname – Name of the operating system. The value of this attribute must be the name of the operating system upon which the native libraries run. A number of canonical names are defined in Environment Properties on page 90.

• osversion – The operating system version. The value of this attribute must be a version range as defined in Version Ranges on page 30.

• processor – The processor architecture. The value of this attribute must be the name of the processor architecture upon which the native libraries run. see Environment Properties on page 90.

• language – The ISO code for a language. The value of this attribute must be the name of the language for which the native libraries have been localized.

• se lect ion-f i l ter – A selection filter. The value of this attribute must be a filter expression that indicates if the native code clause should be selected or not.

The following is a typical example of a native code declaration in a bundle's manifest:

Bundle-NativeCode: lib/http.dll ; lib/zlib.dll ;osname = Windows95 ;osname = Windows98 ;osname = WindowsNT ;processor = x86 ;selection-filter=

"(org.osgi.framework.windowing.system=win32)";language = en ;language = se ,

lib/solaris/libhttp.so ;osname = Solaris ;osname = SunOS ;processor = sparc,

lib/linux/libhttp.so ;osname = Linux ;processor = mips;selection-filter

= "(org.osgi.framework.windowing.system = gtk)"

If multiple native code libraries need to be installed on one platform, they must all be specified in the same clause for that platform.

60-268 OSGi Service Platform Release 4

Page 69: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Loading Native Code Libraries

If a Bundle-NativeCode clause contains duplicate parameter entries, the cor-responding values must be OR 'ed together. This feature must be carefully used because the result is not always obvious. This is highlighted by the fol-lowing example:

// The effect of this header has probably // not the intended effect!Bundle-NativeCode: lib/http.DLL ;

osname = Windows95 ;osversion = 3.1 ;osname = WindowsXP ;osversion = 5.1 ;processor = x86

The above example implies that the native library will load on Windows XP 3.1 and later, which was probably not intended. The single clause should be split in two clauses:

Bundle-NativeCode: lib/http.DLL ;osname = Windows95 ;osversion = 3.1;processor = x86,

lib/http.DLL ;osname = WindowsXP ;osversion = 5.1;processor = x86

If the optional’*’ is specified at the end of the Bundle-NativeCode manifest header, a bundle installation error will not occur if the Bundle-NativeCode header has no matching clauses.

The following is a typical example of a native code declaration in a bundle's manifest with an optional clause:

Bundle-NativeCode: lib/win32/winxp/optimized.dll ;lib/win32/native.dll ;osname = WindowsXP ;processor = x86 ,

lib/win32/native.dll ;osname = Windows95 ;osname = Windows98 ;osname = WindowsNT ;osname = Windows2000;processor = x86 ,*

3.9.1 Native Code AlgorithmIn the description of this algorithm, [x] represents the value of the Frame-work property x and ~= represents the match operation. The match opera-tion is a case insensitive comparison.

Certain properties can be aliased. In those cases, the manifest header should contain the generic name for that property but the Framework should attempt to include aliases when it matches. (See Environment Properties on page 90). If a property is not an alias, or has the wrong value, the Operator

OSGi Service Platform Release 4 61-268

Page 70: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Loading Native Code Libraries Module Layer Version 1.3

should set the appropriate system property to the generic name or to a valid value because Java System properties with this name override the Frame-work construction of these properties. For example, if the operating system returns version 2.4.2-kwt , the Operator should set the system property org.osgi.framework.os.version to 2.4.2.

The Framework must select the native code clause using the following algo-rithm:

1 Only select the native code clauses for which the following expressions all evaluate to true.• osname ~= [org .osg i . f ramework.os .name]• processor ~= [org .osgi . f ramework.processor]• osvers ion range includes [org .osgi . f ramework.os.vers ion] or

osvers ion is not specified• language ~= [org .osg i. framework. language] or language is not spec-

ified• se lection-f i l ter evaluates to t rue when using the values of the system

properties or se lection-fi l ter is not specified2 If no native clauses were selected in step 1, this algorithm is terminated

and a BundleException is thrown if the optional clause is not present.3 The selected clauses are now sorted in the following priority order:

• osvers ion : floor of the osversion range in descending order, osvers ion not specified

• language : language specified, language not specified• Position in the Bundle-NativeCode manifest header: lexical left to

right.4 The first clause of the sorted clauses from step 3 must be used as the

selected native code clause.

If a native code library in a selected native code clause cannot be found within the bundle then the bundle installation must fail with a Bundle Exception. This is true even if the optional clause is specified.

If a selection filter is evaluated and its syntax is invalid, then the bundle installation must fail with a Bundle Exception. If a selection filter is not evaluated (it may be in a native code clause where the osname or processor does not match), then the invalid filter must not cause the bundle installa-tion to fail. This is also true even if the optional clause is specified.

Designing a bundle native code header can become quickly complicated when different operating systems, libraries, and languages are used. The best practice for designing the header is to place all parameters in a table. Every targeted environment is then a row in that table. See Table 4 for an example.

Table 4 Native code tableLibraries

osna

me

osve

rsio

n

proc

esso

r

lang

uage

filte

r

nativecodewin32.dll, delta.dll win32 x86 en

62-268 OSGi Service Platform Release 4

Page 71: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Loading Native Code Libraries

The previous table makes it easier to detect missing combinations. This table is then mapped to the Bundle-NativeCode header in the following table.

Bundle-NativeCode:nativecodewin32.dll;delta.dll;osname=win32;processor=x86;language=en,

nativecodegtk.so;osname=linux;processor=x86;language=en;selection-filter=

"(org.osgi.framework.windowing.system = gtk)",nativecodeqt.so;

osname=linux;processor=x86;language=en;selection-filter =

"(org.osgi.framework.windowing.system = qt)"

3.9.2 Considerations Using Native LibrariesThere are some restrictions on loading native libraries due to the nature of class loaders. In order to preserve name space separation in class loaders, only one class loader can load a native library as specified by an absolute path. Loading of a native library file by multiple class loaders (from multiple bundles, for example) will result in a linkage error.

A native library is unloaded only when the class loader that loaded it has been garbage collected.

When a bundle is uninstalled or updated, any native libraries loaded by the bundle remain in memory until the bundle's class loader is garbage col-lected. The garbage collection will not happen until all references to objects in the bundle have been garbage collected, and all bundles importing pack-ages from the updated or uninstalled bundle are refreshed. This implies that native libraries loaded from the system class loader always remain in mem-ory because the system class loader is never garbage collected.

nativecodegtk.so l inux x86 en (org .osgi . f ramework.windowing.systems=gtk)

nativecodeqt.so l inux x86 en (org .osgi . f ramework.windowing.system=qt)

Table 4 Native code tableLibraries

osna

me

osve

rsio

n

proc

esso

r

lang

uage

filte

r

OSGi Service Platform Release 4 63-268

Page 72: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Localization Module Layer Version 1.3

3.10 LocalizationA bundle contains a significant amount of information that is human-read-able. Some of this information may require different translations depending on the user's language, country, and any special variant preferences, a.k.a. the locale. This section describes how a bundle can provide common transla-tions for the manifest and other configuration resources depending on a locale.

Bundle localization entries share a common base name. To find a potential localization entry, an underscore (’_ ’ \u005F) is added plus a number of suf-fixes, separated by another underscore, and finally appended with the suffix .propert ies . The suffixes are defined in java.uti l .Loca le . The order for the suffixes this must be:

• language• country• variant

For example, the following files provide manifest translations for English, Dutch (Belgium and the Netherlands) and Swedish.

OSGI-INF/l10n/bundle_en.propertiesOSGI-INF/l10n/bundle_nl_BE.propertiesOSGI-INF/l10n/bundle_nl_NL.propertiesOSGI-INF/l10n/bundle_sv.properties

The Framework searches for localization entries by appending suffixes to the localization base name according to a specified locale and finally appending the .p roperties suffix. If a translation is not found, the locale must be made more generic by first removing the variant, then the country and finally the language until an entry is found that contains a valid transla-tion. For example, looking up a translation for the locale en_GB_welsh will search in the following order:

OSGI-INF/l10n/bundle_en_GB_welsh.propertiesOSGI-INF/l10n/bundle_en_GB.propertiesOSGI-INF/l10n/bundle_en.propertiesOSGI-INF/l10n/bundle.properties

This allows localization files for more specific locales to override localiza-tions from less specific localization files.

3.10.1 Finding Localization EntriesLocalization entries can be contained in the bundle or delivered in frag-ments. The Framework must therefore first look in the bundle and then in its attached fragments. Fragment bundles must delegate the search for a localization entry to their host bundle with the lowest bundle ID.

The bundle's class loader is not used to search for localization entries. Only the contents of the bundle and its attached fragments are searched. The bun-dle will still be searched for localization entries even if dot (' . ') is not in the bundle class path.

64-268 OSGi Service Platform Release 4

Page 73: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Bundle Validity

3.10.2 Manifest LocalizationLocalized values are stored in property resources within the bundle. The default base name of the bundle localization property files is OSGI-INF/l10n/bundle . The Bundle-Localization manifest header may optionally define another base name for the localization files. This location is relative to the root of the bundle and bundle fragments.

A localization entry contains key/value entries for localized information. All headers in a bundle's manifest can be localized. However, the Frame-work must always use the non-localized versions of headers that have Framework semantics.

A localization key can be specified as the value of a bundle's manifest header using the following syntax:

header-value ::= ’%’texttext ::= < any value which is both a valid manifest header value and a valid property key name >

For example, consider the following bundle manifest entries:

Bundle-Name: %acme bundleBundle-Vendor: %acme corporationBundle-Description: %acme descriptionBundle-Activator: com.acme.bundle.ActivatorAcme-Defined-Header: %acme special header

user-defined headers can also be localized. Spaces in the localization keys are explicitly allowed.

The previous example manifest entries could be localized by the following entries in the manifest localization entry OSGI-INF/l10n/bundle.properties.

# bundle.propertiesacme bundle=The ACME Bundleacme corporation=The ACME Corporationacme description=The ACME Bundle provides all of the ACME \ servicesacme special header=user-defined Acme Data

The above manifest entries could also have French localizations in the man-ifest localization entry OSGI-INF/l10n/bundle_fr_FR.properties.

3.11 Bundle ValidityIf the Bundle-ManifestVersion is not specified, then the bundle manifest version defaults to 1, and certain Release 4 syntax, such as a new manifest header, is ignored rather than causing an error. Release 3 bundles must be treated according to the R3 specification.

The following (non-exhaustive) list of errors causes a bundle to fail to install:

• Bundle-RequireExecutionEnvironment header does not match the available execution environments.

• Missing Bundle-SymbolicName.

OSGi Service Platform Release 4 65-268

Page 74: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Optional Module Layer Version 1.3

• Duplicate attribute or duplicate directive.• Multiple imports of a given package.• Export or import of java.* .• Export-Package with a mandatory attribute that is not defined.• Installing a bundle that has the same symbolic name and version as an

already installed bundle.• Updating a bundle to a bundle that has the same symbolic name and

version as another installed bundle.• Any syntactic error (for example, improperly formatted version or

bundle symbolic name, unrecognized directive value, etc.).• Specification-version and version specified together (for the same

package(s)) but with different values on manifest headers that treat them as synonyms. For example:

Import-Package p;specification-version=1;version=2would fail to install, but:

Import-Package p;specification-version=1, q;version=2would not be an error.

• The manifest lists a OSGI- INF/permission .perm file but no such file is present.

• Bundle-ManifestVersion value not equal to 2, unless the Framework spe-cifically recognizes the semantics of a later release.

3.12 OptionalThis specification provides for a number of optional mechanisms. The rea-son to make these mechanisms optional is to allow implementations that put a premium on footprint. All optional mechanisms can be more or less implemented with the mandatory mechanisms.

The following properties define optional parts of the Framework. These names are self-explanatory:

• org.osgi .supports. framework.requirebundle• org.osgi .supports. framework.f ragments• org.osgi .supports. framework.extension • org.osgi .supports.bootclasspath.extension

If the property is not set or the value is unrecognized, then the value defaults to fa lse .

A Framework that does not implement the headers associated with the mechanisms must refuse to install or update a bundle that carries one of these headers. It must then throw an exception at install or update time.

3.13 Requiring BundlesThe Framework can support a mechanism where bundles can be directly wired to other bundles, discarding any specific package knowledge. The fol-lowing sections define the relevant headers and then discuss the possible scenarios. At the end, some of the (sometimes unexpected) consequences of using Require-Bundle are discussed.

66-268 OSGi Service Platform Release 4

Page 75: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Requiring Bundles

3.13.1 Require-BundleThe Require-Bundle manifest header contains a list of bundle symbolic names that need to be searched after the imports are searched but before the bundle’s class path is searched. However, only packages that are marked exported by the required bundles are visible to the requiring bundle.

The Require-Bundle manifest header must conform to the following syntax:

Require-Bundle ::= bundle-description ( ',' bundle-description )*

bundle-description ::= symbolic-name // See 1.4.2(';' parameter )*

The following directives can be used in the Require-Bundle header:

• vis ib i l i ty – If the value is private (Default), then all visible packages from the required bundles are not re-exported. If the value is reexport then all the visible packages of the required bundles are exported from this bundle as if they were local to this bundle.

• resolut ion – If the value is mandatory (default) then the required bundle must exist for this bundle to resolve. If the value is opt ional , the bundle will resolve even if the required bundle does not exist.

The following matching attribute is architected by the Framework:

• bundle-vers ion – The value of this attribute is a version range to select the bundle version of the required bundle. See Version Ranges on page 30. The default value is [0.0.0,∞) .

A given package may be available from more than one of the bundles that are required. This is explicitly allowed; such packages are treated as split packages. A split package is a package which does not have a single provider, but the contents can come from different bundles. For example, take the fol-lowing setup:

A: Require-Bundle: B Export-Package: pB: Export-Package: p;partial=true;mandatory:=partial

If bundle C imports package p , it will be wired to package A.p , however the contents will come from B.p > A.p . The mandatory attribute on bundle B ’s export definition ensures that bundle B is not accidentally selected as exporter for package p . Split packages have a number drawbacks that are discussed in Issues With Requiring Bundles on page 68.

Resources and classes from a split package must be searched in the order in which the required bundles are specified in the Require-Bundle header.

As an example, assume that a bundle consists of a number of bundles and a number of language resources (also bundles) that are optional.

Require-Bundle: com.acme.facade;visibility:=reexport, com.acme.bar.one;visibility:=reexport, com.acme.bar.two;visibility:=reexport, com.acme.bar._nl;visibility:=reexport;resolution:=optional, com.acme.bar._en;visibility:=reexport;resolution:=optional

OSGi Service Platform Release 4 67-268

Page 76: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Requiring Bundles Module Layer Version 1.3

A bundle may both import packages (via Import-Package) and require one or more bundles (via Require-Bundle), but if a package is imported via Import-Package, it is not also visible via Require-Bundle: Import-Package takes priority over Require-Bundle, and packages which are exported by a required bundle and imported via Import-Package must not be treated as split packages.

In order to be allowed to require a named bundle, the requiring bundle must have BundlePermiss ion[<bundle symbol ic name>, REQUIRE] , where the bundle symbolic name is the name of the bundle that is required. The required bundle must be able to provide the bundle and must therefore have BundlePermission[<bundle symbol ic name>, PROVIDE] , where the name designates the requiring bundle.

3.13.2 Issues With Requiring BundlesThe preferred way of wiring bundles is to use the Import-Package and Export-Package headers because they couple the importer and exporter to a much lesser extent. Bundles can be refactored to have a different package composition without causing other bundles to fail.

The Require-Bundle header provides a way for a bundle to bind to all the exports of another bundle, regardless of what those exports are. Though this can seem convenient at first, it has a number of drawbacks:

• Split Packages – Classes from the same package can come from different bundles with Require bundle, such a package is called a split package. Split packages have the following drawbacks:• Completeness – Split packages are open ended, there is no way to guar-

antee that all the intended pieces of a split package have actually been included.

• Ordering – If the same classes are present in more than one required bundle, then the ordering of Require-Bundle is significant. A wrong ordering can cause hard to trace errors, similar to the traditional class path model of Java.

• Performance – A class must be searched in all providers when packages are split. This increases the number of times that a ClassNotFoundExcept ion must be thrown which can introduce a sig-nificant overhead.

• Mutable Exports – The feature of v is ibi l ity :=reexport that the export sig-nature of the requiring bundle can unexpectedly change depending on the export signature of the required bundle.

• Shadowing – The classes in the requiring bundle that are shadowed by those in a required bundle depend on the export signature of the required bundle and the classes the required bundle contains. (By con-trast, Import-Package, except with resolut ion:=optiona l , shadows whole packages regardless of the exporter.)

• Unexpected Signature Changes – The Require-Bundle directive vis ib il i ty :=pr ivate (the default) may be unexpectedly overridden in some circumstances as the following example shows.

A: p (private, not exposed in manifest) Require-Bundle: B;visibility:=reexport, C;visibility:=private

68-268 OSGi Service Platform Release 4

Page 77: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Fragment Bundles

B: Export-Package: pC: Export-Package: p

The export signature of bundle A will consist of only package p . How-ever, package p is split. The Framework searches for a class in package p in bundle B , then bundle C , and last bundle A .So the vis ib il i ty :=pr ivate directive on Require-Bundle C had no effect rel-ative to package p. However, if bundle B was changed to stop exporting package p , then the directive would take effect and package p would drop out of bundle A 's export signature. This is depicted in Figure 27.

Figure 27 Unexpected Signature change

3.14 Fragment BundlesFragments are bundles that are attached to a host bundle by the Framework. Attaching is done as part of resolving: the Framework appends the relevant definitions of the fragment bundles to the host’s definitions before the host is resolved. Fragments are therefore treated as part of the host; they must not have their own class loader.

A key use case for fragments is providing translation files for different locales. This allows the translation files to be treated and shipped indepen-dently from the main application bundle.

When an attached fragment bundle is updated, the content of the previous fragment must remain attached to its host bundle. The new content of the updated fragment must not be allowed to attach to the host bundle until the Framework is restarted or the host bundle is refreshed.

When attaching a fragment bundle to a host bundle the Framework must perform the following steps:

1 Append the import definitions for the Fragment bundle that do not con-flict with an import definition of the host to the import definitions of the host bundle. A Fragment import definition conflicts with a host import definition if it has the same package name and any of its directives or matching attributes are different. If a conflict is found, the Fragment bundle is not attached to the host bundle. A Fragment can provide an import statement for a private package of the host. The private package in the host is hidden in that case.

2 Append the Require-Bundle entries of the fragment bundle that do not conflict with a Require-Bundle entry of the host to the Require-Bundle

A

C

B

p

pp

q

visibility:=reexport

visibility:=private

OSGi Service Platform Release 4 69-268

Page 78: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Fragment Bundles Module Layer Version 1.3

entries of the host bundle. A fragment Require-Bundle entry conflicts with a host Require-Bundle entry only if it has the same bundle symbolic name but a different version range. If a conflict is found, the fragment is not attached to the host bundle.

3 Append the export definitions of a Fragment bundle that do not conflict with an export definition of the host to the export definitions of the host bundle. A Fragment bundle’s export definition conflicts with a host export definition if it has the same package name. If a conflict is found, the export from the Fragment bundle must be ignored but the fragment bundle is still attached.

A Fragment bundle must enter the resolved state only if it has been success-fully attached to its host bundle.

During runtime, the fragment’s JAR is searched after the host’s bundle class path as described in Fragments During Runtime on page 71.

3.14.1 Fragment-HostA fragment is a bundle that is attached to one other bundle called its host bun-dle. The components of the fragment, like the Bundle-Classpath and other definitions, are added at the end of the related definitions of the host bundle. All classes and resources within the fragment bundle must be loaded using the class loader of the host bundle.

The Fragment-Host manifest header must conform to the following syntax:

Fragment-Host ::= bundle-descriptionbundle-description ::= symbolic-name

(';' parameter ) * // See 1.4.2

The following directives are architected by the Framework for Fragment-Host:

• extension – Indicates this extension is a system or boot class path extension. It is only applicable when the Fragment-Host is the System Bundle. This is discussed in Extension Bundles on page 72. The following values are supported:• framework - The fragment bundle is a Framework extension bundle.• bootclasspath - The fragment bundle is a boot class path extension

bundle.The fragment must be the bundle symbolic name of the implementation specific system bundle or the alias system.bundle . The Framework should fail to install an extension bundle when the bundle symbolic name is not referring to the system bundle.

The following attributes are architected by the Framework for Fragment-Host:

• bundle-vers ion – The version range to select the bundle that provides the host bundle. See Version Matching on page 42. The default value is [0.0 .0,∞) .

When a fragment bundle becomes resolved, the Framework must attach the fragment bundle to the selected host bundle with the highest version. When a fragment bundle is attached to its host bundle, it logically becomes part of it. All classes and resources within the fragment bundle must be

70-268 OSGi Service Platform Release 4

Page 79: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Fragment Bundles

loaded using the class loader of its host bundle. The fragment bundles of a host bundle must be attached to the host bundle in the order that the frag-ment bundles are installed, which is in ascending bundle ID order. If an error occurs during the attachment of a fragment bundle then the fragment bundle must not be attached to the host. A fragment bundle must enter the resolved state only if it has been successfully attached to its host bundles.

If a bundle specifies the Fragment-Host header, it is illegal to specify:

• Bundle-Activator

In order for a host bundle to allow fragments to attach, the host bundle must have BundlePermission[<bundle symbol ic name>,HOST] . In order to be allowed to attach to a host bundle, a fragment bundle must have BundlePermiss ion[<bundle symbol ic name> ,FRAGMENT] .

3.14.2 Fragments During RuntimeAll class or resource loading of a fragment is handled through the host’s class loader, a fragment must never have its own class loader. Fragment bun-dles are treated as if they are an intrinsic part of their host.

Though a fragment bundle does not have its own class loader, it still must have a separate Protection Domain when it is not an extension fragment. Each fragment can have its own permissions linked to the fragment bun-dle’s location and signer.

A host bundle’s class path is searched before a fragment’s class path. This implies that packages can be split over the host and any of its fragments. Searching the fragments must be done in ascending bundle ID order. This is the order that the fragment bundles were installed.

Figure 28 Resource/class searching with fragments

Figure 28 shows a setup with two fragments. Bundle B is installed before bundle C and both bundle B and bundle C attach to bundle A . The following table shows where different packages originate in this setup. Note that the order of the append (>) is significant.

A

p

p

r

pB

s

qC

21

qq

q

D

r

p

t t

A.p export is chosen

OSGi Service Platform Release 4 71-268

Page 80: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Extension Bundles Module Layer Version 1.3

In the example above, if package p had been imported from bundle D , the table would have looked quite different. Package p would have come from bundle D, and bundle A ’s own contents as well as the contents of bundle B would have been ignored.

If package q had bundle D , then the class path would have to be searched, and A.q would have consisted of A.q > C.q .

Fragments must remain attached as long as the host remains resolved. When a host bundle becomes unresolved, then all attached Fragment bun-dles must be detached from the host bundle. When a fragment bundle becomes unresolved the Framework must:

• Detach it from the host• Re-resolve the host bundle • Reattach the remaining attached fragment bundles.

A Fragment bundle can become unresolved by calling the ref reshPackages method or the resolveBundle method on itself or on its host.

3.15 Extension BundlesExtension bundles can deliver optional parts of the Framework implemen-tation or provide functionality that must reside on the boot class path. These packages cannot be provided by the normal import/export mecha-nisms.

Boot class path extensions are necessary because certain package implemen-tations assume that they are on the boot class path or are required to be available to all clients. An example of a boot class path extension is an implementation of java.sql such as JSR 169.

Framework extensions are necessary to provide implementation aspects of the Framework. For example, a Framework vendor could supply the optional services like Permission Admin service and Start Level service with Framework extension bundles.

An extension bundle should use the bundle symbolic name of the imple-mentation system bundle, or it can use the alias of the system bundle, which is system.bundle .

Table 5 Effect of fragments on searchingPackage Requested From Remark

p A.p > B.p Bundle A exports package p , therefore, it will search its class path for p . This class path con-sists of the JAR and then its Fragment bundles.

q D.q The import does not handle split packages and package q is imported from bundle D . Therefore, C.q is not found.

r A.r > B.r Package r is not imported and therefore comes from the class path.

s C.s

t B.t > C.t

72-268 OSGi Service Platform Release 4

Page 81: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Extension Bundles

The following example uses the Fragment-Host manifest header to specify an extension bundle for a specific Framework implementation.

Fragment-Host: com.acme.impl.framework; extension:=framework

The following example uses the Fragment-Host manifest header to specify a boot class path extension bundle.

Fragment-Host: system.bundle; extension:=bootclasspath

The following steps describe the life cycle of an extension bundle:

1 When an extension bundle is installed it enters the INSTALLED state. 2 The extension bundle is allowed to enter the RESOLVED state at the

Frameworks discretion.3 If the extension bundle is refreshed then the Framework must

shutdown, the host VM must terminate and the Framework must be re-launched.

4 If a RESOLVED extension bundle is refreshed then the Framework must shutdown; the host VM must terminate and framework must be re-launched.

5 When a RESOLVED extension bundle is updated or UNINSTALLED, it is not allowed to re-enter the RESOLVED state. If the extension bundle is refreshed then the Framework must shutdown; the host VM must ter-minate and framework must be re-launched.

3.15.1 Illegal Manifest Headers for Extension BundlesAn extension bundle must throw a BundleException if it is installed or updated and it specifies any of the following headers.

• Import-Package• Require-Bundle• Bundle-NativeCode• Dynamic Import-Package• Bundle-Activator

Both boot class path and framework extension bundles are permitted to specify an Export-Package header. Any exported packages specified by a framework extension bundle must be exported by the System Bundle when the extension bundle is resolved.

3.15.2 Class Path TreatmentA boot class path extension bundle’s JAR file must be appended to the boot class path of the host VM. A framework extension bundle’s JAR is appended to the class path of the Framework.

Extension bundles must be appended to their class path in the order in which the extension bundles are installed: that is, ascending bundle ID order.

How a framework configures itself or the boot class path to append the extension bundle’s JAR is implementation specific. In some execution envi-ronments, it may be impossible to support extension bundles. In such envi-ronments, the Framework must throw a BundleException when such an extension bundle is installed. The resulting Bundle Exception must have a cause of type UnsupportedOperationExcept ion .

OSGi Service Platform Release 4 73-268

Page 82: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Module Layer Version 1.3

3.16 Security

3.16.1 Extension BundlesIn an environment that has Java 2 security enabled the Framework must perform an additional security check before allowing an extension bundle to be installed. In order for an extension bundle to successfully install, the Framework must check that the extension bundle has All Permissions assigned to it. This means that the permissions of an extension bundle must be setup before the extension bundle is installed.

AllPermission must be granted to extension bundles because they will be loaded under the Protection Domain of either the boot class path or the Framework implementation. Both of these Protection Domains have All Permissions granted to them. It must therefore not be allowed for an exten-sion bundle to be installed unless it already has been granted AllPermis-sions.

The installer of an extension bundle must have AdminPermiss ion[ <extension bundle>,EXTENSIONLIFECYCLE] to install an extension bundle.

3.16.2 Bundle PermissionMost package sharing permissions are based on Package Permission. How-ever, fragments and required bundles use the bundle symbolic name to han-dle sharing. The Bundle Permission is used to control this type of package sharing. Bundle Permission is optional, but a Framework that supports Require-Bundle must also support Bundle Permission.

The name parameter of the Bundle Permission is a bundle symbolic name. The symbolic name is used as the identifier for the target bundle. A wild card (’ .*’ \u002E,\u002A) is permitted at the end of the name.

For example, if fragment bundle A attaches to its host bundle B then frag-ment bundle A requires BundlePermission("B" , " f ragment" ) so that A is per-mitted to target host bundle B . The direction of the actions is depicted in Figure 29.

Figure 29 Permissions and bundle sharing

The following actions are architected:

• provide – Permission to provide packages to the target bundle. • require – Permission to require packages from the target bundle.• host – Permission to attach to the target fragment bundle.• f ragment – Permission to attach as a fragment to the target host bundle.

A

p

ps

qB

t

Cq A, fragment

B, host

C, provide

A, require

74-268 OSGi Service Platform Release 4

Page 83: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 Security

3.16.3 Package Permission Bundles can only import and export packages for which they have the required permission. A PackagePermission must be valid across all versions of a package.

A PackagePermiss ion has two parameters:

• The package that may be exported or imported. A wildcard may be used. The granularity of the permission is the package, not the class name.

• The action, either IMPORT or EXPORT . If a bundle has permission to export a package, the Framework must automatically grant it per-mission to import the package.

A PackagePermiss ion with * and EXPORT as parameters allows the import and export of any package.

3.16.4 Resource PermissionsA Framework must always give a bundle the RESOURCE, METADATA, and CLASS AdminPermiss ion actions to access the resources contained within:

• Itself • Any attached fragments• Any resources from imported packages

A resource in a bundle may also be accessed by using certain methods on Bundle . The caller of these methods must have AdminPermission[bundle , RESOURCE] .

If the caller does not have the necessary permission, a resource is not acces-sible and nul l must be returned. Otherwise, a URL object to the resource must be returned. These URLs are called bundle resource URLs. Once the URL object is returned, no further permission checks are performed when the contents of the resource are accessed. The URL object must use a scheme defined by the Framework implementation.

Bundle resource URLs are normally created by the Framework, however, in certain cases bundles need to manipulate the URL to find related resources. For example, a URL can be constructed to a resource that is in the same directory as a given resource.

URLs that are not constructed by the Framework must follow slightly differ-ent security rules due to the design of the java.net .URL class. Not all con-structors of the URL class interact with the URL Stream Handler classes (the implementation specific part). Other constructors call at least the parseURL method in the URL Stream Handler where the security check can take place. This design makes it impossible for the Framework check the permissions during construction of a bundle resource URL.

The following constructors use the parseURL method and are therefore checked when a bundle resource URL is constructed.

URL(String spec)URL(URL context, String spec)URL(URL context, String spec, URLStreamHandler handler)

OSGi Service Platform Release 4 75-268

Page 84: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Module Layer Version 1.3

When one of these constructors is called for a bundle resource URL, the implementation of the Framework must check the caller for the necessary permissions in the parseURL method. If the caller does not have the neces-sary permissions then the parseURL method must throw a Security Excep-tion. This will cause a Malformed URL Exception to be thrown by the URL constructor. If the caller has the necessary permissions, then the URL object is setup to access the bundle resource without further checks.

The following java.net.URL constructors do not call the parseURL method in the URL Stream Handler, making it impossible for the Framework to verify the permission during construction.

URL(String protocol, String host, int port, String file)URL(String protocol, String host, int port, String file, URLStreamHandler handler)URL(String protocol, String host, String file)

Bundle resource URLs that are created with these constructors cannot per-form the permission check during creation and must therefore delay the permission check. When the content of the URL is accessed, the Framework must throw a Security Exception if the caller does not have AdminPermission[bundle , RESOURCE] for the bundle referenced by the URL.

3.16.5 Permission ChecksSince multiple bundles can export permission classes with the same class name, the Framework must make sure that permission checks are per-formed using the correct class. For example, a bundle that calls the check-Permission method provides an instance of the Permission class:

void foo(String name) { checkPermission(new FooPermission(name,"foo"));}

This class of this Permission instance comes from a particular source. Per-missions can only be tested against instances that come from the same source.

Therefore, the Framework needs to look up permissions based on class rather than class name. When it needs to instantiate a permission it must use the class of the permission being checked to do the instantiation. This is a complication for Framework implementers; bundle programmers are not affected.

Consider the following example:

Bundle A Import-Package: p

Export-Package: q Bundle B

Import-Package: p• Bundle A uses a p.FooService . Usage of this class checks

q.FooPermiss ion whenever one of its methods is invoked.• Bundle B has a FooPermiss ion in its Protection Domain in a (Condi-

tional) Permission Info object.

76-268 OSGi Service Platform Release 4

Page 85: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Module Layer Version 1.3 References

• Bundle B invokes a method in the FooService that was given by bundle A.

• The FooService calls the checkPermission method with a new FooPermission instance.

• The Framework must use a FooPermiss ion object that is from the same class loader as the given FooPermiss ion object before it can call the impl ies method. In this case, the FooPermiss ion class comes from package A.q .

After the permission check, bundle B will have a FooPermiss ion instanti-ated using a class from a package it does not import. It is therefore possible that the Framework has to instantiate multiple variations of the FooPermiss ion class to satisfy the needs of different bundles.

3.17 References[19] The Standard for the Format of ARPA Internet Text Messages

STD 11, RFC 822, UDEL, August 1982http://www.ietf.org/rfc/rfc822.txt

[20] The Hypertext Transfer Protocol - HTTP/1.1RFC 2068 DEC, MIT/LCS, UC Irvine, January 1997 http://www.ietf.org/rfc/rfc2068.txt

[21] The Java 2 Platform API SpecificationStandard Edition, Version 1.3, Sun Microsystemshttp://java.sun.com/j2se/1.4

[22] The Java Language SpecificationSecond Edition, Sun Microsystems, 2000http://java.sun.com/docs/books/jls/index.html

[23] A String Representation of LDAP Search FiltersRFC 1960, UMich, 1996http://www.ietf.org/rfc/rfc1960.txt

[24] The Java Security Architecture for JDK 1.2Version 1.0, Sun Microsystems, October 1998

[25] The Java 2 Package Versioning Specificationhttp://java.sun.com/j2se/1.4/docs/guide/versioning/index.html

[26] Codes for the Representation of Names of Languages ISO 639, International Standards Organizationhttp://lcweb.loc.gov/standards/iso639-2/langhome.html

[27] Zip File FormatThe Zip file format as defined by the java.util.zip package.

[28] Manifest Format http://java.sun.com/j2se/1.4/docs/guide/jar/jar.html#JAR%20Manifest

[29] W3C EBNFhttp://www.w3c.org/TR/REC-xml#sec-notation

[30] Lexical Structure Java Languagehttp://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html

[31] Mathematical Convention for Interval Notationhttp://planetmath.org/encyclopedia/Interval.html

OSGi Service Platform Release 4 77-268

Page 86: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Module Layer Version 1.3

[32] Uniform Resource Identifiers URI: Generic SyntaxRFC 2396http://www.ietf.org/rfc/rfc2396.txt

[33] Codes for the Representation of Names of Languages ISO 639, International Standards Organizationhttp://lcweb.loc.gov/standards/iso639-2/langhome.html:

78-268 OSGi Service Platform Release 4

Page 87: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 Introduction

4 Life Cycle LayerVersion 1.3

4.1 IntroductionThe Life Cycle Layer provides an API to control the security and life cycle operations of bundles. The layer is based on the module and security layer.

4.1.1 Essentials• Complete – The Life Cycle layer must implement an API that fully covers

the installation, starting, stopping, updating, uninstallation, and moni-toring of bundles.

• Reflective – The API must provide full insight into the actual state of the Framework.

• Secure – It must be possible to use the API in a secure environment using fine-grained permissions. However, security must be optional.

• Manageable – It must be possible to manage a Service Platform remotely.

4.1.2 Entities• Bundle – Represents an installed bundle in the Framework.• Bundle Context – A bundle's execution context within the Framework.

The Framework passes this to a Bundle Activator when a bundle is started or stopped.

• Bundle Activator – An interface implemented by a class in a bundle that is used to start and stop that bundle.

• Bundle Event – An event that signals a life cycle operation on a bundle. This event is received via a (Synchronous) Bundle Listener.

• Framework Event – An event that signals an error or Framework state change. The event is received via a Framework Listener.

• Bundle Listener – A listener to Bundle Events.• Synchronous Bundle Listener – A listener to synchronously delivered

Bundle Events.• Framework Listener – A listener to Framework events.• Bundle Exception – An Exception thrown when Framework operations

fail.• System Bundle – A bundle that represents the Framework.

OSGi Service Platform Release 4 79-268

Page 88: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Bundles Life Cycle Layer Version 1.3

Figure 30 Class diagram org.osgi . f ramework Life Cycle Layer

4.2 BundlesA bundle represents a JAR file that is executed in an OSGi Framework. The class loading aspects of this concept were specified in the Module Layer. However, the Module Layer does not define how a bundle is installed, updated, and uninstalled. These life cycle operations are defined here.

The installation of a bundle can only be performed by another bundle or through implementation specific means (for example as a command line parameter of the Framework implementation).

A Bundle is started through its Bundle Activator. Its Bundle Activator is identified by the Bundle-Activator manifest header. The given class must implement the BundleAct ivator interface. This interface has a start and stop method that is used by the bundle programmer to register itself as lis-tener and start any necessary threads. The stop method must clean up and stop any running threads.

Upon the activation of a bundle, it receives a Bundle Context. The Bundle Context interface’s methods can roughly be divided in the following catego-ries:

<<interface>>Bundle

<<interface>>BundleContext

Framework Impl

<<interface>>Synchr.Bundle Listener

<<class>>FrameworkEvent

<<interface>>FrameworkListener

<<interface>>BundleListener

<<class>>BundleException

implementationcode of bundle

<<interface>>Constants

<<interface>>BundleActivator

class loader

Bundle Controller Impl

<<class>>Bundle Event

activated with

class loaded by

activated by

0,1

11

1

11

1

1..n

0..n

1 1

0..n

management representationcode mngmt

80-268 OSGi Service Platform Release 4

Page 89: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 The Bundle Object

• Information – Access to information about the rest of the Framework.• Life Cycle – The possibility to install other bundles.• Service Registry – The service registry is discussed in Service Layer on page

103.

4.3 The Bundle ObjectFor each bundle installed in the OSGi Service Platform, there is an associ-ated Bundle object. The Bundle object for a bundle can be used to manage the bundle’s life cycle. This is usually done with a Management Agent, which is also a Bundle.

4.3.1 Bundle IdentifiersA bundle is identified by a number of names that vary in their scope:

• Bundle identifier – A long that is a Framework assigned unique identifier for the full lifetime of a bundle, even if it is updated or the Framework is restarted. Its purpose is to distinguish bundles in a Framework. Bundle identifiers are assigned in ascending order to bundles when they are installed. The method getBundle Id() returns a bundle’s identifier.

• Bundle location – A name assigned by the management agent (Operator) to a bundle during the installation. This string is normally interpreted as a URL to the JAR file but this is not mandatory. Within a particular Framework, a location must be unique. A location string uniquely iden-tifies a bundle and must not change when a bundle is updated. The get-Locat ion() method retrieves the location of a bundle.

• Bundle Symbolic Name – A name assigned by the developer. The combi-nation of Bundle Version and Bundle Symbolic Name is a globally unique identifier for a bundle. The getSymbol icName() method returns the assigned bundle name.

4.3.2 Bundle StateA bundle can be in one of the following states:

• INSTALLED – The bundle has been successfully installed.• RESOLVED – All Java classes that the bundle needs are available. This

state indicates that the bundle is either ready to be started or has stopped.• STARTING – The bundle is being started, the BundleActivator.start

method has been called, and the start method has not yet returned.• ACTIVE – The bundle has successfully started and is running.• STOPPING – The bundle is being stopped. The BundleActivator.stop

method has been called but the stop method has not yet returned.• UNINSTALLED – The bundle has been uninstalled. It cannot move into

another state.

OSGi Service Platform Release 4 81-268

Page 90: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Bundle Object Life Cycle Layer Version 1.3

Figure 31 State diagram Bundle

When a bundle is installed, it is stored in the persistent storage of the Frame-work and remains there until it is explicitly uninstalled. Whether a bundle has been started or stopped must be recorded in the persistent storage of the Framework. A bundle that has been persistently recorded as started must be started whenever the Framework starts until the bundle is explicitly stopped. The Start Level service influences the actual starting and stopping of bundles. See Start Level Service Specification on page 195.

The Bundle interface defines a getState() method for returning a bundle’s state.

If this specification uses the term active to describe a state, then this includes the STARTING and STOPPING states.

Bundle states are expressed as a bit-mask though a bundle can only be in one state at any time. The following code sample can be used to determine if a bundle is in the STARTING , ACTIVE , or STOPPING state:

if ((b.getState() & (STARTING | ACTIVE | STOPPING) != 0)doActive()

4.3.3 Installing BundlesThe BundleContext interface, which is given to the Bundle Activator of a bundle, defines the following methods for installing a bundle:

• instal lBundle(Str ing) – Installs a bundle from the specified location string (which should be a URL).

• insta l lBundle(Str ing, InputStream) – Installs a bundle from the specified InputStream object.

A bundle must be valid before it is installed, otherwise the install must fail. The validity of a bundle is discussed in Bundle Validity on page 65.

Every bundle is uniquely identified by its location string. If an installed bun-dle is using the specified location, the ins tal lBundle methods must return the Bundle object for that installed bundle and not install a new bundle.

The Framework must assign a unique bundle identifier that is higher than any previous bundle identifier.

INSTALLED

UNINSTALLED

STARTING

STOPPING

ACTIVE

upda

te

reso

lvestop

install

RESOLVED

refre

sh

update

unin

stal

lunin

stal

l

start

refresh

82-268 OSGi Service Platform Release 4

Page 91: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 The Bundle Object

The installation of a bundle in the Framework must be:

• Persistent – The bundle must remain installed across Framework and Java VM invocations until it is explicitly uninstalled.

• Atomic – The install method must completely install the bundle or, if the installation fails, the OSGi Service Platform must be left in the same state as it was in before the method was called.

Once a bundle has been installed, a Bundle object is created and all remain-ing life cycle operations must be performed upon this object. The returned Bundle object can be used to start, stop, update, and uninstall the bundle.

4.3.4 Resolving BundlesA bundle can enter the RESOLVED state when the Framework has success-fully resolved the bundle's dependencies as described in the manifest. These dependencies are described in Resolving Process on page 50.

4.3.5 Starting BundlesThe Bundle interface defines the start() method for starting a bundle. If this method succeeds, the bundle’s state is set to ACTIVE and it remains in this state until it is stopped. The optional Start Level service influences the actual order of starting and stopping of bundles. See Start Level Service Specifi-cation on page 195.

To be started, a bundle must first be resolved. The Framework must attempt to resolve the bundle, if not already resolved, when trying to start the bun-dle. If the bundle fails to resolve, the start method must throw a BundleExcept ion . In this case, the bundle must still be persistently marked as started. A bundle marked as started and whose start level is appropriate must be automatically started as soon as the bundle becomes resolvable, even after a Framework restart.

If the bundle is resolved, the bundle must be activated by calling its Bundle Activator object, if one exists. The BundleAct ivator interface defines meth-ods that the Framework invokes when it starts and stops the bundle.

To inform the OSGi environment of the fully qualified class name serving as its Bundle Activator, a bundle developer must declare a Bundle-Activator manifest header in the bundle’s manifest file. The Framework must instanti-ate a new object of this class and cast it to a BundleActivator instance. It must then call the BundleActivator.s tart method to start the bundle.

The following is an example of a Bundle-Activator manifest header:

Bundle-Activator: com.acme.Activator

A class acting as a Bundle Activator must implement the BundleActivator interface, be declared public , and have a public default constructor so an instance of it may be created with Class.newInstance .

Supplying a Bundle Activator is optional. For example, a library bundle that only exports a number of packages does not need to define a Bundle Activa-tor. In addition, other mechanism exists to obtain control and get a Bundle Context, like for example the Service Component Runtime.

The BundleActivator interface defines these methods for starting and stop-ping a bundle:

OSGi Service Platform Release 4 83-268

Page 92: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Bundle Object Life Cycle Layer Version 1.3

• start (BundleContext) – This method can allocate resources that a bundle needs, start threads, register services, and more. If this method does not register any services, the bundle can register services it needs later: for example, in a callback or an external event, as long as it is in the ACTIVE state.

• stop(BundleContext) – This method must undo all the actions of the BundleAct ivator.start (BundleContext) method. However, it is unnec-essary to unregister services or Framework listeners, because they must be cleaned up by the Framework anyway.

A Bundle Activator must be created when a Bundle is started, implying the creation of a class loader. For larger systems, this greedy strategy can signifi-cantly increase startup times and unnecessarily increase the memory foot-print. Mechanisms such as the Service Component Runtime can mitigate these problems.

4.3.6 Stopping BundlesThe Bundle interface defines the stop() method for stopping a bundle. This stops a bundle and sets the bundle’s state to RESOLVED .

The BundleActivator interface defines a stop(BundleContext) method, which is invoked by the Framework to stop a bundle. This method must release any resources allocated since activation. All threads associated with the stopping bundle should be stopped immediately. The threaded code may no longer use Framework-related objects (such as services and BundleContext objects) once the stop method returns.

If the stopping bundle had registered any services during its lifetime, then the Framework must automatically unregister all registered services when the bundle is stopped. It is therefore unnecessary to unregister any services in the stop method.

The Framework must guarantee that if a BundleActivator .start method has executed successfully, that same BundleAct ivator object must be called with its BundleAct ivator .stop method when the bundle is deactivated. After call-ing the stop method, that particular BundleAct ivator object must never be used again.

Packages exported by a stopped bundle continue to be available to other bundles. This continued export implies that other bundles can execute code from a stopped bundle, and the designer of a bundle should assure that this is not harmful. Exporting interfaces only is one way to prevent such unwanted execution when the bundle is not started. Generally, to ensure they cannot be executed, interfaces should not contain executable code.

4.3.7 Updating BundlesThe Bundle interface defines two methods for updating a bundle:

• update() – This method updates a bundle. • update( InputStream) – This method updates a bundle from the specified

InputStream object.

The update process supports migration from one version of a bundle to a newer version of the same bundle.

84-268 OSGi Service Platform Release 4

Page 93: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 The Bundle Object

An updated bundle must directly provide its exported packages to the sys-tem. At the same time, packages exported by the previous version continue to be available, for existing and future bundles, until the refreshPackages method has been called or the Framework is restarted.

An updater of a bundle must have AdminPermission[<bundle> ,L IFECYCLE] for both the installed bundle as well as the new bundle. The parameters of AdminPermiss ion are explained in Admin Permission on page 97.

4.3.8 Uninstalling BundlesThe Bundle interface defines the uninstal l ( ) method for uninstalling a bun-dle from the Framework. This method causes the Framework to notify other bundles that the bundle is being uninstalled, and sets the bundle’s state to UNINSTALLED . To whatever extent possible, the Framework must remove any resources related to the bundle. This method must always uninstall the bundle from the persistent storage of the Framework.

Once this method returns, the state of the OSGi Service Platform must be the same as if the bundle had never been installed, unless:

• The uninstalled bundle has exported any packages (via its Export-Package manifest header)

• The uninstalled bundle was selected by the Framework as the exporter of these packages.

If the bundle did export any packages that are used by other bundles, the Framework must continue to make these packages available to their importing bundles until one of the following conditions is satisfied:

• The org.osgi .serv ice .packageadmin.PackageAdmin .refreshPackages method has been called.

• The Framework is restarted.

Packages of uninstalled bundles must not be used by newly installed bun-dles, but are still used by its importers until the ref reshPackages method has been called or the Framework is restarted.

4.3.9 Detecting Bundle ChangesThe Bundle object provides a convenient way to detect changes in a bundle. The Framework must keep the time that a bundle is changed by any of the life cycle operations. The getLastModif ied() method will return the last time the bundle was installed, updated, or uninstalled. This last modified time must be stored persistently.

The method must return the number of milliseconds since midnight Jan. 1, 1970 UTC with the condition that a change must always result in a higher value than the previous last modified time of any bundle.

The getLastModif ied() is very useful when a bundle is caching resources from another bundle and needs to refresh the cache when the bundle changes. This life cycle change of the target bundle can happen while the caching bundle is not active. The last modified time is therefore a conve-nient way to track these target bundles.

OSGi Service Platform Release 4 85-268

Page 94: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Bundle Object Life Cycle Layer Version 1.3

4.3.10 Retrieving Manifest HeadersThe Bundle interface defines two methods to return manifest header infor-mation: getHeaders() and getHeaders(Str ing) .

• getHeaders() – Returns a Dict ionary object that contains the bundle's manifest headers and values as key/value pairs. The values returned are localized according to the default locale returned by java .uti l .Locale.getDefau lt .

• getHeaders(Str ing) – Returns a Dict ionary object that contains the bundle's manifest headers and values as key/value pairs. The returned values are localized using the specified locale. The locale may take the following values:• nul l – The default locale returned by java.ut i l .Locale.getDefault is

used. This makes this method identical to the getHeaders() method.• Empty string – The dictionary will contain the raw (unlocalized) man-

ifest headers including any leading '%'. • A Specific Locale – The given locale is used to localize the manifest

headers.

Localization is performed according to the description in Localization on page 64. If no translation is found for a specific key, the Dictionary returned by Bundle .getHeaders will return the raw values as specified in the mani-fest header values without the leading '%’ character.

These methods require AdminPermiss ion[<bundle> , METADATA ] because some of the manifest header information may be sensitive, such as the pack-ages listed in the Export-Package header. Bundles always have permission to read their own headers.

The getHeaders methods must continue to provide the manifest header information after the bundle enters the UNINSTALLED state. After the bun-dle has been uninstalled, this method will only return manifest headers that are raw or localized for the default locale at the time the bundle was unin-stalled.

A framework implementation must use only the raw (unlocalized) manifest headers when processing manifest headers. Localizations must not influ-ence the operations of the Framework.

4.3.11 Loading ClassesIn certain cases, it is necessary to load classes as if they were loaded from inside the bundle. The loadClass(Str ing) method gives access to the bundle class loader. This method can be used to:

• Load plugins from another bundle• Start an application model activator• Interact with legacy code

For example, an application model could use this feature to load the initial class from the bundle and start it according to the rules of the application model.

void appStart() {Class initializer = bundle.loadClass(activator);if ( initializer != null ) {

86-268 OSGi Service Platform Release 4

Page 95: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 The Bundle Object

App app = (App) initializer.newInstance(); app.activate(); }}

4.3.12 Access to ResourcesThe resources from a bundle can come from different sources. They can come from the raw JAR file, Fragment bundles, imported packages, or the bundle class path. Different use cases require a different resource search strategy. The Bundle interface provides a number of methods that access resources but use different strategies. The following search strategies are supported:

• Class Space – The getResource(Str ing) and getResources(Str ing) provide access to resources that is consistent with the class space as described in Overall Search Order on page 54. Following the search order can make certain parts of the JAR files inaccessible. These methods require that the bundle is resolved. If the bundle is not resolved, the Framework must attempt to resolve it.The search order can hide certain directories of the JAR file. Split pack-ages are taken into account; therefore, resources with the same package names can come from different JARs. If the bundle is unresolved (or can-not be resolved), the getResource and getResources methods must only load resources from the bundle class path. This search strategy should be used by code that wants to access its own resources. Calling either method can cause the creation of a class loader and force the bundle to become resolved.

• JAR File – The getEntry(Str ing) and getEntryPaths(Str ing) methods provide access to the resources in the bundle’s JAR file. No searching is involved, only the raw JAR file is taken into account. The purpose of these methods is to provide low-level access without requiring that the bundle is resolved.

• Bundle Space – The f indEntries(String,Str ing,boolean) is an intermediate form. Useful when configuration or setup information is needed from another bundle. It considers Fragment bundles but it will never create a class loader or resolve the bundle. The method provides access to all directories in the associated JAR files.

For example, consider the following setup:

A: Require-Bundle: D Import-Package: q,t Export-Package: tB: Export-Package: q,tC: Fragment-Host: AD: Export-Package: s

This setup is depicted in Figure 32.

OSGi Service Platform Release 4 87-268

Page 96: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Bundle Object Life Cycle Layer Version 1.3

Figure 32 Setup for showing the difference between getResource and getEntry

The following table shows the effect of getting a resource from this setup when bundle A is resolved.

Table 7 shows the same cases as the previous table but now for an unre-solved bundle A .

4.3.13 Permissions of a BundleThe Bundle interface defines a method for returning information pertaining to a bundle’s permissions: hasPermission(Object) . This method returns true if the bundle’s Protection Domain has the specified permission, and fa lse if it does not, or if the object specified by the argument is not an instance of java.security .Permission .

The parameter type is Object so that the Framework can be implemented on Java platforms that do not support Java 2 based security.

BA

p

qq

s

p

r

D

C

t

t

t

Table 6 Differences between getResource, getEntry, and findEntries for resolved bundle A

Resource getResource getEntry findEntriesq B.q null nullp A.p > C.p A.p A.p > C.pr C.r null C.rs D.s null nullt B.t A.t A.t

Table 7 Differences between getResource, getEntry, and findEntries for an unre-solved bundle A

Resource getResource getEntry findEntriesq null null nullp A.p A.p A.pr null null nulls null null nullt A.t A.t A.t

88-268 OSGi Service Platform Release 4

Page 97: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 The Bundle Context

4.4 The Bundle ContextThe relationship between the Framework and its installed bundles is real-ized by the use of BundleContext objects. A BundleContext object repre-sents the execution context of a single bundle within the OSGi Service Platform, and acts as a proxy to the underlying Framework.

A BundleContext object is created by the Framework when a bundle is started. The bundle can use this private BundleContext object for the fol-lowing purposes:

• Installing new bundles into the OSGi environment. See Installing Bundles on page 82.

• Interrogating other bundles installed in the OSGi environment. See Getting Bundle Information on page 89.

• Obtaining a persistent storage area. See Persistent Storage on page 89.• Retrieving service objects of registered services. See Service References on

page 105.• Registering services in the Framework service. See Registering Services on

page 106.• Subscribing or unsubscribing to events broadcast by the Framework. See

Listeners on page 93.

When a bundle is started, the Framework creates a BundleContext object and provides this object as an argument to the start(BundleContext) method of the bundle’s Bundle Activator. Each bundle is provided with its own BundleContext object; these objects should not be passed between bun-dles, since the BundleContext object is related to the security and resource allocation aspects of a bundle.

After the stop(BundleContext) method has returned, the BundleContext object must no longer be used. Framework implementations must throw an exception if the BundleContext object is used after a bundle is stopped.

4.4.1 Getting Bundle InformationThe BundleContext interface defines methods to retrieve information about bundles installed in the OSGi Service Platform:

• getBundle() – Returns the single Bundle object associated with the BundleContext object.

• getBundles() – Returns an array of the bundles currently installed in the Framework.

• getBundle( long) – Returns the Bundle object specified by the unique identifier, or nul l if no matching bundle is found.

Bundle access is not restricted; any bundle can enumerate the set of installed bundles. Information that can identify a bundle, however (such as its loca-tion, or its header information), is only provided to callers that have AdminPermiss ion[<bundle> ,METADATA] .

4.4.2 Persistent StorageThe Framework should provide a private persistent storage area for each installed bundle on platforms with some form of file system support.

OSGi Service Platform Release 4 89-268

Page 98: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Bundle Context Life Cycle Layer Version 1.3

The BundleContext interface defines access to this storage in terms of the Fi le class, which supports platform-independent definitions of file and directory names.

The BundleContext interface defines a method to access the private persis-tent storage area: getDataF i le(Str ing) . This method takes a relative file name as an argument. It translates this file name into an absolute file name in the bundle’s persistent storage area. It then returns a F ile object. This method returns nul l if there is no support for persistent storage.

The Framework must automatically provide the bundle with Fi lePermission[<storage area> , READ | WRITE | DELETE] to allow the bun-dle to read, write, and delete files in that storage area.

If EXECUTE permissions is required, then a relative path name can be used in the File Permission definition. For example, Fi lePermission[bin/*,EXECUTE] speci f ies that the sub-directory in the bundle’s private data area may contain executables. This only provides execute permission within the Java environment and does not handle the potential underlying operating system issues related to executables.

This special treatment applies only to F ilePermiss ion objects assigned to a bundle. Default permissions must not receive this special treatment. A Fi lePermission for a relative path name assigned via the setDefaultPermission method must be ignored.

4.4.3 Environment PropertiesThe BundleContext interface defines a method for returning information pertaining to Framework properties: getProperty(Str ing) . This method can be used to return the following Framework properties:

Table 8 Property NamesProperty name Descriptionorg.osg i. f ramework.vers ion The specification version of the Framework, must be 1.3org.osg i. f ramework.vendor The vendor of the Framework implementation. org.osg i. f ramework. language The language being used. See ISO 639, International Standards

Organization See [41] Codes for the Representation of Names of Languages for valid values.

org.osg i. f ramework. « executionenvironment

A comma-separated list of provided execution environments (EE). All methods of each listed EE must be present on the Service Platform. For example, this property could contain:

CDC-1.0/Foundation-1.0,OSGi/Minimum-1.0

A Service Platform implementation must provide all the sig-natures that are defined in the mentioned EEs. Thus, the exe-cution environment for a specific Service Platform Server must be the combined set of all signatures of all EEs in the org.osgi . f ramework.execut ionenvironment property.

org.osg i. f ramework .processor Processor name. The following table defines a list of proces-sor names. New processors are made available on the OSGi web site. Names should be matched case insensitive.Name Aliases Description

90-268 OSGi Service Platform Release 4

Page 99: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 The Bundle Context

68k 68000 and upARM Inte l Strong ARMAlpha CompaqIgnite psc1k PTSCMips SGIPArisc Hewlett PackardPowerPC power ppc Motoro la/ IBMSparc SUNx86 pent ium i386

i486 i586 i686Inte l

x86-64 amd64 New 64 bit x86 a rchitec-ture

org .osg i . framework.os.version The version of the operating system. If the version does not fit the standard x.y.z format (e.g. 2.4.32-kwt), then the Opera-tor should define a System property with this name.

org .osg i . framework.os.name The name of the operating system (OS) of the host computer. The following table defines a list of OS names. New OS names are made available on the OSGi web site. Names should be matched case insensitive.Name Aliases DescriptionAIX IBMDig italUnix CompaqFreeBSD Free BSDHPUX Hewlett PackardIRIX Si l icon GraphicsLinux Open sourceMacOS AppleNetware Novel lOpenBSD Open sourceNetBSD Open sourceOS2 OS/2 IBMQNX procnto QNXSolaris Sun Micro SystemsSunOS Sun Micro SystemsVxWorks WindR iver SystemsWin32 Win* Al l Microsoft Windows

operating systemsWindows95 Win95

Windows 95Microsoft Windows 95

Windows98 Win98Windows 98

Microsoft Windows 98

WindowsNT WinNTWindows NT

Microsoft Windows NT

Table 8 Property NamesProperty name Description

OSGi Service Platform Release 4 91-268

Page 100: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The System Bundle Life Cycle Layer Version 1.3

All Framework properties may be defined by the Operator as System proper-ties. If these properties are not defined as System properties, the Framework must construct these properties from relevant standard Java System proper-ties.

The alias column contains is names that have been reported to be returned by certain versions of the related operating systems. Frameworks should try to convert these aliases to the canonical OS or processor name. The bundle developer should use the canonical name in the Bundle-NativeCode mani-fest header.

4.5 The System BundleIn addition to normal bundles, the Framework itself is represented as a bun-dle. The bundle representing the Framework is referred to as the system bun-dle. Through the system bundle, the Framework may register services that can be used by other bundles. Examples of such services are the Package Admin and Permission Admin services.

The system bundle is listed in the set of installed bundles returned by BundleContext .getBundles() , although it differs from other bundles in the following ways:

• The system bundle is always assigned a bundle identifier of zero (0).• The system bundle getLocation method returns the string: "System

Bundle", as defined in the Constants interface.

WindowsCE WinCEWindows CE

Microsoft Windows CE

Windows2000 Win2000Windows 2000

Microsoft Windows 2000

WindowsXP Windows XP, WinXP

Microsoft Windows XP

org.osg i.supports .«

framework.extension

See Optional on page 66.

org.osg i.supports .«

bootc lasspath.extension

See Optional on page 66.

org.osg i.supports .«

f ramework.fragment

See Optional on page 66.

org.osg i.supports .«

f ramework.requirebundle

See Optional on page 66.

org.osg i. f ramework.«

bootdelegation

See Parent Delegation on page 54

org.osg i. f ramework.«

system.packages

See Parent Class Loader on page 57

Table 8 Property NamesProperty name Description

92-268 OSGi Service Platform Release 4

Page 101: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 Events

• The system bundle has a bundle symbolic name that is unique for a spe-cific version. However, the name system.bundle must be recognized as an alias to this implementation-defined name.

• The system bundle’s life cycle cannot be managed like normal bundles. Its life cycle methods must behave as follows:• start – Does nothing because the system bundle is already started.• stop – Returns immediately and shuts down the Framework on

another thread.• update – Returns immediately, then stops and restarts the Framework

on another thread.• uninstall – The Framework must throw a BundleException indicating

that the system bundle cannot be uninstalled.• See Framework Startup and Shutdown on page 96 for more information

about the starting and stopping of the Framework.• The system bundle’s Bundle.getHeaders method returns a Dict ionary

object with implementation-specific manifest headers. For example, the system bundle’s manifest file should contain an Export-Package header declaring which packages are to be exported by the Framework (for example, org .osg i . framework).

4.6 EventsThe OSGi Framework Life Cycle layer supports the following types of events:

• BundleEvent – Reports changes in the life cycle of bundles.• FrameworkEvent – Reports that the Framework is started, start level has

changed, packages have been refreshed, or that an error has been encountered.

The actual event that is reported is available with the getType method. The integer that is returned from this method can be one of the constant names that are described in the class. However, events can, and will be, extended in the future. Unrecognized event types should be ignored.

4.6.1 ListenersA listener interface is associated with each type of event. The following list describes these listeners.

• BundleListener and SynchronousBundleListener – Called with an event of type BundleEvent when a bundle’s life cycle information has been changed.SynchronousBundleListener objects are called synchronously during the processing of the event and must be called before any BundleListener object is called. The following events are sent by the Framework after it has moved to a different state:• INSTALLED – Sent after a bundle is installed.• RESOLVED– Sent when the Framework has resolved a bundle.• STARTING – Sent when the Framework is about to start a bundle. This

is only sent to SynchronousBundleListener objects.• STARTED – Sent when the Framework has started a bundle.

OSGi Service Platform Release 4 93-268

Page 102: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Events Life Cycle Layer Version 1.3

• STOPPING – Sent when the Framework is about to stop a bundle. This is only sent to SynchronousBundleL is tener objects.

• STOPPED– Sent when the Framework has stopped a bundle.• UNINSTALLED – Sent when the Framework has uninstalled a bundle• UNRESOLVED – Sent when the Framework detects that a bundle

becomes unresolved; this could happen when the bundle is refreshed or updated. When a set of bundles are refreshed using the Package Admin API then each bundle in the set must have an UNRESOLVED BundleEvent published. The UNRESOLVED BundleEvent must be published after all the bundles in the set have been stopped and, in the case of a synchronous bundle listener, before any of the bundles in the set are re-started. RESOLVED and UNRESOLVED do not have to paired.

• UPDATED – Sent after a bundle is updated.

• FrameworkLis tener – Called with an event of type FrameworkEvent . Framework events are of type:• ERROR – Important error that requires the immediate attention of an

operator.• INFO – General information that is of interest in special situations.• PACKAGES_REFRESHED – The Framework has refreshed the packages.• STARTED – The Framework has performed all initialization and is

running in normal mode.• STARTLEVEL_CHANGED – Is sent by the Framework after a new start

level has been set and processed.• WARNING – A warning to the operator that is not crucial but may

indicate a potential error situation.

BundleContext interface methods are defined which can be used to add and remove each type of listener.

Events can be asynchronously delivered, unless otherwise stated, meaning that they are not necessarily delivered by the same thread that generated the event. The thread used to call an event listener is not defined.

The Framework must publish a FrameworkEvent.ERROR if a callback to an event listener generates an unchecked exception - except when the callback happens while delivering a FrameworkEvent.ERROR (to prevent an infinite loop).

4.6.2 Delivering EventsIf the Framework delivers an event asynchronously, it must:

• Collect a snapshot of the listener list at the time the event is published (rather than doing so in the future just prior to event delivery), but before the event is delivered, so that listeners do not enter the list after the event happened.

• Ensure, at the time the snapshot is taken, that listeners on the list still belong to active bundles at the time the event is delivered.

94-268 OSGi Service Platform Release 4

Page 103: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 Events

If the Framework did not capture the current listener list when the event was published, but instead waited until just prior to event delivery, then the following error could occur: a bundle could have started and registered a listener, and then the bundle could see its own BundleEvent . INSTALLED event.

The following three scenarios illustrate this concept.

1. Scenario one event sequence:• Event A is published.• Listener 1 is registered.• Asynchronous delivery of Event A is attempted.Expected Behavior: Listener 1 must not receive Event A, because it was not registered at the time the event was published.

2. Scenario two event sequence:• Listener 2 is registered.• Event B is published.• Listener 2 is unregistered.• Asynchronous delivery of Event B is attempted.Expected Behavior: Listener 2 receives Event B, because Listener 2 was registered at the time Event B was published.

3. Scenario three event sequence:• Listener 3 is registered.• Event C is published.• The bundle that registered Listener 3 is stopped.• Asynchronous delivery of Event C is attempted.Expected Behavior: Listener 3 must not receive Event C, because its Bun-dle Context object is invalid.

4.6.3 Synchronization PitfallsGenerally, a bundle that calls a listener should not hold any Java monitors. This means that neither the Framework nor the originator of a synchronous event should be in a monitor when a callback is initiated.

The purpose of a Java monitor is to protect the update of data structures. This should be a small region of code that does not call any code the effect of which cannot be overseen. Calling the OSGi Framework from synchronized code can cause unexpected side effects. One of these side effects might be deadlock. A deadlock is the situation where two threads are blocked because they are waiting for each other.

Time-outs can be used to break deadlocks, but Java monitors do not have time-outs. Therefore, the code will hang forever until the system is reset (Java has deprecated all methods that can stop a thread). This type of dead-lock is prevented by not calling the Framework (or other code that might cause callbacks) in a synchronized block.

If locks are necessary when calling other code, use the Java monitor to create semaphores that can time-out and thus provide an opportunity to escape a deadlocked situation.

OSGi Service Platform Release 4 95-268

Page 104: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework Startup and Shutdown Life Cycle Layer Version 1.3

4.7 Framework Startup and ShutdownA Framework implementation must be started before any services can be provided. How a Framework should be started by the Operator is not detailed in this specification because it can differ for different implementa-tions. Some Framework implementations may provide command line options, and others may read startup information from a configuration file. In all cases, Framework implementations must perform all of the following actions in the given order.

4.7.1 StartupWhen the Framework is started, the following actions must occur:

1. Event handling is enabled. Events can now be delivered to listeners. Events are discussed in Events on page 93.

2. The system bundle enters the STARTING state. More information about the system bundle can be found in The System Bundle on page 92.

3. All installed bundles previously recorded as being started must be started as described in the Bundle .sta rt method. Any exceptions that occur during startup must be wrapped in a BundleExcept ion and then published as a Framework event of type FrameworkEvent.ERROR . Bun-dles and their different states are discussed in The Bundle Object on page81. If the Framework implements the optional Start Level specification, this behavior is different. See Start Level Service Specification on page 195.

4. The system bundle enters the ACTIVE state.

5. A Framework event of type FrameworkEvent.STARTED is broadcast.

4.7.2 ShutdownThe Framework will also need to be shut down on occasion. Shutdown can also be initiated by stopping the system bundle, covered in The System Bun-dle on page 92. When the Framework is shut down, the following actions must occur in the given order:

1. The system bundle enters the STOPPING state.

2. All ACTIVE bundles are stopped as described in the Bundle .stop method, except that their persistently recorded state indicates that they must be restarted when the Framework is next started. Any exceptions that occur during shutdown must be wrapped in a BundleException and then pub-lished as a Framework event of type FrameworkEvent.ERROR . If the Framework implements the optional Start Level specification, this behavior is different. See Start Level Service Specification on page 195.

3. Event handling is disabled.

96-268 OSGi Service Platform Release 4

Page 105: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 Security

4.8 Security

4.8.1 Admin PermissionThe Admin Permission is a permission used to grant the right to manage the Framework with the option to restrict this right to a subset of bundles, called targets. For example, an Operator can give a bundle the right to only manage bundles of a signer that has a subject name of ACME:

org.osgi.framework.AdminPermission("(signer=\*, o=ACME, c=us)", ... )

The actions of the Admin Permission are fine-grained. They allow the deployer to assign only the permissions that are necessary for a bundle. For example, an HTTP implementation could be granted access to all resources of all bundles.

org.osgi.framework.AdminPermission("*","resource" )

Code that needs to check Admin Permission must always use the construc-tor that takes a bundle as parameter: AdminPermiss ion(Bundle ,Str ing) with a single action. This is to ensure the fastest execution of the permission check.

For example, the implementation of the loadClass method must check that the caller has access to the class space:

public class BundleImpl implements Bundle {

Class loadClass(String name) {securityManager.checkPermission(

new AdminPermission(this,"class") );...

}}

When assigning permissions to the bundle via (Conditional) Permission Admin service, it is difficult for the administrator to have a priori knowl-edge of the bundle ID assigned to a bundle. In order to provide a more flexi-ble way to designate the bundle for an Admin Permission, (Conditional) Permission Admin must provide special support for creating AdminPermiss ion objects from a Permission Info object. When a Permission Info specifies an Admin Permission, the name parameter of the Permission Info must be a filter string. This filter has the same syntax as an OSGi filter but has special rules for wildcards in the location and signer attributes.

The filter can contain the following keys:

• id – The bundle ID of the designated bundle. For example:

(id=256)

• location – The location of a bundle. Filter wildcards for Strings are sup-ported, allowing the value to specify a set of bundles. For example:

OSGi Service Platform Release 4 97-268

Page 106: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Life Cycle Layer Version 1.3

(location=https://www.acme.com/download/*)

• signer – A Distinguished Name chain. See the Certificate Matching on page 23 for more information how Distinguished Names are matched. Wildcards in a DN are not matched according to the filter string rules, but according to the rules defined for a DN chain. The wildcard character (’*’ or \u002a) must be escaped with a backslash (’\’) to avoid being inter-preted as a filter wildcard. For example:

(signer=\*,o=ACME,c=NL)

• name – The symbolic name of a bundle. Filter wildcards for Strings are supported allowing the value to specify a set of bundles. A single sym-bolic name may also map to a set of bundles. For example:

(name=com.acme.*)

The complete filter can also be a single wildcard character (’*’ or \u002a). In that case all bundles must match.

4.8.1.1 Actions

The action parameter of Admin Permission will specify the subset of privi-leged administrative operations that are allowed by the Framework. The actions that are architected are listed in table Table 9. Future versions of the specification, as well as additional system services, can add additional actions. The given set should therefore not be assumed to be a closed set.

Table 9 Admin Permission actionsAction Used in

metadata Bundle.getHeadersBundle.getLocation

resource Bundle.getResourceBundle.getResourcesBundle.getEntryBundle.getEntryPathsBundle.findEntriesBundle resource/entry URL creation

class Bundle.loadClasslifecycle BundleContext.installBundle

Bundle.updateBundle.uninstall

execute Bundle.startBundle.stopStartLevel.setBundleStartLevel

listener BundleContext.addBundleListener for SynchronousBundleListenerBundleContext.removeBundleListener for SynchronousBundleListener

extensionLifecycle BundleContext.installBundle for extension bundlesBundle.update for extension bundlesBundle.uninstall for extension bundles

98-268 OSGi Service Platform Release 4

Page 107: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 Security

The special action "*" will represent all actions.

Each bundle must be given AdminPermission(<bundle identi f ier>, "resource,metadata,c lass" ) so that it can access its own resources. This is an implicit permission that must be automatically given to all bundles by the Framework.

The actions resolve and start leve l must use the system bundle as target.

The implementation of the AdminPermission class requires close integra-tion with the Framework implementation. However, an AdminPermission class accompanies the specification. Framework implementations can change this class if they so desire. However, the default implementation pro-vided must load a Framework implementation provided class when it is loaded. This class comes from the package named in the following property:

org.osgi.vendor.framework

The class named AdminPermiss ion in that package must be used to instanti-ate a new Permission object using the constructor with the same signature to which all the AdminPermission methods must delegate.

4.8.2 Using Signer for the TargetThe Admin Permission use the signer of the bundle to select a target. For example, a bundle could be granted the permission to perform life cycle operations on bundles signed by a particular principal.

Using the principal (signer) as target, the maintenance of the permission management can be significantly reduced because it is not necessary to con-figure for individual bundles: the signer is effectively used as a grouping mechanism. However, one must consider that signatures can be added by any part, thereby causing it to become eligible for management by bundles that have the permission to administrate specific signers.

Using multiple signers is both a feature as well as it is a possible threat. From a management perspective it is beneficial to be able to use signatures to handle the grouping. However, it can also be used to maliciously manage a trusted bundle.

For example a trusted bundle signed by T , could later have a signature added by an untrusted party U . This will grant the bundle the permissions of both T and U, which ordinarily is a desirable feature. However, If the permissions associated with signer U also allow the management of bundles signed by U , then U could unexpectedly gain the permission to manage this trusted bun-dle. For example, it could now sta rt and stop this trusted bundle. This unex-pected effect of becoming eligible to be managed should be carefully considered when multiple signers are used.

resolve PackageAdmin.refreshPackagesPackageAdmin.resolveBundles

startlevel StartLevel.setStartLevelStartLevel.setInitialBundleStartLevel

Table 9 Admin Permission actionsAction Used in

OSGi Service Platform Release 4 99-268

Page 108: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Life Cycle Layer Version 1.3

4.8.3 Privileged CallbacksThe following interfaces define bundle callbacks that are invoked by the Framework:

• BundleAct ivator• ServiceFactory• Bundle -, Service-, and FrameworkL is tener .

When any of these callbacks are invoked by the Framework, the bundle that caused the callback may still be on the stack. For example, when one bundle installs and then starts another bundle, the installer bundle may be on the stack when the BundleActivator.s tart method of the installed bundle is called. Likewise, when a bundle registers a service object, it may be on the stack when the Framework calls back the serviceChanged method of all qualifying ServiceListener objects.

Whenever any of these bundle callbacks try to access a protected resource or operation, the access control mechanism should consider not only the per-missions of the bundle receiving the callback, but also those of the Frame-work and any other bundles on the stack. This means that in these callbacks, bundle programmers normally would use doPr iv i leged calls around any methods protected by a permission check (such as getting or registering ser-vice objects).

In order to reduce the number of doPriv i leged calls by bundle programmers, the Framework must perform a doPr iv i leged call around any bundle call-backs. The Framework should have java.security .A l lPermission . Therefore, a bundle programmer can assume that the bundle is not further restricted except for its own permissions.

Bundle programmers do not need to use doPriv i leged calls in their imple-mentations of any callbacks registered with and invoked by the Framework.

For any other callbacks that are registered with a service object and there-fore get invoked by the service-providing bundle directly, doPriv i leged calls must be used in the callback implementation if the bundle’s own privileges are to be exercised. Otherwise, the callback must fail if the bundle that initi-ated the callback lacks the required permissions.

A framework must never load classes in a doPriv i leged region, but must instead use the current stack. This means that static initializers should never assume that they are privileged. Any privileged code in a static initial-izer must be guarded with a doPr iv i leged region in the static initializer.

4.9 References[34] The Standard for the Format of ARPA Internet Text Messages

STD 11, RFC 822, UDEL, August 1982http://www.ietf.org/rfc/rfc822.txt

[35] The Hypertext Transfer Protocol - HTTP/1.1RFC 2068 DEC, MIT/LCS, UC Irvine, January 1997 http://www.ietf.org/rfc/rfc2068.txt

[36] The Java 2 Platform API SpecificationStandard Edition, Sun Microsystems

100-268 OSGi Service Platform Release 4

Page 109: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Life Cycle Layer Version 1.3 References

http://java.sun.com/j2se

[37] The Java Language SpecificationSecond Edition, Sun Microsystems, 2000http://java.sun.com/docs/books/jls/index.html

[38] A String Representation of LDAP Search FiltersRFC 1960, UMich, 1996http://www.ietf.org/rfc/rfc1960.txt

[39] The Java Security Architecture for JDK 1.2Version 1.0, Sun Microsystems, October 1998

[40] The Java 2 Package Versioning Specificationhttp://java.sun.com/j2se/1.4/docs/guide/versioning/index.html

[41] Codes for the Representation of Names of Languages ISO 639, International Standards Organizationhttp://lcweb.loc.gov/standards/iso639-2/langhome.html

[42] Manifest Format http://java.sun.com/j2se/1.4/docs/guide/jar/jar.html#JAR%20Manifest

[43] W3C EBNFhttp://www.w3c.org/TR/REC-xml#sec-notation

[44] Lexical Structure Java Languagehttp://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html

[45] Interval Notationhttp://www.math.ohio-state.edu/courses/math104/interval.pdf

OSGi Service Platform Release 4 101-268

Page 110: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Life Cycle Layer Version 1.3

102-268 OSGi Service Platform Release 4

Page 111: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Introduction

5 Service LayerVersion 1.3

5.1 IntroductionThe OSGi Service Layer defines a dynamic collaborative model that is highly integrated with the Life Cycle Layer. The service model is a publish, find and bind model. A service is a normal Java object that is registered under one or more Java interfaces with the service registry. Bundles can reg-ister services, search for them, or receive notifications when their registra-tion state changes.

5.1.1 Essentials• Collaborative – The service layer must provide a mechanism for bundles

to publish, find, and bind to each other’s services without having a priori knowledge of those bundles.

• Dynamic – The service mechanism must be able to handle changes in the outside world and underlying structures directly.

• Secure – It must be possible to restrict access to services.• Reflective – Provide full access to the Service Layer’s internal state.• Versioning – Provide mechanisms that make it possible to handle the fact

that bundles and their services evolve over time.• Persistent Identifier – Provide a means for bundles to track services across

Framework restarts.

5.1.2 Entities• Service – An object registered with the service registry under one or more

interfaces together with properties. This object can be discovered and used by bundles.

• Service Registry – Holds the service registrations. • Service Reference – A reference to a service. Provides access to the service’s

properties but not the actual service object. The service object must be acquired through a bundle’s Bundle Context.

• Service Registration – The receipt provided when a service is registered. The service registration allows the update of the service properties and the unregistration of the service.

• Service Permission – The permission to use an interface name when regis-tering or using a service.

• Service Factory – A facility to let the registering bundle customize the service object for each using bundle.

• Service Listener – A listener to Service Events.• Service Event – An event holding information about the registration,

modification, or unregistration of a service object.• Filter – An object that implements a simple but powerful filter language.

It can select on properties.

OSGi Service Platform Release 4 103-268

Page 112: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Services Service Layer Version 1.3

• Invalid Syntax Exception – The exception thrown when a filter expression contains an error.

Figure 33 Class Diagram org.osgi . f ramework Service Layer

5.2 ServicesIn the OSGi Service Platform, bundles are built around a set of cooperating services available from a shared service registry. Such an OSGi service is defined semantically by its service interface and implemented as a service object.

The service interface should be specified with as few implementation details as possible. OSGi has specified many service interfaces for common needs and will specify more in the future.

The service object is owned by, and runs within, a bundle. This bundle must register the service object with the Framework service registry so that the service’s functionality is available to other bundles under control of the Framework.

Bundle Impl Service Impl

Object<<interface>>BundleContext

<<interface>>Service Registration

<<interface>>Service Listener

<<class>>Service Event

<<class>>Invalid Syntax Exception

Service Registry Impl

<<interface>>Service Reference

<<interface>>Service Factory

Service Factory Impl

<<interface>>Filter

registersservice

0,1

1

0,1

0..n 1

1

0..n0..n

1

1

1 1<<interface>>All Service Listener

104-268 OSGi Service Platform Release 4

Page 113: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Services

Dependencies between the bundle owning the service and the bundles using it are managed by the Framework. For example, when a bundle is stopped, all the services registered with the Framework by that bundle must be automatically unregistered.

The Framework maps services to their underlying service objects, and pro-vides a simple but powerful query mechanism that enables a bundle to request the services it needs. The Framework also provides an event mecha-nism so that bundles can receive events of services that are registered, modi-fied, or unregistered.

5.2.1 Service ReferencesIn general, registered services are referenced through Serv iceReference objects. This avoids creating unnecessary dynamic service dependencies between bundles when a bundle needs to know about a service but does not require the service object itself.

A ServiceReference object can be stored and passed on to other bundles without the implications of dependencies. When a bundle wishes to use the service, it can be obtained by passing the Serv iceReference object to BundleContext.getService(Serv iceReference) . See Locating Services on page 110.

A ServiceReference object encapsulates the properties and other meta-information about the service object it represents. This meta-information can be queried by a bundle to assist in the selection of a service that best suits its needs.

When a bundle queries the Framework service registry for services, the Framework must provide the requesting bundle with the ServiceReference objects of the requested services, rather than with the services themselves.

A Serv iceReference object may also be obtained from a ServiceRegistrat ion object.

A ServiceReference object is valid only as long as the service object is regis-tered. However, its properties must remain available as long as the ServiceReference object exists.

5.2.2 Service InterfacesA service interface is the specification of the service’s public methods.

In practice, a bundle developer creates a service object by implementing its service interface and registers the service with the Framework service regis-try. Once a bundle has registered a service object under an interface name, the associated service can be acquired by bundles under that interface name, and its methods can be accessed by way of its service interface. The Frame-work also supports registering service objects under a class name, so refer-ences to service interface in this specification can be interpreted to be an interface or class.

When requesting a service object from the Framework, a bundle can specify the name of the service interface that the requested service object must implement. In the request, the bundle may also specify a filter string to nar-row the search.

OSGi Service Platform Release 4 105-268

Page 114: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Services Service Layer Version 1.3

Many service interfaces are defined and specified by organizations such as the OSGi Alliance. A service interface that has been accepted as a standard can be implemented and used by any number of bundle developers.

5.2.3 Registering ServicesA bundle publishes a service by registering a service object with the Frame-work service registry. A service object registered with the Framework is exposed to other bundles installed in the OSGi environment.

Every registered service object has a unique ServiceRegis trat ion object, and has one or more ServiceReference objects that refer to it. These ServiceReference objects expose the registration properties of the service object, including the set of service interfaces they implement. The ServiceReference object can then be used to acquire a service object that implements the desired service interface.

The Framework permits bundles to register and unregister service objects dynamically. Therefore, a bundle is permitted to register service objects at any time during the STARTING , ACTIVE or STOPPING states.

A bundle registers a service object with the Framework by calling one of the BundleContext.reg isterService methods on its BundleContext object:

• reg is terService(Str ing,Object,Dict ionary) – For a service object regis-tered under a single service interface.

• reg is terService(Str ing[] ,Object,Dict ionary) – For a service object regis-tered under multiple service interfaces.

The names of the service interfaces under which a bundle wants to register its service are provided as arguments to the reg isterService methods. The Framework must ensure that the service object actually is an instance of each specified service interfaces, unless the object is a Service Factory. See Service Factory on page 113.

To perform this check, the Framework must load the Class object for each specified service interface from either the bundle or a shared package. For each Class object, Class. is Instance must be called and return true on the Class object with the service object as the argument.

The service object being registered may be further described by a Dictionary object, which contains the properties of the service as a collection of key/value pairs.

The service interface names under which a service object has been success-fully registered are automatically added to the service object’s properties under the key objectClass . This value must be set automatically by the Framework and any value provided by the bundle must be overridden.

If the service object is successfully registered, the Framework must return a ServiceRegist rat ion object to the caller. A service object can be unregistered only by the holder of its ServiceRegistrat ion object (see the unregister() method). Every successful service object registration must yield a unique ServiceRegist rat ion object even if the same service object is registered mul-tiple times.

106-268 OSGi Service Platform Release 4

Page 115: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Services

Using the ServiceRegis trat ion object is the only way to reliably change the service object’s properties after it has been registered (see setProper-t ies(Dictionary)). Modifying a service object’s Dictionary object after the service object is registered may not have any effect on the service’s proper-ties.

The process of registering a service object is subject to a permission check. The registering bundle must have ServicePermiss ion[< interface name>,REGISTER] to register the service object under all the service interfaces spec-ified. Otherwise, the service object must not be registered, and a SecurityException must be thrown.

5.2.4 Early Need for ServiceRegistration ObjectThe registration of a service object will cause all registered ServiceListener objects to be notified. This is a synchronous notification. This means that such a listener can get access to the service and call its methods before the reg isterService method has returned the ServiceRegis trat ion object. In cer-tain cases, access to the ServiceRegis trat ion object is necessary in such a callback. However, the registering bundle has not yet received the ServiceRegistrat ion object. Figure 34 on page 107 shows such a sequence.

Figure 34 Service Registration and registration

In a case as described previously, access to the registration object can be obtained via a ServiceFactory object. If a ServiceFactory object is registered, the Framework must call-back the registering bundle with the ServiceFactory method getService(Bundle ,ServiceRegistrat ion) . The required ServiceRegis trat ion object is passed as a parameter to this method.

5.2.5 Service PropertiesProperties hold information as key/value pairs. The key must be a Str ing object and the value should be a type recognized by Fi l ter objects (see Filters on page 112 for a list). Multiple values for the same key are supported with arrays ([]) and Vector objects.

The values of properties should be limited to primitive or standard Java types to prevent unwanted inter bundle dependencies. The Framework can-not detect dependencies that are created by the exchange of objects between bundles via the service properties.

T2T1

deliver event

get service

Framework (not a thread)In method

The registerService

registerService

callback

method has notreturned yet, so thereis no ServiceRegistration

return

return

object

OSGi Service Platform Release 4 107-268

Page 116: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Services Service Layer Version 1.3

The key of a property is not case sensitive. ObjectClass , OBJECTCLASS and objectclass all are the same property key. A Framework must return the key in ServiceReference.getPropertyKeys in exactly the same case as it was last set. When a Dict ionary object that contains keys that only differ in case is passed, the Framework must raise an exception.

The service properties are intended to provide information about the service object. The properties should not be used to participate in the actual func-tion of the service. Modifying the properties for the service registration is a potentially expensive operation. For example, a Framework may pre-pro-cess the properties into an index during registration to speed up later look-ups.

The Fi l ter interface supports complex filtering; it can be used to find match-ing service objects. Therefore, all properties share a single name space in the Framework service registry. As a result, it is important to use descriptive names or formal definitions of shorter names to prevent conflicts. Several OSGi specifications reserve parts of this name space. All properties starting with the prefix service . and the property objectClass are reserved for use by OSGi specifications.

Table 10 Standard Service Properties contains a list of pre-defined properties.

Table 10 Standard Service Properties

Property Key Type Constants Property Description

objectClass Str ing[] OBJECTCLASS The objectClass property contains the set of interface names under which a service object is registered with the Framework. The Frame-work must set this property auto-matically. The Framework must guarantee that when a service object is retrieved with BundleContext.getService(ServiceReference) , it can be cast to any of the interface names.

service.descript ion Str ing SERVICE_DESCRIPTION The service.descr ipt ion property is intended to be used as documenta-tion and is optional. Frameworks and bundles can use this property to provide a short description of a reg-istered service object. The purpose is mainly for debugging because there is no support for localization.

108-268 OSGi Service Platform Release 4

Page 117: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Services

5.2.6 Persistent Identifier (PID)The purpose of a Persistent Identifier (PID) is to identify a service across Framework restarts. Services that can reference the same underlying entity every time they are registered should therefore use a service property that contains a PID. The name of the service property for PID is defined as service.pid . The PID is a unique identifier for a service that persists over multiple invocations of the Framework. For a given service, the same PID should always be used. If the bundle is stopped and later started, the same PID must always be used.

The format of the PID should be:

pid ::= symbolic-name // See 1.4.2

A PID must be unique for each service. A bundle must not register multiple services with the same PID, nor should other bundles use the same PID. If this happens, it is an error condition.

service. id Long SERVICE_ ID Every registered service object is assigned a unique service. id by the Framework. This number is added to the service object’s properties. The Framework assigns a unique value to every registered service object that is larger than values pro-vided to all previously registered service objects.

service.pid Str ing SERVICE_PID The serv ice .pid property option-ally identifies a persistent, unique identifier for the service object. See Persistent Identifier (PID) on page109.

service .ranking Integer SERVICE_RANKING When registering a service object, a bundle may optionally specify a service .ranking number as one of the service object’s properties. If multiple qualifying service inter-faces exist, a service with the high-est SERVICE_RANKING number, or when equal to the lowest SERVICE_ID, determines which ser-vice object is returned by the Frame-work.

service .vendor Str ing SERVICE_VENDOR This optional property can be used by the bundle registering the ser-vice object to indicate the vendor.

Table 10 Standard Service Properties

Property Key Type Constants Property Description

OSGi Service Platform Release 4 109-268

Page 118: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Services Service Layer Version 1.3

5.2.7 Locating ServicesIn order to use a service object and call its methods, a bundle must first obtain a ServiceReference object. The BundleContext interface defines two methods a bundle can call to obtain ServiceReference objects from the Framework:

• getServiceReference(Str ing) – This method returns a Serv iceReference object to a service object that implements, and was registered under, the name of the service interface specified as Str ing . If multiple such service objects exist, the service object with the highest SERVICE_RANKING is returned. If there is a tie in ranking, the service object with the lowest SERVICE_ID (the service object that was registered first) is returned.

• getServiceReferences(Str ing,Str ing) – This method returns an array of ServiceReference objects that:• Implement and were registered under the given service interface.• Satisfy the search filter specified. The filter syntax is further

explained in Filters on page 112.

Both methods must return nul l if no matching service objects are returned. Otherwise, the caller receives one or more ServiceReference objects. These objects can be used to retrieve properties of the underlying service object, or they can be used to obtain the actual service object via the BundleContext object.

Both methods require that the caller has the required ServicePermission[<name>, GET] to get the service object for the specified service interface names. If the caller lacks the required permission, these methods must return nul l .

5.2.8 Getting Service PropertiesTo allow for interrogation of service objects, the ServiceReference interface defines these two methods:

• getPropertyKeys() – Returns an array of the property keys that are available.

• getProperty(Str ing) – Returns the value of a property.

Both of these methods must continue to provide information about the ref-erenced service object, even after it has been unregistered from the Frame-work. This requirement can be useful when a ServiceReference object is stored with the Log Service.

5.2.9 Getting Service ObjectsThe BundleContext object is used to obtain the actual service object so that the Framework can manage dependencies. If a bundle retrieves a service object, that bundle becomes dependent upon the life cycle of that registered service object. This dependency is tracked by the BundleContext object used to obtain the service object, and is one reason that it is important to be care-ful when sharing BundleContext objects with other bundles.

The method BundleContext .getService(ServiceReference) returns an object that implements the interfaces as defined by the objectC lass prop-erty.

110-268 OSGi Service Platform Release 4

Page 119: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Service Events

This method has the following characteristics:

• Returns nul l if the underlying service object has been unregistered.• Determines if the caller has ServicePermission[<inter face name>,GET] ,

to get the service object using at least one of the service interfaces under which the service was registered. This permission check is necessary so that ServiceReference objects can be passed around freely without com-promising security.

• Increments the usage count of the service object by one for this BundleContext object.

• If the service object does not implement the ServiceFactory interface, it is returned. Otherwise, if the bundle context’s usage count of the service object is one, the object is cast to a ServiceFactory object and the getService method is called to create a customized service object for the calling bundle which is then returned. Otherwise, a cached copy of this customized object is returned. See Service Factory on page 113 for more information about ServiceFactory objects.

5.2.10 Information About ServicesThe Bundle interface defines these two methods for returning information pertaining to service usage of the bundles:

• getRegis teredServ ices() – Returns the service objects that the bundle has registered with the Framework.

• getServicesInUse() – Returns the service objects that the bundle is using.

5.3 Service Events• ServiceEvent – Reports registration, unregistration, and property

changes for service objects. All events of this kind must be delivered syn-chronously. The type of the event is given by the getType() method, which returns an int . Event types can be extended in the future; unknown event types should be ignored.

• ServiceListener – Called with a Serv iceEvent when a service object has been registered or modified, or is in the process of unregistering. A security check must be performed for each registered listener when a ServiceEvent occurs. The listener must not be called unless the bundle which registered the listener has the required ServicePermission[<inter face name> ,GET] for at least one of the inter-faces under which the service object is registered.

A bundle that uses a service object should register a Serv iceListener object to track the availability of the service object, and take appropriate action when the service object is unregistering.

OSGi Service Platform Release 4 111-268

Page 120: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Stale References Service Layer Version 1.3

5.4 Stale ReferencesThe Framework must manage the dependencies between bundles. This management is, however, restricted to Framework structures. Bundles must listen to events generated by the Framework to clean up and remove stale references.

A stale reference is a reference to a Java object that belongs to the class loader of a bundle that is stopped or is associated with a service object that is unregistered. Standard Java does not provide any generic means to clean up stale references, and bundle developers must analyze their code carefully to ensure that stale references are deleted.

Stale references are potentially harmful because they hinder the Java gar-bage collector from harvesting the classes, and possibly the instances, of stopped bundles. This may result in significantly increased memory usage and can cause updating native code libraries to fail. Bundles using services are strongly recommended to use either the Service Tracker or Declarative Services.

Service developers can minimize the consequences of (but not completely prevent) stale references by using the following mechanisms:

• Implement service objects using the Serv iceFactory interface. The methods in the ServiceFactory interface simplify tracking bundles that use their service objects. See Service Factory on page 113.

• Use indirection in the service object implementations. Service objects handed out to other bundles should use a pointer to the actual service object implementation. When the service object becomes invalid, the pointer is set to nul l , effectively removing the reference to the actual service object.

The behavior of a service that becomes unregistered is undefined. Such ser-vices may continue to work properly or throw an exception at their discre-tion. This type of error should be logged.

5.5 FiltersThe Framework provides a Fi l ter interface, and uses a filter syntax in the getServiceReferences method that is defined in Filter Syntax on page 31. Fil-ter objects can be created by calling BundleContext .createFi l ter(Str ing) or FrameworkUti l .createFi l ter (St r ing) with the chosen filter string. The filter supports the following match methods:

• match(ServiceReference) – Match the properties of the Service Ref-erence performing key lookup in a case insensitive way.

• match(Dict ionary) – Match the entries in the given Dictionary object performing key lookup in a case insensitive way.

• matchCase(Dict ionary) – Match the entries in the given Dictionary object performing key lookup in a case sensitive way.

A F i lter object can be used numerous times to determine if the match argu-ment, a ServiceReference object or a Dictionary object, matches the filter string that was used to create the Fi l ter object.

112-268 OSGi Service Platform Release 4

Page 121: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Service Factory

This matching requires comparing the value string in the filter to a target object from the service properties or dictionary. This comparison can be exe-cuted with the Comparable interface if the target object’s class implements a constructor taking a single Str ing object and the class implements the Comparable interface. That is, if the target object is of class Target , the class Target must implement:

• A constructor Target(St r ing)• Implement the java. lang.Comparable interface

If the target object does not implement java. lang.Comparable , the =, ~=, <= >= operators must return only true when the objects are equal (using the equals(Object) method). The Target class does not need to be a public class.

The following example shows how a class can verify the ordering of an enu-meration with a filter.

public class B implements Comparable { String keys[] = {"bugs", "daffy", "elmer", "pepe"}; int index; public B(String s) { for ( index=0; index<keys.length; index++ ) if ( keys[index].equals(s) ) return; } public int compareTo( Object other ) { B vother = (B) other; return index - vother.index; } }

The class could be used with the following filter:

(!(enum>=elmer)) -> matches bugs and daffy

The Fi l ter. toString method must always return the filter string with unnec-essary white space removed.

5.6 Service FactoryA Service Factory allows customization of the service object that is returned when a bundle calls BundleContext .getServ ice(ServiceReference) .

Often, the service object that is registered by a bundle is returned directly. If, however, the service object that is registered implements the ServiceFac-tory interface, the Framework must call methods on this object to create a unique service object for each distinct bundle that gets the service.

When the service object is no longer used by a bundle – for example, when that bundle is stopped – then the Framework must notify the ServiceFactory object.

OSGi Service Platform Release 4 113-268

Page 122: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Releasing Services Service Layer Version 1.3

ServiceFactory objects help manage bundle dependencies that are not explicitly managed by the Framework. By binding a returned service object to the requesting bundle, the service can be notified when that bundle ceases to use the service, such as when it is stopped, and release resources associated with providing the service to that bundle.

The ServiceFactory interface defines the following methods:

• getService(Bundle ,ServiceRegis trat ion) – This method is called by the Framework if a call is made to BundleContext .getService and the fol-lowing are true:• The ServiceReference argument to BundleContext .getService refers

to a service object that implements the ServiceFactory interface.• The bundle’s usage count of that service object is zero; that is, the

bundle currently does not have any dependencies on the service object.

The call to BundleContext .getService must be routed by the Framework to this method, passing to it the Bundle object of the caller. The Frame-work must cache the mapping of the requesting bundle-to-service, and return the cached service object to the bundle on future calls to BundleContext .getService , as long as the requesting bundle's usage count of the service object is greater than zero.The Framework must check the service object returned by this method. If it is not an instance of all the classes named when the service factory was registered, nul l is returned to the caller that called getService . This check must be done as specified in Registering Services on page 106.

• ungetService(Bundle ,ServiceRegist rat ion,Object) – This method is called by the Framework if a call is made to BundleContext .ungetServ ice and the following are true:• The ServiceReference argument to BundleContext .ungetService

refers to a service object that implements the ServiceFactory inter-face.

• The bundle’s usage count for that service object must drop to zero after this call returns; that is, the bundle is about to release its last dependency on the service object.

The call to BundleContext .ungetService must be routed by the Frame-work to this method so the ServiceFactory object can release the service object previously created.Additionally, the cached copy of the previously created service object must be unreferenced by the Framework so it may be garbage collected.

5.7 Releasing ServicesIn order for a bundle to release a service object, it must remove the dynamic dependency on the bundle that registered the service object. The BundleContext interface defines a method to release service objects: ungetSer-vice(ServiceReference) . A ServiceReference object is passed as the argu-ment of this method.

This method returns a boolean value:

114-268 OSGi Service Platform Release 4

Page 123: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Unregistering Services

• fa lse if the bundle’s usage count of the service object is already zero when the method was called, or the service object has already been unregistered.

• t rue if the bundle’s usage count of the service object was more than zero before this method was called.

5.8 Unregistering ServicesThe ServiceRegistrat ion interface defines the unregis ter() method to unreg-ister the service object. This must remove the service object from the Frame-work service registry. The Serv iceReference object for this ServiceRegistrat ion object can no longer be used to access the service object.

The fact that this method is on the ServiceRegist rat ion object ensures that only the bundle holding this object can unregister the associated service object. The bundle that unregisters a service object, however, might not be the same bundle that registered it. As an example, the registering bundle could have passed the ServiceRegistrat ion object to another bundle, endow-ing that bundle with the responsibility of unregistering the service object. Passing ServiceRegist rat ion objects should be done with caution.

After ServiceRegis trat ion.unregis ter successfully completes, the service object must be:

• Completely removed from the Framework service registry. Therefore, ServiceReference objects obtained for that service object can no longer be used to access the service object. Calling BundleContext.getService method with the ServiceReference object must return nul l .

• Unregistered, even if other bundles had dependencies upon it. Bundles must be notified of the unregistration through the publishing of a ServiceEvent object of type ServiceEvent .UNREGISTERING . This event is sent synchronously in order to give bundles the opportunity to release the service object. After receiving an event of type ServiceEvent .UNREGISTERING , a bundle should release the service object and release any references it has to this object, so that the service object can be garbage collected by the Java VM.

• Released by all using bundles. For each bundle whose usage count for the service object remains greater than zero after all invoked ServiceListener objects have returned, the Framework must set the usage count to zero and release the service object.

5.9 Multiple Version Export ConsiderationsAllowing multiple bundles to export a package with a given name causes some complications for Framework implementers and bundle program-mers: The class name no longer uniquely identifies the exported class. This affects the service registry and permission checking.

OSGi Service Platform Release 4 115-268

Page 124: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Service Layer Version 1.3

5.9.1 Service RegistryBundles must not be exposed to services for which there are conflicting class loaders. A bundle that gets a service should be able to expect that it can safely cast the service object to any of the associated interfaces or classes under which the service was registered and that it can access. No ClassCastExceptions should occur because those interfaces do not come from the same class loader. The service registry must therefore ensure that bundles can only see services that are not incompatible with them. A service is not incompatible with the bundle getting the service when that bundle is not wired to another source class loader for this interface package than the bundle registering the service. That is, it is either wired to the same source class loader or it has no wire for that package at all.

It is paramount that bundles are not accidentally confronted with incom-patible services. Therefore, the following methods need to filter ServiceReference objects depending on the incompatibility of the inter-faces with the calling bundle. The bundle is identified by the used Bundle Context:

• getServiceReference(Str ing) – Only return a Service Reference that is not incompatible with the calling bundle for the specified interface.

• getServiceReferences(Str ing,Str ing) – Only return Service References that are not incompatible with the calling bundle for the specified interface.

The getA l lServiceReferences(Str ing,Str ing) provides access to the service registry without any compatibility restrictions. Services acquired through this method can cause Class Cast Exceptions for the correct class names.

The ServiceReference i sAssignableTo(Bundle,St r ing) method is also avail-able to test if the bundle that registered the service referenced by this Ser-viceReference and the specified bundle are both wired to same source for the specified interface.

5.9.2 Service EventsService events must only be delivered to event listeners that are not incom-patible with the Service Reference.

Some bundles need to listen to all service events regardless the compatibil-ity issues. A new type of ServiceListener is therefore added: Al lServiceLis-tener . This is a marker interface; it extends ServiceListener . Listeners that use this marker interface indicate to the Framework that they want to see all services, including services that are incompatible with them.

5.10 Security

5.10.1 Service PermissionA ServicePermiss ion has the following parameters.

• Interface Name – The interface name may end with a wildcard to match multiple interface names. (See java .secur ity .BasicPermiss ion for a dis-cussion of wildcards.)

116-268 OSGi Service Platform Release 4

Page 125: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Service Layer Version 1.3 Security

• Action – Supported actions are: • REGISTER – Indicates that the permission holder may register the ser-

vice object • GET – Indicates that the holder may get the service.

When an object is being registered as a service object using BundleContext .reg is terService , the registering bundle must have the ServicePermission to register all the named classes. See Registering Services on page 106.

When a Serv iceReference object is obtained from the service registry using BundleContext .getServiceReference or BundleContext.getServiceReferences, the calling bundle must have the required ServicePermiss ion[<inter face name> , GET] to get the service object with the named class. See Service References on page 105.

When a service object is obtained from a ServiceReference object using BundleContext .getService(ServiceReference) , the calling code must have the required ServicePermission[<name>, GET] to get the service object for at least one of the classes under which it was registered.

ServicePermission must be used as a filter for the service events received by the Service Listener, as well as for the methods to enumerate services, including Bundle .getRegis teredServices and Bundle.getServicesInUse . The Framework must assure that a bundle must not be able to detect the presence of a service that it does not have permission to access.

OSGi Service Platform Release 4 117-268

Page 126: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Service Layer Version 1.3

118-268 OSGi Service Platform Release 4

Page 127: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6 Framework APIVersion 1.3

6.1 org.osgi.frameworkThe OSGi Framework Package. Specification Version 1.3.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle’s manifest. For example:

Import-Package: org.osgi.framework;version=1.3

6.1.1 Summary• AdminPermission - Indicates the caller’s authority to perform specific

privileged administrative operations on or to get sensitive information about a bundle. [p.120]

• AllServiceListener - A ServiceEvent listener. [p.123]• Bundle - An installed bundle in the Framework. [p.123]• BundleActivator - Customizes the starting and stopping of a bundle.

[p.136]• BundleContext - A bundle’s execution context within the Framework.

[p.137]• BundleEvent - An event from the Framework describing a bundle life-

cycle change. [p.148]• BundleException - A Framework exception used to indicate that a

bundle lifecycle problem occurred. [p.149]• BundleListener - A BundleEvent listener. [p.150]• BundlePermission - A bundle’s authority to require or provide a bundle

or to receive or attach fragments. [p.151]• Configurable - Supports a configuration object. [p.152]• Constants - Defines standard names for the OSGi environment property,

service property, and Manifest header attribute keys. [p.153]• Filter - An RFC 1960-based Filter. [p.167]• FrameworkEvent - A general event from the Framework. [p.168]• FrameworkListener - A FrameworkEvent listener. [p.170]• FrameworkUtil - Framework Utility class. [p.170]• InvalidSyntaxException - A Framework exception. [p.171]• PackagePermission - A bundle’s authority to import or export a package.

[p.172]• ServiceEvent - An event from the Framework describing a service life-

cycle change. [p.173]• ServiceFactory - Allows services to provide customized service objects in

the OSGi environment. [p.175]• ServiceListener - A ServiceEvent listener. [p.176]• ServicePermission - Indicates a bundle’s authority to register or get a

service. [p.176]• ServiceReference - A reference to a service. [p.177]

OSGi Service Platform Release 4 119-268

Page 128: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

• ServiceRegistration - A registered service. [p.179]• SynchronousBundleListener - A synchronous BundleEvent listener.

[p.180]• Version - Version identifier for bundles and packages. [p.181]AdminPermission

6.1.2 public final class AdminPermissionextends BasicPermissionIndicates the caller’s authority to perform specific privileged administrative operations on or to get sensitive information about a bundle. The actions for this permission are:

Action Methodsclass Bundle.loadClassexecute Bundle.start

Bundle.stopStartLevel.setBundleStartLevel

extensionLifecycle BundleContext.installBundle forextension bundles

Bundle.update for extension bundlesBundle.uninstall for extension bundles

lifecycle BundleContext.installBundleBundle.updateBundle.uninstall

listener BundleContext.addBundleListener forSynchronousBundleListener

BundleContext.removeBundleListener forSynchronousBundleListener

metadata Bundle.getHeadersBundle.getLocation

resolve PackageAdmin.refreshPackagesPackageAdmin.resolveBundles

resource Bundle.getResourceBundle.getResourcesBundle.getEntryBundle.getEntryPathsBundle.findEntriesBundle resource/entry URL creation

startlevel StartLevel.setStartLevelStartLevel.setInitialBundleStartLevel

The special action “*” will represent all actions.

The name of this permission is a filter expression. The filter gives access to the following parameters:

• signer - A Distinguished Name chain used to sign a bundle. Wildcards in a DN are not matched according to the filter string rules, but according to the rules defined for a DN chain.

• location - The location of a bundle.• id - The bundle ID of the designated bundle.• name - The symbolic name of a bundle.CLASS

6.1.2.1 public static final String CLASS = “class”

The action string class (Value is “class”).

120-268 OSGi Service Platform Release 4

Page 129: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Since 1.3EXECUTE

6.1.2.2 public static final String EXECUTE = “execute”

The action string execute (Value is “execute”).

Since 1.3EXTENSIONLIFECYCLE

6.1.2.3 public static final String EXTENSIONLIFECYCLE = “extensionLifecycle”

The action string extensionLifecycle (Value is “extensionLifecycle”).

Since 1.3LIFECYCLE

6.1.2.4 public static final String LIFECYCLE = “lifecycle”

The action string lifecycle (Value is “lifecycle”).

Since 1.3LISTENER

6.1.2.5 public static final String LISTENER = “listener”

The action string listener (Value is “listener”).

Since 1.3METADATA

6.1.2.6 public static final String METADATA = “metadata”

The action string metadata (Value is “metadata”).

Since 1.3RESOLVE

6.1.2.7 public static final String RESOLVE = “resolve”

The action string resolve (Value is “resolve”).

Since 1.3RESOURCE

6.1.2.8 public static final String RESOURCE = “resource”

The action string resource (Value is “resource”).

Since 1.3STARTLEVEL

6.1.2.9 public static final String STARTLEVEL = “startlevel”

The action string startlevel (Value is “startlevel”).

Since 1.3AdminPermission()

6.1.2.10 public AdminPermission( )

Creates a new AdminPermission object that matches all bundles and has all actions. Equivalent to AdminPermission(”*”,”*”); AdminPermission(String,String)

6.1.2.11 public AdminPermission( String filter, String actions )

filter A filter expression that can use signer, location, id, and name keys. A value of “*” or null matches all bundle.

actions class, execute, extensionLifecycle, lifecycle, listener, metadata, resolve, re-source, or startlevel. A value of “*” or null indicates all actions

Create a new AdminPermission. This constructor must only be used to cre-ate a permission that is going to be checked.

Examples:

OSGi Service Platform Release 4 121-268

Page 130: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

(signer=\*,o=ACME,c=US)(&(signer=\*,o=ACME,c=US)(name=com.acme.*)(location=http://www.acme.com/bundles/*))(id>=1)

When a signer key is used within the filter expression the signer value must escape the special filter chars (’*’, ‘(’, ‘)’).

Null arguments are equivalent to “*”.AdminPermission(Bundle,String)

6.1.2.12 public AdminPermission( Bundle bundle, String actions )

bundle A bundle

actions class, execute, extensionLifecycle, lifecycle, listener, metadata, resolve, re-source, startlevel

Creates a new AdminPermission object to be used by the code that must check a Permission object.

Since 1.3equals(Object)

6.1.2.13 public boolean equals( Object obj )

obj The object being compared for equality with this object.

Determines the equality of two AdminPermission objects.

Returns true if obj is equivalent to this AdminPermission; false otherwise.getActions()

6.1.2.14 public String getActions( )

Returns the canonical string representation of the AdminPermission actions.

Always returns present AdminPermission actions in the following order: class, execute, extensionLifecycle, lifecycle, listener, metadata, resolve, resource, startlevel.

Returns Canonical string representation of the AdminPermission actions.hashCode()

6.1.2.15 public int hashCode( )

Returns the hash code value for this object.

Returns Hash code value for this object.implies(Permission)

6.1.2.16 public boolean implies( Permission p )

p The permission to interrogate.

Determines if the specified permission is implied by this object. This method throws an exception if the specified permission was not con-structed with a bundle.

This method returns true if the specified permission is an AdminPermission AND

• this object’s filter matches the specified permission’s bundle ID, bundle symbolic name, bundle location and bundle signer distinguished name chain OR

• this object’s filter is “*”

AND this object’s actions include all of the specified permission’s actions.

122-268 OSGi Service Platform Release 4

Page 131: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Special case: if the specified permission was constructed with “*” filter, then this method returns true if this object’s filter is “*” and this object’s actions include all of the specified permission’s actions

Returns true if the specified permission is implied by this object; false otherwise.

Throws RuntimeException – if specified permission was not constructed with a bundle or “*” newPermissionCollection()

6.1.2.17 public PermissionCollection newPermissionCollection( )

Returns a new PermissionCollection object suitable for storing AdminPer-missions.

Returns A new PermissionCollection object.AllServiceListener

6.1.3 public interface AllServiceListenerextends ServiceListenerA ServiceEvent listener.

AllServiceListener is a listener interface that may be implemented by a bun-dle developer.

An AllServiceListener object is registered with the Framework using the BundleContext.addServiceListener method. AllServiceListener objects are called with a ServiceEvent object when a service is registered, modified, or is in the process of unregistering.

ServiceEvent object delivery to AllServiceListener objects is filtered by the filter specified when the listener was registered. If the Java Runtime Envi-ronment supports permissions, then additional filtering is done. Service-Event objects are only delivered to the listener if the bundle which defines the listener object’s class has the appropriate ServicePermission to get the service using at least one of the named classes the service was registered under.

Unlike normal ServiceListener objects, AllServiceListener objects receive all ServiceEvent objects regardless of the whether the package source of the lis-tening bundle is equal to the package source of the bundle that registered the service. This means that the listener may not be able to cast the service object to any of its corresponding service interfaces if the service object is retrieved.

See Also ServiceEvent[p.173] , ServicePermission[p.176]

Since 1.3Bundle

6.1.4 public interface BundleAn installed bundle in the Framework.

A Bundle object is the access point to define the lifecycle of an installed bun-dle. Each bundle installed in the OSGi environment must have an associated Bundle object.

A bundle must have a unique identity, a long, chosen by the Framework. This identity must not change during the lifecycle of a bundle, even when the bundle is updated. Uninstalling and then reinstalling the bundle must create a new unique identity.

OSGi Service Platform Release 4 123-268

Page 132: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

A bundle can be in one of six states:

• UNINSTALLED [p.125]• INSTALLED [p.124]• RESOLVED [p.124]• STARTING [p.125]• STOPPING [p.125]• ACTIVE [p.124]

Values assigned to these states have no specified ordering; they represent bit values that may be ORed together to determine if a bundle is in one of the valid states.

A bundle should only execute code when its state is one of STARTING,ACTIVE, or STOPPING. An UNINSTALLED bundle can not be set to another state; it is a zombie and can only be reached because references are kept somewhere.

The Framework is the only entity that is allowed to create Bundle objects, and these objects are only valid within the Framework that created them.ACTIVE

6.1.4.1 public static final int ACTIVE = 32

This bundle is now running.

A bundle is in the ACTIVE state when it has been successfully started.

The value of ACTIVE is 0x00000020.INSTALLED

6.1.4.2 public static final int INSTALLED = 2

This bundle is installed but not yet resolved.

A bundle is in the INSTALLED state when it has been installed in the Frame-work but cannot run.

This state is visible if the bundle’s code dependencies are not resolved. The Framework may attempt to resolve an INSTALLED bundle’s code dependen-cies and move the bundle to the RESOLVED state.

The value of INSTALLED is 0x00000002.RESOLVED

6.1.4.3 public static final int RESOLVED = 4

This bundle is resolved and is able to be started.

A bundle is in the RESOLVED state when the Framework has successfully resolved the bundle’s dependencies. These dependencies include:

• The bundle’s class path from its Constants.BUNDLE_CLASSPATH [p.153] Manifest header.

• The bundle’s package dependencies from its Constants .EXPORT_PACKAGE [p.157] and Constants . IMPORT_PACKAGE [p.161] Manifest headers.

• The bundle’s required bundle dependencies from its Constants .REQUIRE_BUNDLE [p.162] Manifest header.

• A fragment bundle’s host dependency from its Constants .FRAGMENT_HOST [p.159] Manifest header.

124-268 OSGi Service Platform Release 4

Page 133: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Note that the bundle is not active yet. A bundle must be put in the RESOLVED state before it can be started. The Framework may attempt to resolve a bundle at any time.

The value of RESOLVED is 0x00000004.STARTING

6.1.4.4 public static final int STARTING = 8

This bundle is in the process of starting.

A bundle is in the STARTING state when the start [p.131] method is active. A bundle must be in this state when the bundle’s BundleAct ivator .sta rt [p.136] is called. If this method completes without exception, then the bundle has successfully started and must move to the ACTIVE state.

The value of STARTING is 0x00000008.STOPPING

6.1.4.5 public static final int STOPPING = 16

This bundle is in the process of stopping.

A bundle is in the STOPPING state when the stop [p.132] method is active. A bundle must be in this state when the bundle’s BundleAct ivator .stop [p.136] method is called. When this method completes the bundle is stopped and must move to the RESOLVED state.

The value of STOPPING is 0x00000010.UNINSTALLED

6.1.4.6 public static final int UNINSTALLED = 1

This bundle is uninstalled and may not be used.

The UNINSTALLED state is only visible after a bundle is uninstalled; the bundle is in an unusable state but references to the Bundle object may still be available and used for introspection.

The value of UNINSTALLED is 0x00000001.findEntries(String,String,boolean)

6.1.4.7 public Enumeration findEntries( String path, String filePattern, boolean recurse )

path The path name in which to look. A specified path of “/” indicates the root of the bundle. Path is relative to the root of the bundle and must not be null.

filePattern The file name pattern for selecting entries in the specified path. The pattern is only matched against the last element of the entry path and it supports substring matching, as specified in the Filter specification, using the wild-card character (”*”). If null is specified, this is equivalent to “*” and matches all files.

recurse If true, recurse into subdirectories. Otherwise only return entries from the given directory.

Returns entries in this bundle and its attached fragments. The bundle’s classloader is not used to search for entries. Only the contents of the bundle and its attached fragments are searched for the specified entries. If this bun-dle’s state is INSTALLED, this method must attempt to resolve the bundle before attempting to find entries.

OSGi Service Platform Release 4 125-268

Page 134: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

This method is intended to be used to obtain configuration, setup, localiza-tion and other information from this bundle. This method takes into account that the “contents” of this bundle can be extended with fragments. This “bundle space” is not a namespace with unique members; the same entry name can be present multiple times. This method therefore returns an enumeration of URL objects. These URLs can come from different JARs but have the same path name. This method can either return only entries in the specified path or recurse into subdirectories returning entries in the direc-tory tree beginning at the specified path. Fragments can be attached after this bundle is resolved, possibly changing the set of URLs returned by this method. If this bundle is not resolved, only the entries in the JAR file of this bundle are returned.

Examples:

// List all XML files in the OSGI-INF directory and belowEnumeration e = b.findEntries(”OSGI-INF”, “*.xml”, true);

// Find a specific localization fileEnumeration e = b.findEntries(”OSGI-INF/l10n”,

“bundle_nl_DU.properties”,false);

if (e.hasMoreElements())return (URL) e.nextElement();

Returns An enumeration of URL objects for each matching entry, or null if an entry could not be found or if the caller does not have the appropriate AdminPer-mission[this,RESOURCE], and the Java Runtime Environment supports per-missions. The URLs are sorted such that entries from this bundle are returned first followed by the entries from attached fragments in ascending bundle id order. If this bundle is a fragment, then only matching entries in this fragment are returned.

Since 1.3getBundleId()

6.1.4.8 public long getBundleId( )

Returns this bundle’s identifier. The bundle is assigned a unique identifier by the Framework when it is installed in the OSGi environment.

A bundle’s unique identifier has the following attributes:

• Is unique and persistent. • Is a long. • Its value is not reused for another bundle, even after the bundle is unin-

stalled. • Does not change while the bundle remains installed. • Does not change when the bundle is updated.

This method must continue to return this bundle’s unique identifier while this bundle is in the UNINSTALLED state.

Returns The unique identifier of this bundle.getEntry(String)

6.1.4.9 public URL getEntry( String name )

name The name of the entry. See java.lang.ClassLoader.getResource for a descrip-tion of the format of a resource name.

126-268 OSGi Service Platform Release 4

Page 135: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Returns a URL to the specified entry in this bundle. The bundle’s classloader is not used to search for the specified entry. Only the contents of the bundle is searched for the specified entry. A specified path of “/” indicates the root of the bundle.

Returns A URL to the specified entry, or null if no entry could be found or if the caller does not have the appropriate AdminPermission[this,RESOURCE] and the Java Runtime Environment supports permissions.

Throws IllegalStateException – If this bundle has been uninstalled.

Since 1.3getEntryPaths(String)

6.1.4.10 public Enumeration getEntryPaths( String path )

path The path name for which to return entry paths.

Returns an Enumeration of all the paths (String objects) to entries within the bundle whose longest sub-path matches the supplied path argument. The bundle’s classloader is not used to search for entries. Only the contents of the bundle is searched. A specified path of “/” indicates the root of the bundle.

Returned paths indicating subdirectory paths end with a “/”. The returned paths are all relative to the root of the bundle.

Returns An Enumeration of the entry paths (String objects) or null if no entry could be found or if the caller does not have the appropriate AdminPermis-sion[this,RESOURCE] and the Java Runtime Environment supports permis-sions.

Throws IllegalStateException – If this bundle has been uninstalled.

Since 1.3getHeaders()

6.1.4.11 public Dictionary getHeaders( )

Returns this bundle’s Manifest headers and values. This method returns all the Manifest headers and values from the main section of the bundle’s Man-ifest file; that is, all lines prior to the first blank line.

Manifest header names are case-insensitive. The methods of the returned Dictionary object must operate on header names in a case-insensitive man-ner. If a Manifest header value starts with “%”, it must be localized accord-ing to the default locale.

For example, the following Manifest headers and values are included if they are present in the Manifest file:

Bundle-NameBundle-VendorBundle-VersionBundle-DescriptionBundle-DocURLBundle-ContactAddress

This method must continue to return Manifest header information while this bundle is in the UNINSTALLED state.

Returns A Dictionary object containing this bundle’s Manifest headers and values.

OSGi Service Platform Release 4 127-268

Page 136: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Throws SecurityException – If the caller does not have the appropriate AdminPer-mission[this,METADATA], and the Java Runtime Environment supports per-missions.

See Also Constants.BUNDLE_LOCALIZATION[p.154]getHeaders(String)

6.1.4.12 public Dictionary getHeaders( String locale )

locale The locale name into which the header values are to be localized. If the spec-ified locale is null then the locale returned by java.util.Locale.getDefault is used. If the specified locale is the empty string, this method will return the raw (unlocalized) manifest headers including any leading “%”.

Returns this bundle’s Manifest headers and values localized to the specifed locale.

This method performs the same function as Bundle.getHeaders() except the manifest header values are localized to the specified locale. If a Manifest header value starts with “%”, it must be localized according to the specified locale. If the specified locale cannot be found, then the header values must be returned using the default locale. If null is specified as the locale string, the header values must be localized using the default locale. If the empty string (””) is specified as the locale string, the header values must not be localized and the raw (unlocalized) header values, including any leading “%”, must be returned.

This method must continue to return Manifest header information while this bundle is in the UNINSTALLED state, however the header values must only be available in the raw and default locale values.

Returns A Dictionary object containing this bundle’s Manifest headers and values.

Throws SecurityException – If the caller does not have the appropriate AdminPer-mission[this,METADATA], and the Java Runtime Environment supports per-missions.

See Also getHeaders()[p.127] , Constants.BUNDLE_LOCALIZATION[p.154]

Since 1.3getLastModified()

6.1.4.13 public long getLastModified( )

Returns the time when this bundle was last modified. A bundle is consid-ered to be modified when it is installed, updated or uninstalled.

The time value is the number of milliseconds since January 1, 1970, 00:00:00 GMT.

Returns The time when this bundle was last modified.

Since 1.3getLocation()

6.1.4.14 public String getLocation( )

Returns this bundle’s location identifier.

The bundle location identifier is the location passed to BundleCon-text.installBundle when a bundle is installed. The bundle location identifier does not change while the bundle remains installed, even if the bundle is updated.

128-268 OSGi Service Platform Release 4

Page 137: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

This method must continue to return this bundle’s location identifier while this bundle is in the UNINSTALLED state.

Returns The string representation of this bundle’s location identifier.

Throws SecurityException – If the caller does not have the appropriate AdminPer-mission[this,METADATA], and the Java Runtime Environment supports per-missions. getRegisteredServices()

6.1.4.15 public ServiceReference[] getRegisteredServices( )

Returns this bundle’s ServiceReference list for all services it has registered or null if this bundle has no registered services.

If the Java runtime supports permissions, a ServiceReference object to a ser-vice is included in the returned list only if the caller has the ServicePermis-sion to get the service using at least one of the named classes the service was registered under.

The list is valid at the time of the call to this method, however, as the Frame-work is a very dynamic environment, services can be modified or unregis-tered at anytime.

Returns An array of ServiceReference objects or null.

Throws IllegalStateException – If this bundle has been uninstalled.

See Also ServiceRegistration[p.179] , ServiceReference[p.177] , ServicePermission[p.176]getResource(String)

6.1.4.16 public URL getResource( String name )

name The name of the resource. See java.lang.ClassLoader.getResource for a de-scription of the format of a resource name.

Find the specified resource from this bundle. This bundle’s class loader is called to search for the named resource. If this bundle’s state is INSTALLED, then only this bundle must be searched for the specified resource. Imported packages cannot be searched when a bundle has not been resolved. If this bundle is a fragment bundle then null is returned.

Returns A URL to the named resource, or null if the resource could not be found or if this bundle is a fragment bundle or if the caller does not have the appropriate AdminPermission[this,RESOURCE], and the Java Runtime Environment supports permissions.

Throws IllegalStateException – If this bundle has been uninstalled.

Since 1.1getResources(String)

6.1.4.17 public Enumeration getResources( String name ) throws IOException

name The name of the resource. See java.lang.ClassLoader.getResources for a de-scription of the format of a resource name.

Find the specified resources from this bundle. This bundle’s class loader is called to search for the named resource. If this bundle’s state is INSTALLED, then only this bundle must be searched for the specified resource. Imported packages cannot be searched when a bundle has not been resolved. If this bundle is a fragment bundle then null is returned.

OSGi Service Platform Release 4 129-268

Page 138: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Returns An enumeration of URLs to the named resources, or null if the resource could not be found or if this bundle is a fragment bundle or if the caller does not have the appropriate AdminPermission[this,RESOURCE], and the Java Runt-ime Environment supports permissions.

Throws IllegalStateException – If this bundle has been uninstalled.

IOException – If there is an I/O error.

Since 1.3getServicesInUse()

6.1.4.18 public ServiceReference[] getServicesInUse( )

Returns this bundle’s ServiceReference list for all services it is using or returns null if this bundle is not using any services. A bundle is considered to be using a service if its use count for that service is greater than zero.

If the Java Runtime Environment supports permissions, a ServiceReference object to a service is included in the returned list only if the caller has the ServicePermission to get the service using at least one of the named classes the service was registered under.

The list is valid at the time of the call to this method, however, as the Frame-work is a very dynamic environment, services can be modified or unregis-tered at anytime.

Returns An array of ServiceReference objects or null.

Throws IllegalStateException – If this bundle has been uninstalled.

See Also ServiceReference[p.177] , ServicePermission[p.176]getState()

6.1.4.19 public int getState( )

Returns this bundle’s current state.

A bundle can be in only one state at any time.

Returns An element of UNINSTALLED,INSTALLED, RESOLVED,STARTING, STOP-PING,ACTIVE.getSymbolicName()

6.1.4.20 public String getSymbolicName( )

Returns the symbolic name of this bundle as specified by its Bundle-Symbol-icName manifest header. The name must be unique, it is recommended to use a reverse domain name naming convention like that used for java pack-ages. If the bundle does not have a specified symbolic name then null is returned.

This method must continue to return this bundle’s symbolic name while this bundle is in the UNINSTALLED state.

Returns The symbolic name of this bundle.

Since 1.3hasPermission(Object)

6.1.4.21 public boolean hasPermission( Object permission )

permission The permission to verify.

Determines if this bundle has the specified permissions.

If the Java Runtime Environment does not support permissions, this method always returns true.

130-268 OSGi Service Platform Release 4

Page 139: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

permission is of type Object to avoid referencing the java.security.Permis-sion class directly. This is to allow the Framework to be implemented in Java environments which do not support permissions.

If the Java Runtime Environment does support permissions, this bundle and all its resources including embedded JAR files, belong to the same java.secu-rity.ProtectionDomain; that is, they must share the same set of permissions.

Returns true if this bundle has the specified permission or the permissions possessed by this bundle imply the specified permission; false if this bundle does not have the specified permission or permission is not an instanceofjava.securi-ty.Permission.

Throws IllegalStateException – If this bundle has been uninstalled. loadClass(String)

6.1.4.22 public Class loadClass( String name ) throws ClassNotFoundException

name The name of the class to load.

Loads the specified class using this bundle’s classloader.

If the bundle is a fragment bundle then this method must throw a ClassNot-FoundException.

If this bundle’s state is INSTALLED, this method must attempt to resolve the bundle before attempting to load the class.

If the bundle cannot be resolved, a Framework event of type FrameworkEvent .ERROR [p.168] is fired containing a BundleException with details of the reason the bundle could not be resolved. This method must then throw a ClassNotFoundException.

If this bundle’s state is UNINSTALLED, then an IllegalStateException is thrown.

Returns The Class object for the requested class.

Throws ClassNotFoundException – If no such class can be found or if this bundle is a fragment bundle or if the caller does not have the appropriate AdminPer-mission[this,CLASS], and the Java Runtime Environment supports permis-sions.

IllegalStateException – If this bundle has been uninstalled.

Since 1.3start()

6.1.4.23 public void start( ) throws BundleException

Starts this bundle.

If the Framework implements the optional Start Level service and the cur-rent start level is less than this bundle’s start level, then the Framework must persistently mark this bundle as started and delay the starting of this bundle until the Framework’s current start level becomes equal or more than the bundle’s start level.

Otherwise, the following steps are required to start a bundle:

1 If this bundle’s state is UNINSTALLED then an IllegalStateException is thrown.

2 If this bundle’s state is STARTING or STOPPING then this method must wait for this bundle to change state before continuing. If this does not

OSGi Service Platform Release 4 131-268

Page 140: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

occur in a reasonable time, a BundleException is thrown to indicate this bundle was unable to be started.

3 If this bundle’s state is ACTIVE then this method returns immediately. 4 Persistently record that this bundle has been started. When the

Framework is restarted, this bundle must be automatically started. 5 If this bundle’s state is not RESOLVED, an attempt is made to resolve this

bundle’s package dependencies. If the Framework cannot resolve this bundle, a BundleException is thrown.

6 This bundle’s state is set to STARTING. 7 A bundle event of type BundleEvent.STARTING [p.148] is fired. This

event is only delivered to SynchronousBundleListeners. It is not delivered to BundleListeners.

8 The BundleAct ivator .sta rt [p.136] method of this bundle’s BundleActi-vator, if one is specified, is called. If the BundleActivator is invalid or throws an exception, this bundle’s state is set back to RESOLVED. Any services registered by the bundle must be unregistered. Any services used by the bundle must be released. Any listeners registered by the bundle must be removed. A BundleException is then thrown.

9 If this bundle’s state is UNINSTALLED, because the bundle was unin-stalled while the BundleActivator.start method was running, a Bundle-Exception is thrown.

10 This bundle’s state is set to ACTIVE. 11 A bundle event of type BundleEvent.STARTED [p.148] is fired.

Preconditions

• getState() in {INSTALLED}, { RESOLVED}.

Postconditions, no exceptions thrown

• Bundle persistent state is marked as active. • getState() in {ACTIVE}. • BundleActivator.start() has been called and did not throw an exception.

Postconditions, when an exception is thrown

• Depending on when the exception occurred, bundle persistent state is marked as active.

• getState() not in {STARTING}, { ACTIVE}.

Throws BundleException – If this bundle could not be started. This could be be-cause a code dependency could not be resolved or the specified BundleActi-vator could not be loaded or threw an exception.

IllegalStateException – If this bundle has been uninstalled or this bun-dle tries to change its own state.

SecurityException – If the caller does not have the appropriate AdminPer-mission[this,EXECUTE], and the Java Runtime Environment supports per-missions. stop()

6.1.4.24 public void stop( ) throws BundleException

Stops this bundle.

The following steps are required to stop a bundle:

132-268 OSGi Service Platform Release 4

Page 141: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

1 If this bundle’s state is UNINSTALLED then an IllegalStateException is thrown.

2 If this bundle’s state is STARTING or STOPPING then this method must wait for this bundle to change state before continuing. If this does not occur in a reasonable time, a BundleException is thrown to indicate this bundle was unable to be stopped.

3 Persistently record that this bundle has been stopped. When the Framework is restarted, this bundle must not be automatically started.

4 If this bundle’s state is not ACTIVE then this method returns immedi-ately.

5 This bundle’s state is set to STOPPING. 6 A bundle event of type BundleEvent .STOPPING [p.149] is fired. This

event is only delivered to SynchronousBundleListeners. It is not delivered to BundleListeners.

7 The BundleAct ivator .stop [p.136] method of this bundle’s BundleActi-vator, if one is specified, is called. If that method throws an exception, this method must continue to stop this bundle. A BundleException must be thrown after completion of the remaining steps.

8 Any services registered by this bundle must be unregistered. 9 Any services used by this bundle must be released. 10 Any listeners registered by this bundle must be removed. 11 If this bundle’s state is UNINSTALLED, because the bundle was unin-

stalled while the BundleActivator.stop method was running, a BundleEx-ception must be thrown.

12 This bundle’s state is set to RESOLVED. 13 A bundle event of type BundleEvent .STOPPED [p.148] is fired.

Preconditions

• getState() in {ACTIVE}.

Postconditions, no exceptions thrown

• Bundle persistent state is marked as stopped. • getState() not in {ACTIVE, STOPPING}. • BundleActivator.stop has been called and did not throw an exception.

Postconditions, when an exception is thrown

• Bundle persistent state is marked as stopped.

Throws BundleException – If this bundle’s BundleActivator could not be loaded or threw an exception.

IllegalStateException – If this bundle has been uninstalled or this bun-dle tries to change its own state.

SecurityException – If the caller does not have the appropriate AdminPer-mission[this,EXECUTE], and the Java Runtime Environment supports per-missions. uninstall()

6.1.4.25 public void uninstall( ) throws BundleException

Uninstalls this bundle.

This method causes the Framework to notify other bundles that this bundle is being uninstalled, and then puts this bundle into the UNINSTALLED state. The Framework must remove any resources related to this bundle that it is able to remove.

OSGi Service Platform Release 4 133-268

Page 142: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

If this bundle has exported any packages, the Framework must continue to make these packages available to their importing bundles until the Package-Admin.refreshPackages method has been called or the Framework is relaunched.

The following steps are required to uninstall a bundle:

1 If this bundle’s state is UNINSTALLED then an IllegalStateException is thrown.

2 If this bundle’s state is ACTIVE, STARTING or STOPPING, this bundle is stopped as described in the Bundle.stop method. If Bundle.stop throws an exception, a Framework event of type FrameworkEvent .ERROR [p.168] is fired containing the exception.

3 This bundle’s state is set to UNINSTALLED. 4 A bundle event of type BundleEvent.UNINSTALLED [p.149] is fired. 5 This bundle and any persistent storage area provided for this bundle by

the Framework are removed.

Preconditions

• getState() not in {UNINSTALLED}.

Postconditions, no exceptions thrown

• getState() in {UNINSTALLED}. • This bundle has been uninstalled.

Postconditions, when an exception is thrown

• getState() not in {UNINSTALLED}. • This Bundle has not been uninstalled.

Throws BundleException – If the uninstall failed. This can occur if another thread is attempting to change the bundle’s state and does not complete in a timely manner.

IllegalStateException – If this bundle has been uninstalled or this bun-dle tries to change its own state.

SecurityException – If the caller does not have the appropriate AdminPer-mission[this,LIFECYCLE], and the Java Runtime Environment supports per-missions.

See Also stop()[p.132]update()

6.1.4.26 public void update( ) throws BundleException

Updates this bundle.

If this bundle’s state is ACTIVE, it must be stopped before the update and started after the update successfully completes.

If the bundle being updated has exported any packages, these packages must not be updated. Instead, the previous package version must remain exported until the PackageAdmin.refreshPackages method has been has been called or the Framework is relaunched.

The following steps are required to update a bundle:

1 If this bundle’s state is UNINSTALLED then an IllegalStateException is thrown.

134-268 OSGi Service Platform Release 4

Page 143: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

2 If this bundle’s state is ACTIVE, STARTING or STOPPING, the bundle is stopped as described in the Bundle.stop method. If Bundle.stop throws an exception, the exception is rethrown terminating the update.

3 The download location of the new version of this bundle is determined from either the bundle’s Constants.BUNDLE_UPDATELOCATION [p.156] Manifest header (if available) or the bundle’s original location.

4 The location is interpreted in an implementation dependent manner, typically as a URL, and the new version of this bundle is obtained from this location.

5 The new version of this bundle is installed. If the Framework is unable to install the new version of this bundle, the original version of this bundle must be restored and a BundleException must be thrown after com-pletion of the remaining steps.

6 If the bundle has declared an Bundle-RequiredExecutionEnvironment header, then the listed execution environments must be verified against the installed execution environments. If they do not all match, the original version of this bundle must be restored and a BundleException must be thrown after completion of the remaining steps.

7 This bundle’s state is set to INSTALLED. 8 If the new version of this bundle was successfully installed, a bundle

event of type BundleEvent .UPDATED [p.149] is fired. 9 If this bundle’s state was originally ACTIVE, the updated bundle is

started as described in the Bundle.start method. If Bundle.start throws an exception, a Framework event of type FrameworkEvent .ERROR [p.168] is fired containing the exception.

Preconditions

• getState() not in {UNINSTALLED}.

Postconditions, no exceptions thrown

• getState() in {INSTALLED, RESOLVED,ACTIVE}. • This bundle has been updated.

Postconditions, when an exception is thrown

• getState() in {INSTALLED, RESOLVED,ACTIVE}. • Original bundle is still used; no update occurred.

Throws BundleException – If the update fails.

IllegalStateException – If this bundle has been uninstalled or this bun-dle tries to change its own state.

SecurityException – If the caller does not have the appropriate AdminPer-mission[this,LIFECYCLE] for both the current bundle and the updated bun-dle, and the Java Runtime Environment supports permissions.

See Also stop()[p.132] , start()[p.131]update(InputStream)

6.1.4.27 public void update( InputStream in ) throws BundleException

in The InputStream from which to read the new bundle.

Updates this bundle from an InputStream.

This method performs all the steps listed in Bundle.update(), except the bundle must be read from the supplied InputStream, rather than a URL.

OSGi Service Platform Release 4 135-268

Page 144: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

This method must always close the InputStream when it is done, even if an exception is thrown.

Throws BundleException – If the provided stream cannot be read or the update fails.

IllegalStateException – If this bundle has been uninstalled or this bun-dle tries to change its own state.

SecurityException – If the caller does not have the appropriate AdminPer-mission[this,LIFECYCLE] for both the current bundle and the updated bun-dle, and the Java Runtime Environment supports permissions.

See Also update()[p.134]BundleActivator

6.1.5 public interface BundleActivatorCustomizes the starting and stopping of a bundle.

BundleActivator is an interface that may be implemented when a bundle is started or stopped. The Framework can create instances of a bundle’s BundleActivator as required. If an instance’s BundleActivator.start method executes successfully, it is guaranteed that the same instance’s BundleActi-vator.stop method will be called when the bundle is to be stopped.

BundleActivator is specified through the Bundle-Activator Manifest header. A bundle can only specify a single BundleActivator in the Manifest file. Fragment bundles must not have a BundleActivator. The form of the Mani-fest header is:

Bundle-Activator: <i>class-name</i>

where class-name is a fully qualified Java classname.

The specified BundleActivator class must have a public constructor that takes no parameters so that a BundleActivator object can be created by Class.newInstance().start(BundleContext)

6.1.5.1 public void start( BundleContext context ) throws Exception

context The execution context of the bundle being started.

Called when this bundle is started so the Framework can perform the bun-dle-specific activities necessary to start this bundle. This method can be used to register services or to allocate any resources that this bundle needs.

This method must complete and return to its caller in a timely manner.

Throws Exception – If this method throws an exception, this bundle is marked as stopped and the Framework will remove this bundle’s listeners, unregister all services registered by this bundle, and release all services used by this bun-dle.

See Also Bundle.start[p.131]stop(BundleContext)

6.1.5.2 public void stop( BundleContext context ) throws Exception

context The execution context of the bundle being stopped.

136-268 OSGi Service Platform Release 4

Page 145: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Called when this bundle is stopped so the Framework can perform the bun-dle-specific activities necessary to stop the bundle. In general, this method should undo the work that the BundleActivator.start method started. There should be no active threads that were started by this bundle when this bun-dle returns. A stopped bundle must not call any Framework objects.

This method must complete and return to its caller in a timely manner.

Throws Exception – If this method throws an exception, the bundle is still marked as stopped, and the Framework will remove the bundle’s listeners, unregister all services registered by the bundle, and release all services used by the bun-dle.

See Also Bundle.stop[p.132]BundleContext

6.1.6 public interface BundleContextA bundle’s execution context within the Framework. The context is used to grant access to other methods so that this bundle can interact with the Framework.

BundleContext methods allow a bundle to:

• Subscribe to events published by the Framework. • Register service objects with the Framework service registry. • Retrieve ServiceReferences from the Framework service registry. • Get and release service objects for a referenced service. • Install new bundles in the Framework. • Get the list of bundles installed in the Framework. • Get the Bundle [p.123] object for a bundle. • Create File objects for files in a persistent storage area provided for the

bundle by the Framework.

A BundleContext object will be created and provided to the bundle associ-ated with this context when it is started using the BundleAct ivator .sta rt [p.136] method. The same BundleContext object will be passed to the bundle associated with this context when it is stopped using the BundleAct ivator .stop [p.136] method. A BundleContext object is generally for the private use of its associated bundle and is not meant to be shared with other bundles in the OSGi environment.

The Bundle object associated with a BundleContext object is called the con-text bundle.

The BundleContext object is only valid during the execution of its context bundle; that is, during the period from when the context bundle is in the STARTING, STOPPING, and ACTIVE bundle states. If the BundleContext object is used subsequently, an IllegalStateException must be thrown. The BundleContext object must never be reused after its context bundle is stopped.

The Framework is the only entity that can create BundleContext objects and they are only valid within the Framework that created them.addBundleListener(BundleListener)

6.1.6.1 public void addBundleListener( BundleListener listener )

listener The BundleListener to be added.

OSGi Service Platform Release 4 137-268

Page 146: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Adds the specified BundleListener object to the context bundle’s list of lis-teners if not already present. BundleListener objects are notified when a bundle has a lifecycle state change.

If the context bundle’s list of listeners already contains a listener l such that (l==listener), this method does nothing.

Throws IllegalStateException – If this BundleContext is no longer valid.

SecurityException – If listener is a SynchronousBundleListener and the caller does not have the appropriate AdminPermission[context bundle,LIS-TENER], and the Java Runtime Environment supports permissions.

See Also BundleEvent[p.148] , BundleListener[p.150]addFrameworkListener(FrameworkListener)

6.1.6.2 public void addFrameworkListener( FrameworkListener listener )

listener The FrameworkListener object to be added.

Adds the specified FrameworkListener object to the context bundle’s list of listeners if not already present. FrameworkListeners are notified of general Framework events.

If the context bundle’s list of listeners already contains a listener l such that (l==listener), this method does nothing.

Throws IllegalStateException – If this BundleContext is no longer valid.

See Also FrameworkEvent[p.168] , FrameworkListener[p.170]addServiceListener(ServiceListener,String)

6.1.6.3 public void addServiceListener( ServiceListener listener, String filter ) throws InvalidSyntaxException

listener The ServiceListener object to be added.

filter The filter criteria.

Adds the specified ServiceListener object with the specified filter to the con-text bundle’s list of listeners. See F il ter [p.167] for a description of the filter syntax. ServiceListener objects are notified when a service has a lifecycle state change.

If the context bundle’s list of listeners already contains a listener l such that (l==listener), then this method replaces that listener’s filter (which may be null) with the specified one (which may be null).

The listener is called if the filter criteria is met. To filter based upon the class of the service, the filter should reference the Constants.OBJECTCLASS [p.162] property. If filter is null, all services are considered to match the filter.

When using a filter, it is possible that the ServiceEvents for the complete lifecycle of a service will not be delivered to the listener. For example, if the filter only matches when the property x has the value 1, the listener will not be called if the service is registered with the property x not set to the value 1. Subsequently, when the service is modified setting property x to the value 1, the filter will match and the listener will be called with a ServiceEvent of type MODIFIED. Thus, the listener will not be called with a ServiceEvent of type REGISTERED.

138-268 OSGi Service Platform Release 4

Page 147: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

If the Java Runtime Environment supports permissions, the ServiceListener object will be notified of a service event only if the bundle that is registering it has the ServicePermission to get the service using at least one of the named classes the service was registered under.

Throws InvalidSyntaxException – If filter contains an invalid filter string that can-not be parsed.

IllegalStateException – If this BundleContext is no longer valid.

See Also ServiceEvent[p.173] , ServiceListener[p.176] , ServicePermission[p.176]addServiceListener(ServiceListener)

6.1.6.4 public void addServiceListener( ServiceListener listener )

listener The ServiceListener object to be added.

Adds the specified ServiceListener object to the context bundle’s list of lis-teners.

This method is the same as calling BundleContext.addServiceListener(Ser-viceListener listener, String filter) with filter set to null.

Throws IllegalStateException – If this BundleContext is no longer valid.

See Also addServiceListener(ServiceListener, String)[p.138]createFilter(String)

6.1.6.5 public Filter createFilter( String filter ) throws InvalidSyntaxException

filter The filter string.

Creates a Filter object. This Filter object may be used to match a ServiceRef-erence object or a Dictionary object.

If the filter cannot be parsed, an Inva lidSyntaxException [p.171] will be thrown with a human readable message where the filter became unpars-able.

Returns A Filter object encapsulating the filter string.

Throws InvalidSyntaxException – If filter contains an invalid filter string that can-not be parsed.

NullPointerException – If filter is null.

IllegalStateException – If this BundleContext is no longer valid.

See Also Framework specification for a description of the filter string syntax., FrameworkUtil.createFilter(String)[p.170]

Since 1.1getAllServiceReferences(String,String)

6.1.6.6 public ServiceReference[] getAllServiceReferences( String clazz, String filter ) throws InvalidSyntaxException

clazz The class name with which the service was registered or null for all services.

filter The filter criteria.

Returns an array of ServiceReference objects. The returned array of Service-Reference objects contains services that were registered under the specified class and match the specified filter criteria.

OSGi Service Platform Release 4 139-268

Page 148: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

The list is valid at the time of the call to this method, however since the Framework is a very dynamic environment, services can be modified or unregistered at anytime.

filter is used to select the registered service whose properties objects contain keys and values which satisfy the filter. See F il ter [p.167] for a description of the filter string syntax.

If filter is null, all registered services are considered to match the filter. If fil-ter cannot be parsed, an Inval idSyntaxExcept ion [p.171] will be thrown with a human readable message where the filter became unparsable.

The following steps are required to select a set of ServiceReference objects:

1 If the filter string is not null, the filter string is parsed and the set Service-Reference objects of registered services that satisfy the filter is produced. If the filter string is null, then all registered services are considered to satisfy the filter.

2 If the Java Runtime Environment supports permissions, the set of Ser-viceReference objects produced by the previous step is reduced by checking that the caller has the ServicePermission to get at least one of the class names under which the service was registered. If the caller does not have the correct permission for a particular ServiceReference object, then it is removed from the set.

3 If clazz is not null, the set is further reduced to those services that are an instanceof and were registered under the specified class. The complete list of classes of which a service is an instance and which were specified when the service was registered is available from the service’s Constants .OBJECTCLASS [p.162] property.

4 An array of the remaining ServiceReference objects is returned.

Returns An array of ServiceReference objects or null if no services are registered which satisfy the search.

Throws InvalidSyntaxException – If filter contains an invalid filter string that can-not be parsed.

IllegalStateException – If this BundleContext is no longer valid.

Since 1.3getBundle()

6.1.6.7 public Bundle getBundle( )

Returns the Bundle object associated with this BundleContext. This bundle is called the context bundle.

Returns The Bundle object associated with this BundleContext.

Throws IllegalStateException – If this BundleContext is no longer valid. getBundle(long)

6.1.6.8 public Bundle getBundle( long id )

id The identifier of the bundle to retrieve.

Returns the bundle with the specified identifier.

Returns A Bundle object or null if the identifier does not match any installed bundle.getBundles()

6.1.6.9 public Bundle[] getBundles( )

Returns a list of all installed bundles.

140-268 OSGi Service Platform Release 4

Page 149: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

This method returns a list of all bundles installed in the OSGi environment at the time of the call to this method. However, since the Framework is a very dynamic environment, bundles can be installed or uninstalled at any-time.

Returns An array of Bundle objects, one object per installed bundle.getDataFile(String)

6.1.6.10 public File getDataFile( String filename )

filename A relative name to the file to be accessed.

Creates a File object for a file in the persistent storage area provided for the bundle by the Framework. This method will return null if the platform does not have file system support.

A File object for the base directory of the persistent storage area provided for the context bundle by the Framework can be obtained by calling this method with an empty string as filename.

If the Java Runtime Environment supports permissions, the Framework will ensure that the bundle has the java.io.FilePermission with actions read,write,delete for all files (recursively) in the persistent storage area provided for the context bundle.

Returns A File object that represents the requested file or null if the platform does not have file system support.

Throws IllegalStateException – If this BundleContext is no longer valid. getProperty(String)

6.1.6.11 public String getProperty( String key )

key The name of the requested property.

Returns the value of the specified property. If the key is not found in the Framework properties, the system properties are then searched. The method returns null if the property is not found.

The Framework defines the following standard property keys:

• Constants .FRAMEWORK_VERSION [p.161] - The OSGi Framework version.

• Constants .FRAMEWORK_VENDOR [p.161] - The Framework implemen-tation vendor.

• Constants .FRAMEWORK_LANGUAGE [p.160] - The language being used. See ISO 639 for possible values.

• Constants .FRAMEWORK_OS_NAME [p.160] - The host computer oper-ating system.

• Constants .FRAMEWORK_OS_VERSION [p.160] - The host computer oper-ating system version number.

• Constants .FRAMEWORK_PROCESSOR [p.160] - The host computer pro-cessor name.

All bundles must have permission to read these properties.

Note: The last four standard properties are used by the Constants.BUNDLE_NATIVECODE [p.155] Manifest header’s matching algo-rithm for selecting native language code.

Returns The value of the requested property, or null if the property is undefined.

OSGi Service Platform Release 4 141-268

Page 150: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Throws SecurityException – If the caller does not have the appropriate PropertyP-ermission to read the property, and the Java Runtime Environment supports permissions. getService(ServiceReference)

6.1.6.12 public Object getService( ServiceReference reference )

reference A reference to the service.

Returns the specified service object for a service.

A bundle’s use of a service is tracked by the bundle’s use count of that ser-vice. Each time a service’s service object is returned by getService(ServiceReference) [p.142] the context bundle’s use count for that service is incremented by one. Each time the service is released by ungetService(Serv iceReference) [p.147] the context bundle’s use count for that service is decremented by one.

When a bundle’s use count for a service drops to zero, the bundle should no longer use that service.

This method will always return null when the service associated with this reference has been unregistered.

The following steps are required to get the service object:

1 If the service has been unregistered, null is returned. 2 The context bundle’s use count for this service is incremented by one. 3 If the context bundle’s use count for the service is currently one and the

service was registered with an object implementing the ServiceFactory interface, the ServiceFactory .getService(Bundle , ServiceRegis trat ion) [p.175] method is called to create a service object for the context bundle. This service object is cached by the Framework. While the context bundle’s use count for the service is greater than zero, subsequent calls to get the services’s service object for the context bundle will return the cached service object. If the service object returned by the ServiceFactory object is not an instanceof all the classes named when the service was registered or the ServiceFactory object throws an exception, null is returned and a Framework event of type FrameworkEvent.ERROR [p.168] is fired.

4 The service object for the service is returned.

Returns A service object for the service associated with reference or null if the service is not registered or does not implement the classes under which it was regis-tered in the case of a ServiceFactory.

Throws SecurityException – If the caller does not have the ServicePermission to get the service using at least one of the named classes the service was regis-tered under and the Java Runtime Environment supports permissions.

IllegalStateException – If this BundleContext is no longer valid.

See Also ungetService(ServiceReference)[p.147] , ServiceFactory[p.175]getServiceReference(String)

6.1.6.13 public ServiceReference getServiceReference( String clazz )

clazz The class name with which the service was registered.

Returns a ServiceReference object for a service that implements and was reg-istered under the specified class.

142-268 OSGi Service Platform Release 4

Page 151: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

This ServiceReference object is valid at the time of the call to this method, however as the Framework is a very dynamic environment, services can be modified or unregistered at anytime.

This method is the same as calling BundleContext.getServiceRefer-ences(Str ing, Str ing) [p.143] with a null filter string. It is provided as a con-venience for when the caller is interested in any service that implements the specified class.

If multiple such services exist, the service with the highest ranking (as spec-ified in its Constants .SERVICE_RANKING [p.164] property) is returned.

If there is a tie in ranking, the service with the lowest service ID (as specified in its Constants .SERVICE_ID [p.163] property); that is, the service that was registered first is returned.

Returns A ServiceReference object, or null if no services are registered which imple-ment the named class.

Throws IllegalStateException – If this BundleContext is no longer valid.

See Also getServiceReferences(String, String)[p.143]getServiceReferences(String,String)

6.1.6.14 public ServiceReference[] getServiceReferences( String clazz, String filter ) throws InvalidSyntaxException

clazz The class name with which the service was registered or null for all services.

filter The filter criteria.

Returns an array of ServiceReference objects. The returned array of Service-Reference objects contains services that were registered under the specified class, match the specified filter criteria, and the packages for the class names under which the services were registered match the context bundle’s pack-ages as defined in ServiceReference. isAssignableTo(Bundle , Str ing) [p.179] .

The list is valid at the time of the call to this method, however since the Framework is a very dynamic environment, services can be modified or unregistered at anytime.

filter is used to select the registered service whose properties objects contain keys and values which satisfy the filter. See F i lter [p.167] for a description of the filter string syntax.

If filter is null, all registered services are considered to match the filter. If fil-ter cannot be parsed, an Inval idSyntaxExcept ion [p.171] will be thrown with a human readable message where the filter became unparsable.

The following steps are required to select a set of ServiceReference objects:

1 If the filter string is not null, the filter string is parsed and the set Service-Reference objects of registered services that satisfy the filter is produced. If the filter string is null, then all registered services are considered to satisfy the filter.

2 If the Java Runtime Environment supports permissions, the set of Ser-viceReference objects produced by the previous step is reduced by checking that the caller has the ServicePermission to get at least one of the class names under which the service was registered. If the caller does not have the correct permission for a particular ServiceReference object, then it is removed from the set.

OSGi Service Platform Release 4 143-268

Page 152: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

3 If clazz is not null, the set is further reduced to those services that are an instanceof and were registered under the specified class. The complete list of classes of which a service is an instance and which were specified when the service was registered is available from the service’s Constants .OBJECTCLASS [p.162] property.

4 The set is reduced one final time by cycling through each ServiceRef-erence object and calling ServiceReference. isAssignableTo(Bundle , Str ing) [p.179] with the context bundle and each class name under which the ServiceReference object was registered. For any given ServiceRef-erence object, if any call to Serv iceReference. isAss ignableTo(Bundle, Str ing) [p.179] returns false, then it is removed from the set of ServiceRef-erence objects.

5 An array of the remaining ServiceReference objects is returned.

Returns An array of ServiceReference objects or null if no services are registered which satisfy the search.

Throws InvalidSyntaxException – If filter contains an invalid filter string that can-not be parsed.

IllegalStateException – If this BundleContext is no longer valid. installBundle(String)

6.1.6.15 public Bundle installBundle( String location ) throws BundleException

location The location identifier of the bundle to install.

Installs a bundle from the specified location string. A bundle is obtained from location as interpreted by the Framework in an implementation dependent manner.

Every installed bundle is uniquely identified by its location string, typically in the form of a URL.

The following steps are required to install a bundle:

1 If a bundle containing the same location string is already installed, the Bundle object for that bundle is returned.

2 The bundle’s content is read from the location string. If this fails, a BundleException [p.149] is thrown.

3 The bundle’s Bundle-NativeCode dependencies are resolved. If this fails, a BundleException is thrown.

4 The bundle’s associated resources are allocated. The associated resources minimally consist of a unique identifier and a persistent storage area if the platform has file system support. If this step fails, a BundleException is thrown.

5 If the bundle has declared an Bundle-RequiredExecutionEnvironment header, then the listed execution environments must be verified against the installed execution environments. If they are not all present, a BundleException must be thrown.

6 The bundle’s state is set to INSTALLED. 7 A bundle event of type BundleEvent. INSTALLED [p.148] is fired. 8 The Bundle object for the newly or previously installed bundle is

returned.

Postconditions, no exceptions thrown

• getState() in {INSTALLED,RESOLVED}. • Bundle has a unique ID.

144-268 OSGi Service Platform Release 4

Page 153: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Postconditions, when an exception is thrown

• Bundle is not installed and no trace of the bundle exists.

Returns The Bundle object of the installed bundle.

Throws BundleException – If the installation failed.

SecurityException – If the caller does not have the appropriate AdminPer-mission[installed bundle,LIFECYCLE], and the Java Runtime Environment supports permissions.

IllegalStateException – If this BundleContext is no longer valid. installBundle(String,InputStream)

6.1.6.16 public Bundle installBundle( String location, InputStream input ) throws BundleException

location The location identifier of the bundle to install.

input The InputStream object from which this bundle will be read.

Installs a bundle from the specified InputStream object.

This method performs all of the steps listed in BundleContext.installBun-dle(String location), except that the bundle’s content will be read from the InputStream object. The location identifier string specified will be used as the identity of the bundle.

This method must always close the InputStream object, even if an exception is thrown.

Returns The Bundle object of the installed bundle.

Throws BundleException – If the provided stream cannot be read or the installation failed.

SecurityException – If the caller does not have the appropriate AdminPer-mission[installed bundle,LIFECYCLE], and the Java Runtime Environment supports permissions.

IllegalStateException – If this BundleContext is no longer valid.

See Also installBundle(java.lang.String)[p.144]registerService(String[],Object,Dictionary)

6.1.6.17 public ServiceRegistration registerService( String[] clazzes, Object service, Dictionary properties )

clazzes The class names under which the service can be located. The class names in this array will be stored in the service’s properties under the key Constants.OBJECTCLASS [p.162] .

service The service object or a ServiceFactory object.

properties The properties for this service. The keys in the properties object must all be String objects. See Constants [p.153] for a list of standard service property keys. Changes should not be made to this object after calling this method. To update the service’s properties the Serv iceRegist rat ion.setPropert ies [p.180] method must be called. The set of properties may be null if the service has no properties.

OSGi Service Platform Release 4 145-268

Page 154: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Registers the specified service object with the specified properties under the specified class names into the Framework. A ServiceRegistration object is returned. The ServiceRegistration object is for the private use of the bundle registering the service and should not be shared with other bundles. The registering bundle is defined to be the context bundle. Other bundles can locate the service by using either the getServiceReferences [p.143] or getServiceReference [p.142] method.

A bundle can register a service object that implements the ServiceFactory [p.175] interface to have more flexibility in providing service objects to other bundles.

The following steps are required to register a service:

1 If service is not a ServiceFactory, an IllegalArgumentException is thrown if service is not an instanceof all the classes named.

2 The Framework adds these service properties to the specified Dictionary (which may be null): a property named Constants.SERVICE_ID [p.163] identifying the registration number of the service and a property named Constants .OBJECTCLASS [p.162] containing all the specified classes. If any of these properties have already been specified by the registering bundle, their values will be overwritten by the Framework.

3 The service is added to the Framework service registry and may now be used by other bundles.

4 A service event of type ServiceEvent .REGISTERED [p.174] is fired. 5 A ServiceRegistration object for this registration is returned.

Returns A ServiceRegistration object for use by the bundle registering the service to update the service’s properties or to unregister the service.

Throws IllegalArgumentException – If one of the following is true: service is null. service is not a ServiceFactory object and is not an instance of all the named classes in clazzes. properties contains case variants of the same key name.

SecurityException – If the caller does not have the ServicePermission to register the service for all the named classes and the Java Runtime Environ-ment supports permissions.

IllegalStateException – If this BundleContext is no longer valid.

See Also ServiceRegistration[p.179] , ServiceFactory[p.175]registerService(String,Object,Dictionary)

6.1.6.18 public ServiceRegistration registerService( String clazz, Object service, Dictionary properties )

clazz The class name under which the service can be located.

service The service object or a ServiceFactory object.

properties The properties for this service.

Registers the specified service object with the specified properties under the specified class name with the Framework.

This method is otherwise identical to registerService( java. lang.Str ing[] , java. lang.Object, java.uti l .Dict ionary) [p.145] and is provided as a conve-nience when service will only be registered under a single class name. Note that even in this case the value of the service’s Constants.OBJECTCLASS [p.162] property will be an array of strings, rather than just a single string.

146-268 OSGi Service Platform Release 4

Page 155: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Returns A ServiceRegistration object for use by the bundle registering the service to update the service’s properties or to unregister the service.

Throws IllegalStateException – If this BundleContext is no longer valid.

See Also registerService(java.lang.String[], java.lang.Object, java.util.Dictionary)[p.145]removeBundleListener(BundleListener)

6.1.6.19 public void removeBundleListener( BundleListener listener )

listener The BundleListener object to be removed.

Removes the specified BundleListener object from the context bundle’s list of listeners.

If listener is not contained in the context bundle’s list of listeners, this method does nothing.

Throws IllegalStateException – If this BundleContext is no longer valid.

SecurityException – If listener is a SynchronousBundleListener and the caller does not have the appropriate AdminPermission[context bundle,LIS-TENER], and the Java Runtime Environment supports permissions. removeFrameworkListener(FrameworkListener)

6.1.6.20 public void removeFrameworkListener( FrameworkListener listener )

listener The FrameworkListener object to be removed.

Removes the specified FrameworkListener object from the context bundle’s list of listeners.

If listener is not contained in the context bundle’s list of listeners, this method does nothing.

Throws IllegalStateException – If this BundleContext is no longer valid. removeServiceListener(ServiceListener)

6.1.6.21 public void removeServiceListener( ServiceListener listener )

listener The ServiceListener to be removed.

Removes the specified ServiceListener object from the context bundle’s list of listeners.

If listener is not contained in this context bundle’s list of listeners, this method does nothing.

Throws IllegalStateException – If this BundleContext is no longer valid. ungetService(ServiceReference)

6.1.6.22 public boolean ungetService( ServiceReference reference )

reference A reference to the service to be released.

Releases the service object referenced by the specified ServiceReference object. If the context bundle’s use count for the service is zero, this method returns false. Otherwise, the context bundle’s use count for the service is decremented by one.

The service’s service object should no longer be used and all references to it should be destroyed when a bundle’s use count for the service drops to zero.

The following steps are required to unget the service object:

1 If the context bundle’s use count for the service is zero or the service has been unregistered, false is returned.

2 The context bundle’s use count for this service is decremented by one.

OSGi Service Platform Release 4 147-268

Page 156: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

3 If the context bundle’s use count for the service is currently zero and the service was registered with a ServiceFactory object, the Service-Factory .ungetServ ice(Bundle, ServiceRegistrat ion , Object) [p.175] method is called to release the service object for the context bundle.

4 true is returned.

Returns false if the context bundle’s use count for the service is zero or if the service has been unregistered; true otherwise.

Throws IllegalStateException – If this BundleContext is no longer valid.

See Also getService[p.142] , ServiceFactory[p.175]BundleEvent

6.1.7 public class BundleEventextends EventObjectAn event from the Framework describing a bundle lifecycle change.

BundleEvent objects are delivered to BundleListener objects when a change occurs in a bundle’s lifecycle. A type code is used to identify the event type for future extendability.

OSGi Alliance reserves the right to extend the set of types.INSTALLED

6.1.7.1 public static final int INSTALLED = 1

The bundle has been installed.

The value of INSTALLED is 0x00000001.

See Also BundleContext.installBundle(String)[p.144]RESOLVED

6.1.7.2 public static final int RESOLVED = 32

The bundle has been resolved.

The value of RESOLVED is 0x00000020.

See Also Bundle.RESOLVED[p.124]

Since 1.3STARTED

6.1.7.3 public static final int STARTED = 2

The bundle has been started.

The value of STARTED is 0x00000002.

See Also Bundle.start[p.131]STARTING

6.1.7.4 public static final int STARTING = 128

The bundle is about to start.

The value of STARTING is 0x00000080.

See Also Bundle.start()[p.131]

Since 1.3STOPPED

6.1.7.5 public static final int STOPPED = 4

The bundle has been stopped.

The value of STOPPED is 0x00000004.

See Also Bundle.stop[p.132]

148-268 OSGi Service Platform Release 4

Page 157: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

STOPPING

6.1.7.6 public static final int STOPPING = 256

The bundle is about to stop.

The value of STOPPING is 0x00000100.

See Also Bundle.stop()[p.132]

Since 1.3UNINSTALLED

6.1.7.7 public static final int UNINSTALLED = 16

The bundle has been uninstalled.

The value of UNINSTALLED is 0x00000010.

See Also Bundle.uninstall[p.133]UNRESOLVED

6.1.7.8 public static final int UNRESOLVED = 64

The bundle has been unresolved.

The value of UNRESOLVED is 0x00000040.

See Also Bundle.INSTALLED[p.124]

Since 1.3UPDATED

6.1.7.9 public static final int UPDATED = 8

The bundle has been updated.

The value of UPDATED is 0x00000008.

See Also Bundle.update()[p.134]BundleEvent(int,Bundle)

6.1.7.10 public BundleEvent( int type, Bundle bundle )

type The event type.

bundle The bundle which had a lifecycle change.

Creates a bundle event of the specified type. getBundle()

6.1.7.11 public Bundle getBundle( )

Returns the bundle which had a lifecycle change. This bundle is the source of the event.

Returns The bundle that had a change occur in its lifecycle.getType()

6.1.7.12 public int getType( )

Returns the type of lifecyle event. The type values are:

• INSTALLED [p.148]• RESOLVED [p.148]• STARTING [p.148]• STARTED [p.148]• STOPPING [p.149]• STOPPED [p.148]• UPDATED [p.149]• UNRESOLVED [p.149]• UNINSTALLED [p.149]

Returns The type of lifecycle event.BundleException

OSGi Service Platform Release 4 149-268

Page 158: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.8 public class BundleExceptionextends ExceptionA Framework exception used to indicate that a bundle lifecycle problem occurred.

BundleException object is created by the Framework to denote an exception condition in the lifecycle of a bundle. BundleExceptions should not be cre-ated by bundle developers.

This exception is updated to conform to the general purpose exception chaining mechanism.BundleException(String,Throwable)

6.1.8.1 public BundleException( String msg, Throwable cause )

msg The associated message.

cause The cause of this exception.

Creates a BundleException that wraps another exception. BundleException(String)

6.1.8.2 public BundleException( String msg )

msg The message.

Creates a BundleException object with the specified message. getCause()

6.1.8.3 public Throwable getCause( )

Returns the cause of this exception or null if no cause was specified when this exception was created.

Returns The cause of this exception or null if no cause was specified.

Since 1.3getNestedException()

6.1.8.4 public Throwable getNestedException( )

Returns any nested exceptions included in this exception.

This method predates the general purpose exception chaining mechanism. The getCause() [p.150] method is now the preferred means of obtaining this information.

Returns The nested exception; null if there is no nested exception.initCause(Throwable)

6.1.8.5 public Throwable initCause( Throwable cause )

cause Cause of the exception.

The cause of this exception can only be set when constructed.

Returns This object.

Throws IllegalStateException – This method will always throw an IllegalState-Exception since the cause of this exception can only be set when constructed.

Since 1.3BundleListener

150-268 OSGi Service Platform Release 4

Page 159: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6.1.9 public interface BundleListenerextends EventListenerA BundleEvent listener. When a BundleEvent is fired, it is asynchronously delivered to a BundleListener.

BundleListener is a listener interface that may be implemented by a bundle developer.

A BundleListener object is registered with the Framework using the BundleContext .addBundleLis tener [p.137] method. BundleListeners are called with a BundleEvent object when a bundle has been installed, resolved, started, stopped, updated, unresolved, or uninstalled.

See Also BundleEvent[p.148]bundleChanged(BundleEvent)

6.1.9.1 public void bundleChanged( BundleEvent event )

event The BundleEvent.

Receives notification that a bundle has had a lifecycle change. BundlePermission

6.1.10 public final class BundlePermissionextends BasicPermissionA bundle’s authority to require or provide a bundle or to receive or attach fragments.

A bundle symbolic name defines a unique fully qualified name.

For example:

org.osgi.example.bundle

BundlePermission has four actions: PROVIDE, REQUIRE,HOST, and FRAG-MENT. The PROVIDE action implies the REQUIRE action.

Since 1.3FRAGMENT

6.1.10.1 public static final String FRAGMENT = “fragment”

The action string fragment. HOST

6.1.10.2 public static final String HOST = “host”

The action string host. PROVIDE

6.1.10.3 public static final String PROVIDE = “provide”

The action string provide. REQUIRE

6.1.10.4 public static final String REQUIRE = “require”

The action string require. BundlePermission(String,String)

6.1.10.5 public BundlePermission( String symbolicName, String actions )

symbolicName the bundle symbolic name.

actions PROVIDE,REQUIRE, HOST,FRAGMENT (canonical order).

Defines the authority to provide and/or require and or specify a host frag-ment symbolic name within the OSGi environment.

OSGi Service Platform Release 4 151-268

Page 160: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Bundle Permissions are granted over all possible versions of a bundle. A bundle that needs to provide a bundle must have the appropriate BundlePer-mission for the symbolic name; a bundle that requires a bundle must have the appropriate BundlePermssion for that symbolic name; a bundle that specifies a fragment host must have the appropriate BundlePermission for that symbolic name.equals(Object)

6.1.10.6 public boolean equals( Object obj )

obj The object to test for equality with this BundlePermission object.

Determines the equality of two BundlePermission objects. This method checks that specified bundle has the same bundle symbolic name and Bun-dlePermission actions as this BundlePermission object.

Returns true if obj is a BundlePermission, and has the same bundle symbolic name and actions as this BundlePermission object; false otherwise.getActions()

6.1.10.7 public String getActions( )

Returns the canonical string representation of the BundlePermission actions.

Always returns present BundlePermission actions in the following order: PROVIDE,REQUIRE, HOST,FRAGMENT.

Returns Canonical string representation of the BundlePermission actions.hashCode()

6.1.10.8 public int hashCode( )

Returns the hash code value for this object.

Returns A hash code value for this object.implies(Permission)

6.1.10.9 public boolean implies( Permission p )

p The target permission to interrogate.

Determines if the specified permission is implied by this object.

This method checks that the symbolic name of the target is implied by the symbolic name of this object. The list of BundlePermission actions must either match or allow for the list of the target object to imply the target Bun-dlePermission action.

The permission to provide a bundle implies the permission to require the named symbolic name.

x.y.*,”provide” -> x.y.z,”provide” is true*,”require” -> x.y, “require” is true*,”provide” -> x.y, “require” is truex.y,”provide” -> x.y.z, “provide” is false

Returns true if the specified BundlePermission action is implied by this object; false otherwise.newPermissionCollection()

6.1.10.10 public PermissionCollection newPermissionCollection( )

Returns a new PermissionCollection object suitable for storing BundlePer-mission objects.

Returns A new PermissionCollection object.Configurable

152-268 OSGi Service Platform Release 4

Page 161: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6.1.11 public interface ConfigurableSupports a configuration object.

Configurable is an interface that should be used by a bundle developer in support of a configurable service. Bundles that need to configure a service may test to determine if the service object is an instanceof Configurable.

Deprecated Since 1.2. Please use Configuration Admin service.getConfigurationObject()

6.1.11.1 public Object getConfigurationObject( )

Returns this service’s configuration object.

Services implementing Configurable should take care when returning a ser-vice configuration object since this object is probably sensitive.

If the Java Runtime Environment supports permissions, it is recommended that the caller is checked for some appropriate permission before returning the configuration object.

Returns The configuration object for this service.

Throws SecurityException – If the caller does not have an appropriate permission and the Java Runtime Environment supports permissions.

Deprecated Since 1.2. Please use Configuration Admin service.Constants

6.1.12 public interface ConstantsDefines standard names for the OSGi environment property, service prop-erty, and Manifest header attribute keys.

The values associated with these keys are of type java.lang.String, unless otherwise indicated.

Since 1.1BUNDLE_ACTIVATOR

6.1.12.1 public static final String BUNDLE_ACTIVATOR = “Bundle-Activator”

Manifest header attribute (named “Bundle-Activator”) identifying the bun-dle’s activator class.

If present, this header specifies the name of the bundle resource class that implements the BundleActivator interface and whose start and stop meth-ods are called by the Framework when the bundle is started and stopped, respectively.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_CATEGORY

6.1.12.2 public static final String BUNDLE_CATEGORY = “Bundle-Category”

Manifest header (named “Bundle-Category”) identifying the bundle’s cate-gory.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_CLASSPATH

OSGi Service Platform Release 4 153-268

Page 162: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.12.3 public static final String BUNDLE_CLASSPATH = “Bundle-ClassPath”

Manifest header (named “Bundle-ClassPath”) identifying a list of directories and embedded JAR files, which are bundle resources used to extend the bun-dle’s classpath.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_CONTACTADDRESS

6.1.12.4 public static final String BUNDLE_CONTACTADDRESS = “Bundle-ContactAddress”

Manifest header (named “Bundle-ContactAddress”) identifying the contact address where problems with the bundle may be reported; for example, an email address.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_COPYRIGHT

6.1.12.5 public static final String BUNDLE_COPYRIGHT = “Bundle-Copyright”

Manifest header (named “Bundle-Copyright”) identifying the bundle’s copy-right information.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_DESCRIPTION

6.1.12.6 public static final String BUNDLE_DESCRIPTION = “Bundle-Description”

Manifest header (named “Bundle-Description”) containing a brief descrip-tion of the bundle’s functionality.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_DOCURL

6.1.12.7 public static final String BUNDLE_DOCURL = “Bundle-DocURL”

Manifest header (named “Bundle-DocURL”) identifying the bundle’s docu-mentation URL, from which further information about the bundle may be obtained.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_LOCALIZATION

6.1.12.8 public static final String BUNDLE_LOCALIZATION = “Bundle-Localization”

Manifest header (named “Bundle-Localization”) identifying the base name of the bundle’s localization entries.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

See Also BUNDLE_LOCALIZATION_DEFAULT_BASENAME[p.154]

Since 1.3BUNDLE_LOCALIZATION_DEFAULT_BASENAME

6.1.12.9 public static final String BUNDLE_LOCALIZATION_DEFAULT_BASENAME = “OSGI-INF/l10n/bundle”

Default value for the Bundle-Localization manifest header.

See Also BUNDLE_LOCALIZATION[p.154]

154-268 OSGi Service Platform Release 4

Page 163: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Since 1.3BUNDLE_MANIFESTVERSION

6.1.12.10 public static final String BUNDLE_MANIFESTVERSION = “Bundle-ManifestVersion”

Manifest header (named “Bundle-ManifestVersion”) identifying the bundle manifest version. A bundle manifest may express the version of the syntax in which it is written by specifying a bundle manifest version. Bundles exploiting OSGi R4, or later, syntax must specify a bundle manifest version.

The bundle manifest version defined by OSGi R4 or, more specifically, by V1.3 of the OSGi Framework Specification is “2”.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

Since 1.3BUNDLE_NAME

6.1.12.11 public static final String BUNDLE_NAME = “Bundle-Name”

Manifest header (named “Bundle-Name”) identifying the bundle’s name.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_NATIVECODE

6.1.12.12 public static final String BUNDLE_NATIVECODE = “Bundle-NativeCode”

Manifest header (named “Bundle-NativeCode”) identifying a number of hardware environments and the native language code libraries that the bun-dle is carrying for each of these environments.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_NATIVECODE_LANGUAGE

6.1.12.13 public static final String BUNDLE_NATIVECODE_LANGUAGE = “language”

Manifest header attribute (named “language”) identifying the language in which the native bundle code is written specified in the Bundle-NativeCode manifest header. See ISO 639 for possible values.

The attribute value is encoded in the Bundle-NativeCode manifest header like:

Bundle-NativeCode: http.so ; language=nl_be ...BUNDLE_NATIVECODE_OSNAME

6.1.12.14 public static final String BUNDLE_NATIVECODE_OSNAME = “osname”

Manifest header attribute (named “osname”) identifying the operating sys-tem required to run native bundle code specified in the Bundle-NativeCode manifest header).

The attribute value is encoded in the Bundle-NativeCode manifest header like:

Bundle-NativeCode: http.so ; osname=Linux ...BUNDLE_NATIVECODE_OSVERSION

6.1.12.15 public static final String BUNDLE_NATIVECODE_OSVERSION = “osversion”

Manifest header attribute (named “osversion”) identifying the operating system version required to run native bundle code specified in the Bundle-NativeCode manifest header).

OSGi Service Platform Release 4 155-268

Page 164: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

The attribute value is encoded in the Bundle-NativeCode manifest header like:

Bundle-NativeCode: http.so ; osversion=”2.34” ...BUNDLE_NATIVECODE_PROCESSOR

6.1.12.16 public static final String BUNDLE_NATIVECODE_PROCESSOR = “processor”

Manifest header attribute (named “processor”) identifying the processor required to run native bundle code specified in the Bundle-NativeCode man-ifest header).

The attribute value is encoded in the Bundle-NativeCode manifest header like:

Bundle-NativeCode: http.so ; processor=x86 ...BUNDLE_REQUIREDEXECUTIONENVIRONMENT

6.1.12.17 public static final String BUNDLE_REQUIREDEXECUTIONENVIRONMENT = “Bundle-RequiredExecutionEnvironment”

Manifest header (named “Bundle-RequiredExecutionEnvironment”) identi-fying the required execution environment for the bundle. The service plat-form may run this bundle if any of the execution environments named in this header matches one of the execution environments it implements.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

Since 1.2BUNDLE_SYMBOLICNAME

6.1.12.18 public static final String BUNDLE_SYMBOLICNAME = “Bundle-SymbolicName”

Manifest header (named “Bundle-SymbolicName”) identifying the bundle’s symbolic name.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

Since 1.3BUNDLE_SYMBOLICNAME_ATTRIBUTE

6.1.12.19 public static final String BUNDLE_SYMBOLICNAME_ATTRIBUTE = “bundle-symbolic-name”

Manifest header attribute (named “bundle-symbolic-name”) identifying the symbolic name of a bundle that exports a package specified in the Import-Package manifest header.

The attribute value is encoded in the Import-Package manifest header like:

Import-Package: org.osgi.framework; bundle-symbolic-name=”com.acme.module.test”

Since 1.3BUNDLE_UPDATELOCATION

6.1.12.20 public static final String BUNDLE_UPDATELOCATION = “Bundle-UpdateLocation”

Manifest header (named “Bundle-UpdateLocation”) identifying the location from which a new bundle version is obtained during a bundle update opera-tion.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

156-268 OSGi Service Platform Release 4

Page 165: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

BUNDLE_VENDOR

6.1.12.21 public static final String BUNDLE_VENDOR = “Bundle-Vendor”

Manifest header (named “Bundle-Vendor”) identifying the bundle’s vendor.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_VERSION

6.1.12.22 public static final String BUNDLE_VERSION = “Bundle-Version”

Manifest header (named “Bundle-Version”) identifying the bundle’s version.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.BUNDLE_VERSION_ATTRIBUTE

6.1.12.23 public static final String BUNDLE_VERSION_ATTRIBUTE = “bundle-version”

Manifest header attribute (named “bundle-version”) identifying a range of versions for a bundle specified in the Require-Bundle or Fragment-Host manifest headers. The default value is 0.0.0.

The attribute value is encoded in the Require-Bundle manifest header like:

Require-Bundle: com.acme.module.test; bundle-version=”1.1”Require-Bundle: com.acme.module.test; bundle-version=”[1.0,

2.0)”

The bundle-version attribute value uses a mathematical interval notation to specify a range of bundle versions. A bundle-version attribute value speci-fied as a single version means a version range that includes any bundle ver-sion greater than or equal to the specified version.

Since 1.3DYNAMICIMPORT_PACKAGE

6.1.12.24 public static final String DYNAMICIMPORT_PACKAGE = “DynamicImport-Package”

Manifest header (named “DynamicImport-Package”) identifying the pack-ages that the bundle may dynamically import during execution.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

Since 1.2EXCLUDE_DIRECTIVE

6.1.12.25 public static final String EXCLUDE_DIRECTIVE = “exclude”

Manifest header directive (named “exclude”) identifying a list of classes and/or resources of the specified package which must not be allowed to be exported in the Export-Package manifest header.

The directive value is encoded in the Export-Package manifest header like:

Export-Package: org.osgi.framework; exclude:=”MyStuff*”

Since 1.3EXPORT_PACKAGE

6.1.12.26 public static final String EXPORT_PACKAGE = “Export-Package”

Manifest header (named “Export-Package”) identifying the packages that the bundle offers to the Framework for export.

OSGi Service Platform Release 4 157-268

Page 166: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.EXPORT_SERVICE

6.1.12.27 public static final String EXPORT_SERVICE = “Export-Service”

Manifest header (named “Export-Service”) identifying the fully qualified class names of the services that the bundle may register (used for informa-tional purposes only).

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.EXTENSION_BOOTCLASSPATH

6.1.12.28 public static final String EXTENSION_BOOTCLASSPATH = “bootclasspath”

Manifest header directive value (named “bootclasspath”) identifying the type of extension fragment. An extension fragment type of bootclasspath indicates that the extension fragment is to be loaded by the boot class loader.

The directive value is encoded in the Fragment-Host manifest header like:

Fragment-Host: system.bundle; extension:=”bootclasspath”

See Also Constants.EXTENSION_DIRECTIVE[p.158]

Since 1.3EXTENSION_DIRECTIVE

6.1.12.29 public static final String EXTENSION_DIRECTIVE = “extension”

Manifest header directive (named “extension”) identifying the type of the extension fragment.

The directive value is encoded in the Fragment-Host manifest header like:

Fragment-Host: system.bundle; extension:=”framework”

See Also Constants.EXTENSION_FRAMEWORK[p.158] , Constants.EXTENSION_BOOTCLASSPATH[p.158]

Since 1.3EXTENSION_FRAMEWORK

6.1.12.30 public static final String EXTENSION_FRAMEWORK = “framework”

Manifest header directive value (named “framework”) identifying the type of extension fragment. An extension fragment type of framework indicates that the extension fragment is to be loaded by the framework’s class loader.

The directive value is encoded in the Fragment-Host manifest header like:

Fragment-Host: system.bundle; extension:=”framework”

See Also Constants.EXTENSION_DIRECTIVE[p.158]

Since 1.3FRAGMENT_ATTACHMENT_ALWAYS

6.1.12.31 public static final String FRAGMENT_ATTACHMENT_ALWAYS = “always”

Manifest header directive value (named “always”) identifying a fragment attachment type of always. A fragment attachment type of always indicates that fragments are allowed to attach to the host bundle at any time (while the host is resolved or during the process of resolving the host bundle).

The directive value is encoded in the Bundle-SymbolicName manifest header like:

158-268 OSGi Service Platform Release 4

Page 167: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Bundle-SymbolicName: com.acme.module.test; fragment-attach-ment:=”always”

See Also Constants.FRAGMENT_ATTACHMENT_DIRECTIVE[p.159]

Since 1.3FRAGMENT_ATTACHMENT_DIRECTIVE

6.1.12.32 public static final String FRAGMENT_ATTACHMENT_DIRECTIVE = “fragment-attachment”

Manifest header directive (named “fragment-attachment”) identifying if and when a fragment may attach to a host bundle. The default value is “always”.

The directive value is encoded in the Bundle-SymbolicName manifest header like:

Bundle-SymbolicName: com.acme.module.test; fragment-attach-ment:=”never”

See Also Constants.FRAGMENT_ATTACHMENT_ALWAYS[p.158] , Constants.FRAGMENT_ATTACHMENT_RESOLVETIME[p.159] , Constants.FRAGMENT_ATTACHMENT_NEVER[p.159]

Since 1.3FRAGMENT_ATTACHMENT_NEVER

6.1.12.33 public static final String FRAGMENT_ATTACHMENT_NEVER = “never”

Manifest header directive value (named “never”) identifying a fragment attachment type of never. A fragment attachment type of never indicates that no fragments are allowed to attach to the host bundle at any time.

The directive value is encoded in the Bundle-SymbolicName manifest header like:

Bundle-SymbolicName: com.acme.module.test; fragment-attach-ment:=”never”

See Also Constants.FRAGMENT_ATTACHMENT_DIRECTIVE[p.159]

Since 1.3FRAGMENT_ATTACHMENT_RESOLVETIME

6.1.12.34 public static final String FRAGMENT_ATTACHMENT_RESOLVETIME = “resolve-time”

Manifest header directive value (named “resolve-time”) identifying a frag-ment attachment type of resolve-time. A fragment attachment type of resolve-time indicates that fragments are allowed to attach to the host bun-dle only during the process of resolving the host bundle.

The directive value is encoded in the Bundle-SymbolicName manifest header like:

Bundle-SymbolicName: com.acme.module.test; fragment-attach-ment:=”resolve-time”

See Also Constants.FRAGMENT_ATTACHMENT_DIRECTIVE[p.159]

Since 1.3FRAGMENT_HOST

6.1.12.35 public static final String FRAGMENT_HOST = “Fragment-Host”

Manifest header (named “Fragment-Host”) identifying the symbolic name of another bundle for which that the bundle is a fragment.

OSGi Service Platform Release 4 159-268

Page 168: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

Since 1.3FRAMEWORK_BOOTDELEGATION

6.1.12.36 public static final String FRAMEWORK_BOOTDELEGATION = “org.osgi.framework.bootdelegation”

Framework environment property (named “org.osgi.framework.bootdelega-tion”) identifying packages for which the Framework must delegate class loading to the boot class path.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.3FRAMEWORK_EXECUTIONENVIRONMENT

6.1.12.37 public static final String FRAMEWORK_EXECUTIONENVIRONMENT = “org.osgi.framework.executionenvironment”

Framework environment property (named “org.osgi.framework.execution-environment”) identifying execution environments provided by the Frame-work.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.2FRAMEWORK_LANGUAGE

6.1.12.38 public static final String FRAMEWORK_LANGUAGE = “org.osgi.framework.language”

Framework environment property (named “org.osgi.framework.language”) identifying the Framework implementation language (see ISO 639 for possi-ble values).

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.FRAMEWORK_OS_NAME

6.1.12.39 public static final String FRAMEWORK_OS_NAME = “org.osgi.framework.os.name”

Framework environment property (named “org.osgi.framework.os.name”) identifying the Framework host-computer’s operating system.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.FRAMEWORK_OS_VERSION

6.1.12.40 public static final String FRAMEWORK_OS_VERSION = “org.osgi.framework.os.version”

Framework environment property (named “org.osgi.framework.os.version”) identifying the Framework host-computer’s operating system version num-ber.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.FRAMEWORK_PROCESSOR

6.1.12.41 public static final String FRAMEWORK_PROCESSOR =

160-268 OSGi Service Platform Release 4

Page 169: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

“org.osgi.framework.processor”

Framework environment property (named “org.osgi.framework.processor”) identifying the Framework host-computer’s processor name.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.FRAMEWORK_SYSTEMPACKAGES

6.1.12.42 public static final String FRAMEWORK_SYSTEMPACKAGES = “org.osgi.framework.system.packages”

Framework environment property (named “org.osgi.framework.sys-tem.packages”) identifying package which the system bundle must export.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.3FRAMEWORK_VENDOR

6.1.12.43 public static final String FRAMEWORK_VENDOR = “org.osgi.framework.vendor”

Framework environment property (named “org.osgi.framework.vendor”) identifying the Framework implementation vendor.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.FRAMEWORK_VERSION

6.1.12.44 public static final String FRAMEWORK_VERSION = “org.osgi.framework.version”

Framework environment property (named “org.osgi.framework.version”) identifying the Framework version.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.IMPORT_PACKAGE

6.1.12.45 public static final String IMPORT_PACKAGE = “Import-Package”

Manifest header (named “Import-Package”) identifying the packages on which the bundle depends.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.IMPORT_SERVICE

6.1.12.46 public static final String IMPORT_SERVICE = “Import-Service”

Manifest header (named “Import-Service”) identifying the fully qualified class names of the services that the bundle requires (used for informational purposes only).

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.INCLUDE_DIRECTIVE

6.1.12.47 public static final String INCLUDE_DIRECTIVE = “include”

Manifest header directive (named “include”) identifying a list of classes and/or resources of the specified package which must be allowed to be exported in the Export-Package manifest header.

The directive value is encoded in the Export-Package manifest header like:

OSGi Service Platform Release 4 161-268

Page 170: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Export-Package: org.osgi.framework; include:=”MyStuff*”

Since 1.3MANDATORY_DIRECTIVE

6.1.12.48 public static final String MANDATORY_DIRECTIVE = “mandatory”

Manifest header directive (named “mandatory”) identifying names of matching attributes which must be specified by matching Import-Package statements in the Export-Package manifest header.

The directive value is encoded in the Export-Package manifest header like:

Export-Package: org.osgi.framework; mandatory:=”bundle-sym-bolic-name”

Since 1.3OBJECTCLASS

6.1.12.49 public static final String OBJECTCLASS = “objectClass”

Service property (named “objectClass”) identifying all of the class names under which a service was registered in the Framework (of type java.lang.String[]).

This property is set by the Framework when a service is registered.PACKAGE_SPECIFICATION_VERSION

6.1.12.50 public static final String PACKAGE_SPECIFICATION_VERSION = “specification-version”

Manifest header attribute (named “specification-version”) identifying the version of a package specified in the Export-Package or Import-Package manifest header.

The attribute value is encoded in the Export-Package or Import-Package manifest header like:

Import-Package: org.osgi.framework ; specification-ver-sion=”1.1”

Deprecated Since 1.3. This has been replaced by VERSION_ATTRIBUTE [p.166] .REQUIRE_BUNDLE

6.1.12.51 public static final String REQUIRE_BUNDLE = “Require-Bundle”

Manifest header (named “Require-Bundle”) identifying the symbolic names of other bundles required by the bundle.

The attribute value may be retrieved from the Dictionary object returned by the Bundle.getHeaders method.

Since 1.3RESOLUTION_DIRECTIVE

6.1.12.52 public static final String RESOLUTION_DIRECTIVE = “resolution”

Manifest header directive (named “resolution”) identifying the resolution type in the Import-Package or Require-Bundle manifest header.

The directive value is encoded in the Import-Package or Require-Bundle manifest header like:

Import-Package: org.osgi.framework; resolution:=”optional”Require-Bundle: com.acme.module.test; resolution:=”option-

al”

See Also Constants.RESOLUTION_MANDATORY[p.163] , Constants.RESOLUTION_OPTIONAL[p.163]

162-268 OSGi Service Platform Release 4

Page 171: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Since 1.3RESOLUTION_MANDATORY

6.1.12.53 public static final String RESOLUTION_MANDATORY = “mandatory”

Manifest header directive value (named “mandatory”) identifying a manda-tory resolution type. A mandatory resolution type indicates that the import package or require bundle must be resolved when the bundle is resolved. If such an import or require bundle cannot be resolved, the module fails to resolve.

The directive value is encoded in the Import-Package or Require-Bundle manifest header like:

Import-Package: org.osgi.framework; resolution:=”manditory”Require-Bundle: com.acme.module.test; resolution:=”mandito-

ry”

See Also Constants.RESOLUTION_DIRECTIVE[p.162]

Since 1.3RESOLUTION_OPTIONAL

6.1.12.54 public static final String RESOLUTION_OPTIONAL = “optional”

Manifest header directive value (named “optional”) identifying an optional resolution type. An optional resolution type indicates that the import or require bundle is optional and the bundle may be resolved without the import or require bundle being resolved. If the import or require bundle is not resolved when the bundle is resolved, the import or require bundle may not be resolved before the bundle is refreshed.

The directive value is encoded in the Import-Package or Require-Bundle manifest header like:

Import-Package: org.osgi.framework; resolution:=”optional”Require-Bundle: com.acme.module.test; resolution:=”option-

al”

See Also Constants.RESOLUTION_DIRECTIVE[p.162]

Since 1.3SELECTION_FILTER_ATTRIBUTE

6.1.12.55 public static final String SELECTION_FILTER_ATTRIBUTE = “selection-filter”

Manifest header attribute (named “selection-filter”) is used for selection by filtering based upon system properties.

The attribute value is encoded in manifest headers like:

Bundle-NativeCode: libgtk.so; selection-filter=”(ws=gtk)”;...

Since 1.3SERVICE_DESCRIPTION

6.1.12.56 public static final String SERVICE_DESCRIPTION = “service.description”

Service property (named “service.description”) identifying a service’s description.

This property may be supplied in the properties Dictionary object passed to the BundleContext.registerService method.SERVICE_ID

OSGi Service Platform Release 4 163-268

Page 172: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.12.57 public static final String SERVICE_ID = “service.id”

Service property (named “service.id”) identifying a service’s registration number (of type java.lang.Long).

The value of this property is assigned by the Framework when a service is registered. The Framework assigns a unique value that is larger than all pre-viously assigned values since the Framework was started. These values are NOT persistent across restarts of the Framework.SERVICE_PID

6.1.12.58 public static final String SERVICE_PID = “service.pid”

Service property (named “service.pid”) identifying a service’s persistent identifier.

This property may be supplied in the propertiesDictionary object passed to the BundleContext.registerService method.

A service’s persistent identifier uniquely identifies the service and persists across multiple Framework invocations.

By convention, every bundle has its own unique namespace, starting with the bundle’s identifier (see Bundle.getBundleId [p.126] ) and followed by a dot (.). A bundle may use this as the prefix of the persistent identifiers for the services it registers.SERVICE_RANKING

6.1.12.59 public static final String SERVICE_RANKING = “service.ranking”

Service property (named “service.ranking”) identifying a service’s ranking number (of type java.lang.Integer).

This property may be supplied in the properties Dictionary object passed to the BundleContext.registerService method.

The service ranking is used by the Framework to determine the default ser-vice to be returned from a call to the BundleContext .getServ iceReference [p.142] method: If more than one ser-vice implements the specified class, the ServiceReference object with the highest ranking is returned.

The default ranking is zero (0). A service with a ranking of Inte-ger.MAX_VALUE is very likely to be returned as the default service, whereas a service with a ranking of Integer.MIN_VALUE is very unlikely to be returned.

If the supplied property value is not of type java.lang.Integer, it is deemed to have a ranking value of zero.SERVICE_VENDOR

6.1.12.60 public static final String SERVICE_VENDOR = “service.vendor”

Service property (named “service.vendor”) identifying a service’s vendor.

This property may be supplied in the properties Dictionary object passed to the BundleContext.registerService method.SINGLETON_DIRECTIVE

6.1.12.61 public static final String SINGLETON_DIRECTIVE = “singleton”

Manifest header directive (named “singleton”) identifying whether a bundle is a singleton. The default value is false.

164-268 OSGi Service Platform Release 4

Page 173: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

The directive value is encoded in the Bundle-SymbolicName manifest header like:

Bundle-SymbolicName: com.acme.module.test; singleton:=true

Since 1.3SUPPORTS_BOOTCLASSPATH_EXTENSION

6.1.12.62 public static final String SUPPORTS_BOOTCLASSPATH_EXTENSION = “org.osgi.supports.bootclasspath.extension”

Framework environment property (named “org.osgi.supports.bootclass-path.extension”) identifying whether the Framework supports bootclass-path extension bundles. If the value of this property is true, then the Framework supports bootclasspath extension bundles. The default value is false.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.3SUPPORTS_FRAMEWORK_EXTENSION

6.1.12.63 public static final String SUPPORTS_FRAMEWORK_EXTENSION = “org.osgi.supports.framework.extension”

Framework environment property (named “org.osgi.supports.frame-work.extension”) identifying whether the Framework supports framework extension bundles. If the value of this property is true, then the Framework supports framework extension bundles. The default value is false.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.3SUPPORTS_FRAMEWORK_FRAGMENT

6.1.12.64 public static final String SUPPORTS_FRAMEWORK_FRAGMENT = “org.osgi.supports.framework.fragment”

Framework environment property (named “org.osgi.supports.frame-work.fragment”) identifying whether the Framework supports fragment bundles. If the value of this property is true, then the Framework supports fragment bundles. The default value is false.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.3SUPPORTS_FRAMEWORK_REQUIREBUNDLE

6.1.12.65 public static final String SUPPORTS_FRAMEWORK_REQUIREBUNDLE = “org.osgi.supports.framework.requirebundle”

Framework environment property (named “org.osgi.supports.frame-work.requirebundle”) identifying whether the Framework supports the Require-Bundle manifest header. If the value of this property is true, then the Framework supports the Require-Bundle manifest header. The default value is false.

The value of this property may be retrieved by calling the BundleCon-text.getProperty method.

Since 1.3SYSTEM_BUNDLE_LOCATION

OSGi Service Platform Release 4 165-268

Page 174: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.12.66 public static final String SYSTEM_BUNDLE_LOCATION = “System Bundle”

Location identifier of the OSGi system bundle , which is defined to be “System Bundle”. SYSTEM_BUNDLE_SYMBOLICNAME

6.1.12.67 public static final String SYSTEM_BUNDLE_SYMBOLICNAME = “system.bundle”

Alias for the symbolic name of the OSGi system bundle . It is defined to be “system.bundle”.

Since 1.3USES_DIRECTIVE

6.1.12.68 public static final String USES_DIRECTIVE = “uses”

Manifest header directive (named “uses”) identifying a list of packages that an exported package uses.

The directive value is encoded in the Export-Package manifest header like:

Export-Package: org.osgi.util.tracker; uses:=”org.os-gi.framework”

Since 1.3VERSION_ATTRIBUTE

6.1.12.69 public static final String VERSION_ATTRIBUTE = “version”

Manifest header attribute (named “version”) identifying the version of a package specified in the Export-Package or Import-Package manifest header.

The attribute value is encoded in the Export-Package or Import-Package manifest header like:

Import-Package: org.osgi.framework; version=”1.1”

Since 1.3VISIBILITY_DIRECTIVE

6.1.12.70 public static final String VISIBILITY_DIRECTIVE = “visibility”

Manifest header directive (named “visibility”) identifying the visibility of a reqiured bundle in the Require-Bundle manifest header.

The directive value is encoded in the Require-Bundle manifest header like:

Require-Bundle: com.acme.module.test; visibility:=”reex-port”

See Also Constants.VISIBILITY_PRIVATE[p.166] , Constants.VISIBILITY_REEXPORT[p.167]

Since 1.3VISIBILITY_PRIVATE

6.1.12.71 public static final String VISIBILITY_PRIVATE = “private”

Manifest header directive value (named “private”) identifying a private visi-bility type. A private visibility type indicates that any packages that are exported by the required bundle are not made visible on the export signa-ture of the requiring bundle.

The directive value is encoded in the Require-Bundle manifest header like:

Require-Bundle: com.acme.module.test; visibility:=”private”

See Also Constants.VISIBILITY_DIRECTIVE[p.166]

Since 1.3

166-268 OSGi Service Platform Release 4

Page 175: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

VISIBILITY_REEXPORT

6.1.12.72 public static final String VISIBILITY_REEXPORT = “reexport”

Manifest header directive value (named “reexport”) identifying a reexport visibility type. A reexport visibility type indicates any packages that are exported by the required bundle are re-exported by the requiring bundle. Any arbitrary arbitrary matching attributes with which they were exported by the required bundle are deleted.

The directive value is encoded in the Require-Bundle manifest header like:

Require-Bundle: com.acme.module.test; visibility:=”reex-port”

See Also Constants.VISIBILITY_DIRECTIVE[p.166]

Since 1.3Filter

6.1.13 public interface FilterAn RFC 1960-based Filter.

Filter objects can be created by calling BundleContext.createF i lter [p.139] with the chosen filter string.

A Filter object can be used numerous times to determine if the match argu-ment matches the filter string that was used to create the Filter object.

Some examples of LDAP filters are:

“(cn=Babs Jensen)”“(!(cn=Tim Howes))”“(&(” + Constants.OBJECTCLASS +

“=Person)(|(sn=Jensen)(cn=Babs J*)))”“(o=univ*of*mich*)”

See Also Framework specification for a description of the filter string syntax.

Since 1.1equals(Object)

6.1.13.1 public boolean equals( Object obj )

obj The object to compare against this Filter object.

Compares this Filter object to another object.

Returns If the other object is a Filter object, then returns this.toString().equals(obj.toString();false otherwise.hashCode()

6.1.13.2 public int hashCode( )

Returns the hashCode for this Filter object.

Returns The hashCode of the filter string; that is, this.toString().hashCode().match(ServiceReference)

6.1.13.3 public boolean match( ServiceReference reference )

reference The reference to the service whose properties are used in the match.

Filter using a service’s properties.

The filter is executed using the keys and values of the referenced service’s properties. The keys are case insensitively matched with the filter.

Returns true if the service’s properties match this filter; false otherwise.

OSGi Service Platform Release 4 167-268

Page 176: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

match(Dictionary)

6.1.13.4 public boolean match( Dictionary dictionary )

dictionary The Dictionary object whose keys are used in the match.

Filter using a Dictionary object. The Filter is executed using the Dictionary object’s keys and values. The keys are case insensitively matched with the filter.

Returns true if the Dictionary object’s keys and values match this filter; false other-wise.

Throws IllegalArgumentException – If dictionary contains case variants of the same key name. matchCase(Dictionary)

6.1.13.5 public boolean matchCase( Dictionary dictionary )

dictionary The Dictionary object whose keys are used in the match.

Filter with case sensitivity using a Dictionary object. The Filter is executed using the Dictionary object’s keys and values. The keys are case sensitively matched with the filter.

Returns true if the Dictionary object’s keys and values match this filter; false other-wise.

Since 1.3toString()

6.1.13.6 public String toString( )

Returns this Filter object’s filter string.

The filter string is normalized by removing whitespace which does not affect the meaning of the filter.

Returns Filter string.FrameworkEvent

6.1.14 public class FrameworkEventextends EventObjectA general event from the Framework.

FrameworkEvent is the event class used when notifying listeners of general events occuring within the OSGI environment. A type code is used to iden-tify the event type for future extendability.

OSGi Alliance reserves the right to extend the set of event types.ERROR

6.1.14.1 public static final int ERROR = 2

An error has occurred.

There was an error associated with a bundle.

The value of ERROR is 0x00000002.INFO

6.1.14.2 public static final int INFO = 32

An informational event has occurred.

There was an informational event associated with a bundle.

The value of INFO is 0x00000020.

Since 1.3PACKAGES_REFRESHED

168-268 OSGi Service Platform Release 4

Page 177: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6.1.14.3 public static final int PACKAGES_REFRESHED = 4

A PackageAdmin.refreshPackage operation has completed.

This event is fired when the Framework has completed the refresh packages operation initiated by a call to the PackageAdmin.refreshPackages method.

The value of PACKAGES_REFRESHED is 0x00000004.

See Also PackageAdmin.refreshPackages

Since 1.2STARTED

6.1.14.4 public static final int STARTED = 1

The Framework has started.

This event is fired when the Framework has started after all installed bun-dles that are marked to be started have been started and the Framework has reached the intitial start level.

The value of STARTED is 0x00000001.

See Also StartLevelSTARTLEVEL_CHANGED

6.1.14.5 public static final int STARTLEVEL_CHANGED = 8

A StartLevel.setStartLevel operation has completed.

This event is fired when the Framework has completed changing the active start level initiated by a call to the StartLevel.setStartLevel method.

The value of STARTLEVEL_CHANGED is 0x00000008.

See Also StartLevel

Since 1.2WARNING

6.1.14.6 public static final int WARNING = 16

A warning has occurred.

There was a warning associated with a bundle.

The value of WARNING is 0x00000010.

Since 1.3FrameworkEvent(int,Object)

6.1.14.7 public FrameworkEvent( int type, Object source )

type The event type.

source The event source object. This may not be null.

Creates a Framework event.

Deprecated Since 1.2. This constructor is deprecated in favor of using the other construc-tor with the System Bundle as the event source.FrameworkEvent(int,Bundle,Throwable)

6.1.14.8 public FrameworkEvent( int type, Bundle bundle, Throwable throwable )

type The event type.

bundle The event source.

throwable The related exception. This argument may be null if there is no related excep-tion.

Creates a Framework event regarding the specified bundle.

OSGi Service Platform Release 4 169-268

Page 178: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

getBundle()

6.1.14.9 public Bundle getBundle( )

Returns the bundle associated with the event. This bundle is also the source of the event.

Returns The bundle associated with the event.getThrowable()

6.1.14.10 public Throwable getThrowable( )

Returns the exception related to this event.

Returns The related exception or null if none.getType()

6.1.14.11 public int getType( )

Returns the type of framework event.

The type values are:

• STARTED [p.169]• ERROR [p.168]• WARNING [p.169]• INFO [p.168]• PACKAGES_REFRESHED [p.168]• STARTLEVEL_CHANGED [p.169]

Returns The type of state change.FrameworkListener

6.1.15 public interface FrameworkListenerextends EventListenerA FrameworkEvent listener. When a FrameworkEvent is fired, it is asyn-chronously delivered to a FrameworkListener.

FrameworkListener is a listener interface that may be implemented by a bundle developer. A FrameworkListener object is registered with the Frame-work using the BundleContext.addFrameworkLis tener [p.138] method. FrameworkListener objects are called with a FrameworkEvent objects when the Framework starts and when asynchronous errors occur.

See Also FrameworkEvent[p.168]frameworkEvent(FrameworkEvent)

6.1.15.1 public void frameworkEvent( FrameworkEvent event )

event The FrameworkEvent object.

Receives notification of a general FrameworkEvent object. FrameworkUtil

6.1.16 public class FrameworkUtilFramework Utility class.

This class contains utility methods which access Framework functions that may be useful to bundles.

Since 1.3createFilter(String)

6.1.16.1 public static Filter createFilter( String filter ) throws InvalidSyntaxException

filter The filter string.

170-268 OSGi Service Platform Release 4

Page 179: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

Creates a Filter object. This Filter object may be used to match a ServiceRef-erence object or a Dictionary object.

If the filter cannot be parsed, an Inva lidSyntaxException [p.171] will be thrown with a human readable message where the filter became unpars-able.

Returns A Filter object encapsulating the filter string.

Throws InvalidSyntaxException – If filter contains an invalid filter string that can-not be parsed.

NullPointerException – If filter is null.

See Also Filter[p.167]InvalidSyntaxException

6.1.17 public class InvalidSyntaxExceptionextends ExceptionA Framework exception.

An InvalidSyntaxException object indicates that a filter string parameter has an invalid syntax and cannot be parsed.

See Fi l ter [p.167] for a description of the filter string syntax.InvalidSyntaxException(String,String)

6.1.17.1 public InvalidSyntaxException( String msg, String filter )

msg The message.

filter The invalid filter string.

Creates an exception of type InvalidSyntaxException.

This method creates an InvalidSyntaxException object with the specified message and the filter string which generated the exception.InvalidSyntaxException(String,String,Throwable)

6.1.17.2 public InvalidSyntaxException( String msg, String filter, Throwable cause )

msg The message.

filter The invalid filter string.

cause The cause of this exception.

Creates an exception of type InvalidSyntaxException.

This method creates an InvalidSyntaxException object with the specified message and the filter string which generated the exception.

Since 1.3getCause()

6.1.17.3 public Throwable getCause( )

Returns the cause of this exception or null if no cause was specified when this exception was created.

Returns The cause of this exception or null if no cause was specified.

Since 1.3getFilter()

6.1.17.4 public String getFilter( )

Returns the filter string that generated the InvalidSyntaxException object.

OSGi Service Platform Release 4 171-268

Page 180: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

Returns The invalid filter string.

See Also BundleContext.getServiceReferences[p.143] , BundleContext.addServiceListener(ServiceListener,String)[p.138]initCause(Throwable)

6.1.17.5 public Throwable initCause( Throwable cause )

cause Cause of the exception.

The cause of this exception can only be set when constructed.

Returns This object.

Throws IllegalStateException – This method will always throw an IllegalState-Exception since the cause of this exception can only be set when constructed.

Since 1.3PackagePermission

6.1.18 public final class PackagePermissionextends BasicPermissionA bundle’s authority to import or export a package.

A package is a dot-separated string that defines a fully qualified Java pack-age.

For example:

org.osgi.service.http

PackagePermission has two actions: EXPORT and IMPORT. The EXPORT action implies the IMPORT action.EXPORT

6.1.18.1 public static final String EXPORT = “export”

The action string export. IMPORT

6.1.18.2 public static final String IMPORT = “import”

The action string import. PackagePermission(String,String)

6.1.18.3 public PackagePermission( String name, String actions )

name Package name.

actions EXPORT,IMPORT (canonical order).

Defines the authority to import and/or export a package within the OSGi environment.

The name is specified as a normal Java package name: a dot-separated string. Wildcards may be used. For example:

org.osgi.service.httpjavax.servlet.**

Package Permissions are granted over all possible versions of a package. A bundle that needs to export a package must have the appropriate PackageP-ermission for that package; similarly, a bundle that needs to import a pack-age must have the appropriate PackagePermssion for that package.

Permission is granted for both classes and resources.equals(Object)

172-268 OSGi Service Platform Release 4

Page 181: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6.1.18.4 public boolean equals( Object obj )

obj The object to test for equality with this PackagePermission object.

Determines the equality of two PackagePermission objects. This method checks that specified package has the same package name and PackagePer-mission actions as this PackagePermission object.

Returns true if obj is a PackagePermission, and has the same package name and ac-tions as this PackagePermission object; false otherwise.getActions()

6.1.18.5 public String getActions( )

Returns the canonical string representation of the PackagePermission actions.

Always returns present PackagePermission actions in the following order: EXPORT,IMPORT.

Returns Canonical string representation of the PackagePermission actions.hashCode()

6.1.18.6 public int hashCode( )

Returns the hash code value for this object.

Returns A hash code value for this object.implies(Permission)

6.1.18.7 public boolean implies( Permission p )

p The target permission to interrogate.

Determines if the specified permission is implied by this object.

This method checks that the package name of the target is implied by the package name of this object. The list of PackagePermission actions must either match or allow for the list of the target object to imply the target PackagePermission action.

The permission to export a package implies the permission to import the named package.

x.y.*,”export” -> x.y.z,”export” is true*,”import” -> x.y, “import” is true*,”export” -> x.y, “import” is truex.y,”export” -> x.y.z, “export” is false

Returns true if the specified PackagePermission action is implied by this object; false otherwise.newPermissionCollection()

6.1.18.8 public PermissionCollection newPermissionCollection( )

Returns a new PermissionCollection object suitable for storing PackagePer-mission objects.

Returns A new PermissionCollection object.ServiceEvent

6.1.19 public class ServiceEventextends EventObjectAn event from the Framework describing a service lifecycle change.

ServiceEvent objects are delivered to a ServiceListener objects when a change occurs in this service’s lifecycle. A type code is used to identify the event type for future extendability.

OSGi Service Platform Release 4 173-268

Page 182: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

OSGi Alliance reserves the right to extend the set of types.

See Also ServiceListener[p.176]MODIFIED

6.1.19.1 public static final int MODIFIED = 2

The properties of a registered service have been modified.

This event is synchronously delivered after the service properties have been modified.

The value of MODIFIED is 0x00000002.

See Also ServiceRegistration.setProperties[p.180]REGISTERED

6.1.19.2 public static final int REGISTERED = 1

This service has been registered.

This event is synchronously delivered after the service has been registered with the Framework.

The value of REGISTERED is 0x00000001.

See Also BundleContext.registerService(String[],Object,java.util.Dictionary)[p.145]UNREGISTERING

6.1.19.3 public static final int UNREGISTERING = 4

This service is in the process of being unregistered.

This event is synchronously delivered before the service has completed unregistering.

If a bundle is using a service that is UNREGISTERING, the bundle should release its use of the service when it receives this event. If the bundle does not release its use of the service when it receives this event, the Framework will automatically release the bundle’s use of the service while completing the service unregistration operation.

The value of UNREGISTERING is 0x00000004.

See Also ServiceRegistration.unregister[p.180] , BundleContext.ungetService[p.147]ServiceEvent(int,ServiceReference)

6.1.19.4 public ServiceEvent( int type, ServiceReference reference )

type The event type.

reference A ServiceReference object to the service that had a lifecycle change.

Creates a new service event object. getServiceReference()

6.1.19.5 public ServiceReference getServiceReference( )

Returns a reference to the service that had a change occur in its lifecycle.

This reference is the source of the event.

Returns Reference to the service that had a lifecycle change.getType()

6.1.19.6 public int getType( )

Returns the type of event. The event type values are:

• REGISTERED [p.174]• MODIFIED [p.174]

174-268 OSGi Service Platform Release 4

Page 183: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

• UNREGISTER ING [p.174]

Returns Type of service lifecycle change.ServiceFactory

6.1.20 public interface ServiceFactoryAllows services to provide customized service objects in the OSGi environ-ment.

When registering a service, a ServiceFactory object can be used instead of a service object, so that the bundle developer can gain control of the specific service object granted to a bundle that is using the service.

When this happens, the BundleContext.getService(ServiceReference) method calls the ServiceFactory.getService method to create a service object specifically for the requesting bundle. The service object returned by the ServiceFactory object is cached by the Framework until the bundle releases its use of the service.

When the bundle’s use count for the service equals zero (including the bun-dle stopping or the service being unregistered), the ServiceFactory.ungetSer-vice method is called.

ServiceFactory objects are only used by the Framework and are not made available to other bundles in the OSGi environment.

See Also BundleContext.getService[p.142]getService(Bundle,ServiceRegistration)

6.1.20.1 public Object getService( Bundle bundle, ServiceRegistration registration )

bundle The bundle using the service.

registration The ServiceRegistration object for the service.

Creates a new service object.

The Framework invokes this method the first time the specified bundle requests a service object using the BundleContext.getService(ServiceRefer-ence) method. The service factory can then return a specific service object for each bundle.

The Framework caches the value returned (unless it is null), and will return the same service object on any future call to BundleContext.getService from the same bundle.

The Framework will check if the returned service object is an instance of all the classes named when the service was registered. If not, then null is returned to the bundle.

Returns A service object that must be an instance of all the classes named when the service was registered.

See Also BundleContext.getService[p.142]ungetService(Bundle,ServiceRegistration,Object)

6.1.20.2 public void ungetService( Bundle bundle, ServiceRegistration registration, Object service )

bundle The bundle releasing the service.

registration The ServiceRegistration object for the service.

OSGi Service Platform Release 4 175-268

Page 184: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

service The service object returned by a previous call to the ServiceFactory.getSer-vice method.

Releases a service object.

The Framework invokes this method when a service has been released by a bundle. The service object may then be destroyed.

See Also BundleContext.ungetService[p.147]ServiceListener

6.1.21 public interface ServiceListenerextends EventListenerA ServiceEvent listener. When a ServiceEvent is fired, it is synchronously delivered to a BundleListener.

ServiceListener is a listener interface that may be implemented by a bundle developer.

A ServiceListener object is registered with the Framework using the Bundle-Context.addServiceListener method. ServiceListener objects are called with a ServiceEvent object when a service is registered, modified, or is in the pro-cess of unregistering.

ServiceEvent object delivery to ServiceListener objects is filtered by the fil-ter specified when the listener was registered. If the Java Runtime Environ-ment supports permissions, then additional filtering is done. ServiceEvent objects are only delivered to the listener if the bundle which defines the lis-tener object’s class has the appropriate ServicePermission to get the service using at least one of the named classes the service was registered under.

ServiceEvent object delivery to ServiceListener objects is further filtered according to package sources as defined in ServiceReference. isAssigna-bleTo(Bundle , St r ing) [p.179] .

See Also ServiceEvent[p.173] , ServicePermission[p.176]serviceChanged(ServiceEvent)

6.1.21.1 public void serviceChanged( ServiceEvent event )

event The ServiceEvent object.

Receives notification that a service has had a lifecycle change. ServicePermission

6.1.22 public final class ServicePermissionextends BasicPermissionIndicates a bundle’s authority to register or get a service.

• The ServicePermission.REGISTER action allows a bundle to register a service on the specified names.

• The ServicePermission.GET action allows a bundle to detect a service and get it.

ServicePermission to get the specific service. GET

6.1.22.1 public static final String GET = “get”

The action string get (Value is “get”). REGISTER

176-268 OSGi Service Platform Release 4

Page 185: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6.1.22.2 public static final String REGISTER = “register”

The action string register (Value is “register”). ServicePermission(String,String)

6.1.22.3 public ServicePermission( String name, String actions )

name class name

actions get,register (canonical order)

Create a new ServicePermission.

The name of the service is specified as a fully qualified class name.

ClassName ::= <class name> | <class name ending in “.*”>

Examples:

org.osgi.service.http.HttpServiceorg.osgi.service.http.*org.osgi.service.snmp.*

There are two possible actions: get and register. The get permission allows the owner of this permission to obtain a service with this name. The register permission allows the bundle to register a service under that name.equals(Object)

6.1.22.4 public boolean equals( Object obj )

obj The object to test for equality.

Determines the equalty of two ServicePermission objects. Checks that speci-fied object has the same class name and action as this ServicePermission.

Returns true if obj is a ServicePermission, and has the same class name and actions as this ServicePermission object; false otherwise.getActions()

6.1.22.5 public String getActions( )

Returns the canonical string representation of the actions. Always returns present actions in the following order: get, register.

Returns The canonical string representation of the actions.hashCode()

6.1.22.6 public int hashCode( )

Returns the hash code value for this object.

Returns Hash code value for this object.implies(Permission)

6.1.22.7 public boolean implies( Permission p )

p The target permission to check.

Determines if a ServicePermission object “implies” the specified permission.

Returns true if the specified permission is implied by this object; false otherwise.newPermissionCollection()

6.1.22.8 public PermissionCollection newPermissionCollection( )

Returns a new PermissionCollection object for storing ServicePermission objects.

Returns A new PermissionCollection object suitable for storing ServicePermission objects.ServiceReference

OSGi Service Platform Release 4 177-268

Page 186: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.23 public interface ServiceReferenceA reference to a service.

The Framework returns ServiceReference objects from the BundleCon-text.getServiceReference and BundleContext.getServiceReferences methods.

A ServiceReference object may be shared between bundles and can be used to examine the properties of the service and to get the service object.

Every service registered in the Framework has a unique ServiceRegistration object and may have multiple, distinct ServiceReference objects referring to it. ServiceReference objects associated with a ServiceRegistration object have the same hashCode and are considered equal (more specifically, their equals() method will return true when compared).

If the same service object is registered multiple times, ServiceReference objects associated with different ServiceRegistration objects are not equal.

See Also BundleContext.getServiceReference[p.142] , BundleContext.getServiceReferences[p.143] , BundleContext.getService[p.142]getBundle()

6.1.23.1 public Bundle getBundle( )

Returns the bundle that registered the service referenced by this ServiceRef-erence object.

This method must return null when the service has been unregistered. This can be used to determine if the service has been unregistered.

Returns The bundle that registered the service referenced by this ServiceReference object; null if that service has already been unregistered.

See Also BundleContext.registerService(String[],Object,java.util.Dictionary)[p.145]getProperty(String)

6.1.23.2 public Object getProperty( String key )

key The property key.

Returns the property value to which the specified property key is mapped in the properties Dictionary object of the service referenced by this ServiceRef-erence object.

Property keys are case-insensitive.

This method must continue to return property values after the service has been unregistered. This is so references to unregistered services (for exam-ple, ServiceReference objects stored in the log) can still be interrogated.

Returns The property value to which the key is mapped; null if there is no property named after the key.getPropertyKeys()

6.1.23.3 public String[] getPropertyKeys( )

Returns an array of the keys in the properties Dictionary object of the ser-vice referenced by this ServiceReference object.

This method will continue to return the keys after the service has been unregistered. This is so references to unregistered services (for example, Ser-viceReference objects stored in the log) can still be interrogated.

178-268 OSGi Service Platform Release 4

Page 187: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

This method is case-preserving ; this means that every key in the returned array must have the same case as the corresponding key in the properties Dictionary that was passed to the BundleContext .reg isterService(Str ing[] ,Object, java.uti l .D ict ionary) [p.145] or ServiceRegist rat ion.setPropert ies [p.180] methods.

Returns An array of property keys.getUsingBundles()

6.1.23.4 public Bundle[] getUsingBundles( )

Returns the bundles that are using the service referenced by this ServiceRef-erence object. Specifically, this method returns the bundles whose usage count for that service is greater than zero.

Returns An array of bundles whose usage count for the service referenced by this Ser-viceReference object is greater than zero; null if no bundles are currently us-ing that service.

Since 1.1isAssignableTo(Bundle,String)

6.1.23.5 public boolean isAssignableTo( Bundle bundle, String className )

bundle The Bundle object to check.

className The class name to check.

Tests if the bundle that registered the service referenced by this ServiceRef-erence and the specified bundle use the same source for the package of the specified class name.

This method performs the following checks:

1 Get the package name from the specified class name.2 For the bundle that registered the service referenced by this ServiceRef-

erence (registrant bundle); find the source for the package. If no source is found then return true if the registrant bundle is equal to the specified bundle; otherwise return false.

3 If the package source of the registrant bundle is equal to the package source of the specified bundle then return true; otherwise return false.

Returns true if the bundle which registered the service referenced by this ServiceRef-erence and the specified bundle use the same source for the package of the specified class name. Otherwise false is returned.

Since 1.3ServiceRegistration

6.1.24 public interface ServiceRegistrationA registered service.

The Framework returns a ServiceRegistration object when a BundleCon-text.registerService method invocation is successful. The ServiceRegistra-tion object is for the private use of the registering bundle and should not be shared with other bundles.

The ServiceRegistration object may be used to update the properties of the service or to unregister the service.

See Also BundleContext.registerService(String[],Object,Dictionary)[p.145]getReference()

OSGi Service Platform Release 4 179-268

Page 188: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.24.1 public ServiceReference getReference( )

Returns a ServiceReference object for a service being registered.

The ServiceReference object may be shared with other bundles.

Returns ServiceReference object.

Throws IllegalStateException – If this ServiceRegistration object has already been unregistered. setProperties(Dictionary)

6.1.24.2 public void setProperties( Dictionary properties )

properties The properties for this service. See Constants [p.153] for a list of standard service property keys. Changes should not be made to this object after calling this method. To update the service’s properties this method should be called again.

Updates the properties associated with a service.

The Constants .OB JECTCLASS [p.162] and Constants.SERVICE_ ID [p.163] keys cannot be modified by this method. These values are set by the Frame-work when the service is registered in the OSGi environment.

The following steps are required to modify service properties:

1 The service’s properties are replaced with the provided properties. 2 A service event of type ServiceEvent .MODIF IED [p.174] is fired.

Throws IllegalStateException – If this ServiceRegistration object has already been unregistered.

IllegalArgumentException – If properties contains case variants of the same key name. unregister()

6.1.24.3 public void unregister( )

Unregisters a service. Remove a ServiceRegistration object from the Frame-work service registry. All ServiceReference objects associated with this Ser-viceRegistration object can no longer be used to interact with the service.

The following steps are required to unregister a service:

1 The service is removed from the Framework service registry so that it can no longer be used. ServiceReference objects for the service may no longer be used to get a service object for the service.

2 A service event of type ServiceEvent .UNREGISTERING [p.174] is fired so that bundles using this service can release their use of it.

3 For each bundle whose use count for this service is greater than zero: The bundle’s use count for this service is set to zero. If the service was registered with a ServiceFactory [p.175] object, the Ser-viceFactory.ungetService method is called to release the service object for the bundle.

Throws IllegalStateException – If this ServiceRegistration object has already been unregistered.

See Also BundleContext.ungetService[p.147] , ServiceFactory.ungetService[p.175]SynchronousBundleListener

180-268 OSGi Service Platform Release 4

Page 189: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

6.1.25 public interface SynchronousBundleListenerextends BundleListenerA synchronous BundleEvent listener. When a BundleEvent is fired, it is syn-chronously delivered to a BundleListener.

SynchronousBundleListener is a listener interface that may be imple-mented by a bundle developer.

A SynchronousBundleListener object is registered with the Framework using the BundleContext .addBundleListener [p.137] method. Synchronous-BundleListener objects are called with a BundleEvent object when a bundle has been installed, resolved, starting, started, stopping, stopped, updated, unresolved, or uninstalled.

Unlike normal BundleListener objects, SynchronousBundleListeners are synchronously called during bundle lifecycle processing. The bundle lifecy-cle processing will not proceed until all SynchronousBundleListeners have completed. SynchronousBundleListener objects will be called prior to BundleListener objects.

AdminPermission[bundle,LISTENER] is required to add or remove a Syn-chronousBundleListener object.

See Also BundleEvent[p.148]

Since 1.1Version

6.1.26 public class Versionimplements ComparableVersion identifier for bundles and packages.

Version identifiers have four components.

1 Major version. A non-negative integer.2 Minor version. A non-negative integer.3 Micro version. A non-negative integer.4 Qualifier. A text string. See Version(String) for the format of the qualifier

string.

Version objects are immutable.

Since 1.3emptyVersion

6.1.26.1 public static final Version emptyVersion

The empty version “0.0.0”. Equivalent to calling new Version(0,0,0). Version(int,int,int)

6.1.26.2 public Version( int major, int minor, int micro )

major Major component of the version identifier.

minor Minor component of the version identifier.

micro Micro component of the version identifier.

Creates a version identifier from the specified numerical components.

The qualifier is set to the empty string.

Throws IllegalArgumentException – If the numerical components are negative. Version(int,int,int,String)

OSGi Service Platform Release 4 181-268

Page 190: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

6.1.26.3 public Version( int major, int minor, int micro, String qualifier )

major Major component of the version identifier.

minor Minor component of the version identifier.

micro Micro component of the version identifier.

qualifier Qualifier component of the version identifier. If null is specified, then the qualifier will be set to the empty string.

Creates a version identifier from the specifed components.

Throws IllegalArgumentException – If the numerical components are negative or the qualifier string is invalid. Version(String)

6.1.26.4 public Version( String version )

version String representation of the version identifier.

Created a version identifier from the specified string.

Here is the grammar for version strings.

version ::= major(’.’minor(’.’micro(’.’qualifier)?)?)?major ::= digit+minor ::= digit+micro ::= digit+qualifier ::= (alpha|digit|’_’|’-’)+digit ::= [0..9]alpha ::= [a..zA..Z]

There must be no whitespace in version.

Throws IllegalArgumentException – If version is improperly formatted. compareTo(Object)

6.1.26.5 public int compareTo( Object object )

object The Version object to be compared.

Compares this Version object to another object.

A version is considered to be less than another version if its major compo-nent is less than the other version’s major component, or the major compo-nents are equal and its minor component is less than the other version’s minor component, or the major and minor components are equal and its micro component is less than the other version’s micro component, or the major, minor and micro components are equal and it’s qualifier component is less than the other version’s qualifier component (using String.comp-areTo).

A version is considered to be equal to another version if the major, minor and micro components are equal and the qualifier component is equal (using String.compareTo).

Returns A negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified Version object.

Throws ClassCastException – If the specified object is not a Version. equals(Object)

6.1.26.6 public boolean equals( Object object )

object The Version object to be compared.

Compares this Version object to another object.

182-268 OSGi Service Platform Release 4

Page 191: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework API Version 1.3 org.osgi.framework

A version is considered to be equal to another version if the major, minor and micro components are equal and the qualifier component is equal (using String.equals).

Returns true if object is a Version and is equal to this object; false otherwise.getMajor()

6.1.26.7 public int getMajor( )

Returns the major component of this version identifier.

Returns The major component.getMicro()

6.1.26.8 public int getMicro( )

Returns the micro component of this version identifier.

Returns The micro component.getMinor()

6.1.26.9 public int getMinor( )

Returns the minor component of this version identifier.

Returns The minor component.getQualifier()

6.1.26.10 public String getQualifier( )

Returns the qualifier component of this version identifier.

Returns The qualifier component.hashCode()

6.1.26.11 public int hashCode( )

Returns a hash code value for the object.

Returns An integer which is a hash code value for this object.parseVersion(String)

6.1.26.12 public static Version parseVersion( String version )

version String representation of the version identifier. Leading and trailing whitespace will be ignored.

Parses a version identifier from the specified string.

See Version(String) for the format of the version string.

Returns A Version object representing the version identifier. If version is null or the empty string then emptyVersion will be returned.

Throws IllegalArgumentException – If version is improperly formatted. toString()

6.1.26.13 public String toString( )

Returns the string representation of this version identifier.

The format of the version string will be major.minor.micro if qualifier is the empty string or major.minor.micro.qualifier otherwise.

Returns The string representation of this version identifier.

OSGi Service Platform Release 4 183-268

Page 192: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.framework Framework API Version 1.3

184-268 OSGi Service Platform Release 4

Page 193: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Package Admin Service Specification Version 1.2 Introduction

7 Package Admin Service SpecificationVersion 1.2

7.1 IntroductionBundles can export packages to other bundles. This exporting creates a dependency between the bundle exporting a package and the bundle using the package. When the exporting bundle is uninstalled or updated, a deci-sion must be taken regarding any shared packages.

The Package Admin service provides an interface to let the Management Agent make this decision.

7.1.1 Essentials• Information – The Package Admin service must provide the sharing status

of all packages. This should include information about the importing bundles and exporting bundle.

• Policy – The Package Admin service must allow a management agent to provide a policy for package sharing when bundles are updated and uninstalled.

• Minimal update – Only bundles that depend on the package that needs to be resolved should have to be restarted when packages are forced to be refreshed.

7.1.2 Entities• PackageAdmin – The interface that provides access to the internal

Framework package sharing mechanism.• ExportedPackage – The interface provides package information and its

sharing status.• RequiredBundle – The interfaces provides information about the

bindings of required bundles.• Management Agent – A bundle that is provided by the Operator to

implement an Operator specific policy.

OSGi Service Platform Release 4 185-268

Page 194: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Package Admin Package Admin Service Specification Version 1.2

Figure 35 Class Diagram org.osgi.service.packageadmin

7.1.3 OperationThe Framework’s system bundle should provide a Package Admin service for the Management Agent. The Package Admin service must be registered under the org.osgi .service .packageadmin.PackageAdmin interface by the system bundle. It provides access to the internal structures of the Frame-work related to package sharing, fragments and required bundles. This is an optional singleton service, so at most one Package Admin service must be registered at any moment in time.

The Framework must always leave the package sharing intact for packages exported by a bundle that is uninstalled or updated. A Management Agent can then choose to force the framework to refresh these packages using the Package Admin service. A policy of always using the most current packages exported by installed bundles can be implemented with a Management Agent that watches Framework events for bundles being uninstalled or updated, and then refreshes the packages of those bundles using the Pack-age Admin service.

7.2 Package AdminThe Package Admin service is intended to allow a Management Agent to define the policy for managing package sharing. It provides methods for examining the status of the shared packages. It also allows the Management Agent to refresh the packages and stop and restart bundles as necessary.

7.2.1 Package SharingThe PackageAdmin class provides the following methods:

• getExportedPackage(Str ing) – Returns an ExportedPackage object that provides information about the requested package. This information can be used to make the decision to refresh the package.

• getExportedPackages(Bundle) – Returns a list of ExportedPackage objects for each package that the given bundle exports.

• ref reshPackages(Bundle[]) – The management agent may call this method to refresh the exported packages of the specified bundles. The

<<interface>>PackageAdmin

<<interface>>ExportedPackage

0..n1

<<interface>>Bundle

0..n

exported by

1

imported by

0..n

0..n

name

provides

<<interface>>Required Bundle

requiredbundles

requiring bundles 0..n0..n

fragment bundles

0..n

host0..n

1

1

1

0..n

1 1bundle

186-268 OSGi Service Platform Release 4

Page 195: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Package Admin Service Specification Version 1.2 Package Admin

actual work must happen asynchronously. The Framework must send a Framework.PACKAGES_REFRESHED when all packages have been refreshed.

• resolveBundles(Bundle[]) – The Framework must attempt to resolve the given bundles.

7.2.2 Bundle InformationThere is only the Bundle interface in the Framework API while bundles can perform different roles in the Framework. The Package Admin service pro-vides access to this structural information.

• getBundle(C lass) – Answer the bundle with the class loader that loaded the given class.

• getBundles(Str ing,Str ing)– Find a the set of bundles with the given bundle symbolic name and that fall within the given version. If the version is null, all bundles with the given bundle symbolic name are returned.

• getBundleType(Bundle) – Answer the type of the bundle. This is a bitmap of the different types. The following type is defined:• BUNDLE_TYPE_FRAGMENT– The bundle is a fragment.

7.2.3 Fragments and Required BundlesThe Package Admin service provides access to the network that is created by by requiring bundles and hosting fragments.

• getFragments(Bundle) – Return an array of bundles that currently act as fragment to the given bundle. If there are no fragments attached, null must be returned.

• getHosts(Bundle) – Return the bundle that acts as host to this fragment bundle. The given bundle should be an attached fragment bundle, oth-erwise null is returned.

• getRequiredBundles(Str ing) – Return an array of Requ iredBundle objects that match the given name (or all of the given name is nul l). The RequiredBundle object provides structural information about a required bundle.

7.2.4 Exported PackageInformation about the shared packages is provided by the ExportedPackage objects. These objects provide detailed information about the bundles that import and export the package. This information can be used by a Manage-ment Agent to guide its decisions.

7.2.5 Refreshing Packages and Start Level ServiceBundles may be stopped and later started when the ref reshPackages(Bun-dle[]) method is called. If the Start Level Service is present, the stopping and starting of bundles must not violate the start level constraints. This implies that bundles with a higher start level must be stopped before bundles with a lower start level are stopped. Vice versa, bundles should not be started before all the bundles with a lower start level are started. See Startup Sequence on page 199.

OSGi Service Platform Release 4 187-268

Page 196: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Package Admin Service Specification Version 1.2

7.3 SecurityThe Package Admin service is a system service that can easily be abused because it provides access to the internal data structures of the Framework. Many bundles may have the ServicePermission [org .osg i .serv ice .packageadmin.PackageAdmin , GET] because AdminPermiss ion[System Bundle , RESOLVE] is required for calling any of the methods that modify the environment. No bundle must have ServicePermission [org .osg i .serv ice .packageadmin.PackageAdmin , REGISTER] , because only the Framework itself should register such a system service.

This service is intended for use by a Management Agent.

7.4 ChangesPackage Admin has been extended to support the new features introduced in the module layer.

• getExportedPackages(Str ing) – Provide access to exported packages via their name.

• resolveBundles(Bundle[]) – Force the resolving of a set of bundles.• getFragments(Bundle) – Return the fragments associated with a given

bundle.• getHosts(Bundle) – Return the host of a given bundle.• getRequiredBundles(Str ing) – Returns an array RequiredBundle objects

for the given symbolic name. • getBundles(Str ing,Str ing) – Return a bundle given its symbolic name

and version.• getBundleType(Bundle) – Find out the type of a bundle; currently only

the fragment type is supported.

7.5 org.osgi.service.packageadminThe OSGi Package Admin service Package. Specification Version 1.2.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle’s manifest. For example:

Import-Package: org.osgi.service.packageadmin; version=1.2

7.5.1 Summary• ExportedPackage - An exported package. [p.188]• PackageAdmin - Framework service which allows bundle programmers

to inspect the package wiring state of bundles in the Framework as well as other functions related to the class loader network among bundles. [p.190]

• RequiredBundle - A required bundle. [p.193]ExportedPackage

188-268 OSGi Service Platform Release 4

Page 197: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Package Admin Service Specification Version 1.2 org.osgi.service.packageadmin

7.5.2 public interface ExportedPackageAn exported package. Objects implementing this interface are created by the Package Admin service.

The term exported package refers to a package that has been exported from a resolved bundle. This package may or may not be currently wired to other bundles.

The information about an exported package provided by this object may change. An ExportedPackage object becomes stale if the package it refer-ences has been updated or removed as a result of calling PackageAd-min.refreshPackages(). If this object becomes stale, its getName() and getVersion() methods continue to return their original values, isRemoval-Pending() returns true, and getExportingBundle() and getImportingBun-dles() return null.getExportingBundle()

7.5.2.1 public Bundle getExportingBundle( )

Returns the bundle exporting the package associated with this exported package.

Returns The exporting bundle, or null if this ExportedPackage object has become stale.getImportingBundles()

7.5.2.2 public Bundle[] getImportingBundles( )

Returns the resolved bundles that are currently wired to this exported pack-age.

Bundles which require the exporting bundle associated with this exported package are considered to be wired to this exported package are included in the returned array. See RequiredBundle.getRequir ingBundles() [p.194] .

Returns The array of resolved bundles currently wired to this exported package, or null if this ExportedPackage object has become stale.getName()

7.5.2.3 public String getName( )

Returns the name of the package associated with this exported package.

Returns The name of this exported package.getSpecificationVersion()

7.5.2.4 public String getSpecificationVersion( )

Returns the version of this exported package.

Returns The version of this exported package, or null if no version information is available.

Deprecated Since 1.2. This method has been replaced by getVersion[p.189] .getVersion()

7.5.2.5 public Version getVersion( )

Returns the version of this exported package.

Returns The version of this exported package, or Version.emptyVersion if no version information is available.

Since 1.2isRemovalPending()

OSGi Service Platform Release 4 189-268

Page 198: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.packageadmin Package Admin Service Specification Version 1.2

7.5.2.6 public boolean isRemovalPending( )

Returns true if the package associated with this ExportedPackage object has been exported by a bundle that has been updated or uninstalled.

Returns true if the associated package is being exported by a bundle that has been up-dated or uninstalled, or if this ExportedPackage object has become stale; false otherwise.PackageAdmin

7.5.3 public interface PackageAdminFramework service which allows bundle programmers to inspect the pack-age wiring state of bundles in the Framework as well as other functions related to the class loader network among bundles.

If present, there will only be a single instance of this service registered with the Framework.

See Also org.osgi.service.packageadmin.ExportedPackage[p.188] , org.osgi.service.packageadmin.RequiredBundle[p.193]BUNDLE_TYPE_FRAGMENT

7.5.3.1 public static final int BUNDLE_TYPE_FRAGMENT = 1

Bundle type indicating the bundle is a fragment bundle.

The value of BUNDLE_TYPE_FRAGMENT is 0x00000001.

Since 1.2getBundle(Class)

7.5.3.2 public Bundle getBundle( Class clazz )

clazz The class object from which to locate the bundle.

Returns the bundle from which the specified class is loaded. The class loader of the returned bundle must have been used to load the specified class. If the class was not loaded by a bundle class loader then null is returned.

Returns The bundle from which the specified class is loaded or null if the class was not loaded by a bundle class loader.

Since 1.2getBundles(String,String)

7.5.3.3 public Bundle[] getBundles( String symbolicName, String versionRange )

symbolicName The symbolic name of the desired bundles.

versionRange The version range of the desired bundles, or null if all versions are desired.

Returns the bundles with the specified symbolic name whose bundle ver-sion is within the specified version range. If no bundles are installed that have the specified symbolic name, then null is returned. If a version range is specified, then only the bundles that have the specified symbolic name and whose bundle versions belong to the specified version range are returned. The returned bundles are ordered by version in descending version order so that the first element of the array contains the bundle with the highest ver-sion.

Returns An array of bundles with the specified name belonging to the specified ver-sion range ordered in descending version order, or null if no bundles are found.

See Also org.osgi.framework.Constants.BUNDLE_VERSION_ATTRIBUTE

190-268 OSGi Service Platform Release 4

Page 199: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Package Admin Service Specification Version 1.2 org.osgi.service.packageadmin

Since 1.2getBundleType(Bundle)

7.5.3.4 public int getBundleType( Bundle bundle )

bundle The bundle for which to return the special type.

Returns the special type of the specified bundle. The bundle type values are:

• BUNDLE_TYPE_FRAGMENT [p.190]

If a bundle is not one or more of the defined types then 0x00000000 is returned.

Returns The special type of the bundle.

Since 1.2getExportedPackage(String)

7.5.3.5 public ExportedPackage getExportedPackage( String name )

name The name of the exported package to be returned.

Gets the exported package for the specified package name.

If there are multiple exported packages with specified name, the exported package with the highest version will be returned.

Returns The exported package, or null if no exported package with the specified name exists.

See Also getExportedPackages(String)[p.191]getExportedPackages(Bundle)

7.5.3.6 public ExportedPackage[] getExportedPackages( Bundle bundle )

bundle The bundle whose exported packages are to be returned, or null if all export-ed packages are to be returned. If the specified bundle is the system bundle (that is, the bundle with id zero), this method returns all the packages known to be exported by the system bundle. This will include the package specified by the org.osgi.framework.system.packages system property as well as any other package exported by the framework implementation.

Gets the exported packages for the specified bundle.

Returns An array of exported packages, or null if the specified bundle has no exported packages.getExportedPackages(String)

7.5.3.7 public ExportedPackage[] getExportedPackages( String name )

name The name of the exported packages to be returned.

Gets the exported packages for the specified package name.

Returns An array of the exported packages, or null if no exported packages with the specified name exists.

Since 1.2getFragments(Bundle)

7.5.3.8 public Bundle[] getFragments( Bundle bundle )

bundle The bundle whose attached fragment bundles are to be returned.

Returns an array of attached fragment bundles for the specified bundle. If the specified bundle is a fragment then null is returned. If no fragments are attached to the specified bundle then null is returned.

This method does not attempt to resolve the specified bundle. If the speci-fied bundle is not resolved then null is returned.

OSGi Service Platform Release 4 191-268

Page 200: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.packageadmin Package Admin Service Specification Version 1.2

Returns An array of fragment bundles or null if the bundle does not have any at-tached fragment bundles or the bundle is not resolved.

Since 1.2getHosts(Bundle)

7.5.3.9 public Bundle[] getHosts( Bundle bundle )

bundle The bundle whose host bundle is to be returned.

Returns an array containing the host bundle to which the specified frag-ment bundle is attached or null if the specified bundle is not attached to a host or is not a fragment bundle. A fragment may only be attached to a sin-gle host bundle.

Returns An array containing the host bundle or null if the bundle does not have a host bundle.

Since 1.2getRequiredBundles(String)

7.5.3.10 public RequiredBundle[] getRequiredBundles( String symbolicName )

symbolicName The bundle symbolic name or null for all required bundles.

Returns an array of required bundles having the specified symbolic name.

If null is specified, then all required bundles will be returned.

Returns An array of required bundles or null if no required bundles exist for the spec-ified symbolic name.

Since 1.2refreshPackages(Bundle[])

7.5.3.11 public void refreshPackages( Bundle[] bundles )

bundles The bundles whose exported packages are to be updated or removed, or null for all bundles updated or uninstalled since the last call to this method.

Forces the update (replacement) or removal of packages exported by the specified bundles.

If no bundles are specified, this method will update or remove any packages exported by any bundles that were previously updated or uninstalled since the last call to this method. The technique by which this is accomplished may vary among different Framework implementations. One permissible implementation is to stop and restart the Framework.

This method returns to the caller immediately and then performs the fol-lowing steps on a separate thread:

1 Compute a graph of bundles starting with the specified bundles. If no bundles are specified, compute a graph of bundles starting with bundle updated or uninstalled since the last call to this method. Add to the graph any bundle that is wired to a package that is currently exported by a bundle in the graph. The graph is fully constructed when there is no bundle outside the graph that is wired to a bundle in the graph. The graph may contain UNINSTALLED bundles that are currently still exporting packages.

2 Each bundle in the graph that is in the ACTIVE state will be stopped as described in the Bundle.stop method.

3 Each bundle in the graph that is in the RESOLVED state is unresolved and thus moved to the INSTALLED state. The effect of this step is that bundles in the graph are no longer RESOLVED.

192-268 OSGi Service Platform Release 4

Page 201: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Package Admin Service Specification Version 1.2 org.osgi.service.packageadmin

4 Each bundle in the graph that is in the UNINSTALLED state is removed from the graph and is now completely removed from the Framework.

5 Each bundle in the graph that was in the ACTIVE state prior to Step 2 is started as described in the Bundle.start method, causing all bundles required for the restart to be resolved. It is possible that, as a result of the previous steps, packages that were previously exported no longer are. Therefore, some bundles may be unresolvable until another bundle offering a compatible package for export has been installed in the Framework.

6 A framework event of type FrameworkEvent.PACKAGES_REFRESHED is fired.

For any exceptions that are thrown during any of these steps, a Frame-workEvent of type ERROR is fired containing the exception. The source bun-dle for these events should be the specific bundle to which the exception is related. If no specific bundle can be associated with the exception then the System Bundle must be used as the source bundle for the event.

Throws SecurityException – If the caller does not have AdminPermission[System Bundle,RESOLVE] and the Java runtime environment supports permissions. resolveBundles(Bundle[])

7.5.3.12 public boolean resolveBundles( Bundle[] bundles )

bundles The bundles to resolve or null to resolve all unresolved bundles installed in the Framework.

Resolve the specified bundles. The Framework must attempt to resolve the specified bundles that are unresolved. Additional bundles that are not included in the specified bundles may be resolved as a result of calling this method. A permissible implementation of this method is to attempt to resolve all unresolved bundles installed in the framework.

If null is specified then the Framework will attempt to resolve all unre-solved bundles. This method must not cause any bundle to be refreshed, stopped, or started. This method will not return until the operation has completed.

Returns true if all specified bundles are resolved;

Throws SecurityException – If the caller does not have AdminPermission[System Bundle,RESOLVE] and the Java runtime environment supports permissions.

Since 1.2RequiredBundle

7.5.4 public interface RequiredBundleA required bundle. Objects implementing this interface are created by the Package Admin service.

The term required bundle refers to a resolved bundle that has a bundle sym-bolic name and is not a fragment. That is, a bundle that may be required by other bundles. This bundle may or may not be currently required by other bundles.

OSGi Service Platform Release 4 193-268

Page 202: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.packageadmin Package Admin Service Specification Version 1.2

The information about a required bundle provided by this object may change. A RequiredBundle object becomes stale if an exported package of the bundle it references has been updated or removed as a result of calling PackageAdmin.refreshPackages()). If this object becomes stale, its getSym-bolicName() and getVersion() methods continue to return their original val-ues, isRemovalPending() returns true, and getBundle() and getRequiringBundles() return null.

Since 1.2getBundle()

7.5.4.1 public Bundle getBundle( )

Returns the bundle associated with this required bundle.

Returns The bundle, or null if this RequiredBundle object has become stale.getRequiringBundles()

7.5.4.2 public Bundle[] getRequiringBundles( )

Returns the bundles that currently require this required bundle.

If this required bundle is required and then re-exported by another bundle then all the requiring bundles of the re-exporting bundle are included in the returned array.

Returns An array of bundles currently requiring this required bundle, or null if this RequiredBundle object has become stale.getSymbolicName()

7.5.4.3 public String getSymbolicName( )

Returns the symbolic name of this required bundle.

Returns The symbolic name of this required bundle.getVersion()

7.5.4.4 public Version getVersion( )

Returns the version of this required bundle.

Returns The version of this required bundle, or Version.emptyVersion if no version information is available.isRemovalPending()

7.5.4.5 public boolean isRemovalPending( )

Returns true if the bundle associated with this RequiredBundle object has been updated or uninstalled.

Returns true if the reqiured bundle has been updated or uninstalled, or if the Re-quiredBundle object has become stale; false otherwise.

194-268 OSGi Service Platform Release 4

Page 203: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Specification Version 1.0 Introduction

8 Start Level Service SpecificationVersion 1.0

8.1 IntroductionThis specification describes how to enable a Management Agent to control the relative starting and stopping order of bundles in an OSGi Service Plat-form.

The Start Level service assigns each bundle a start level. The Management Agent can modify the start levels for bundles and set the active start level of the Framework, which will start and stop the appropriate bundles. Only bundles that have a start level less or equal to this active start level must be active.

The purpose of the Start Level service is to allow the Management Agent to control, in detail, what bundles will be started and stopped and when this occurs.

8.1.1 Essentials• Ordering – A management agent should be able to order the startup and

shutdown sequences of bundles.• Levels – The management agent should support a virtually unlimited

number of levels.• Backward compatible – The model for start levels should be compatible

with the OSGi Service Platform Release 2 specifications.

8.1.2 Entities• Start Level Service – The service that is used by a Management Agent to

order the startup and shutdown sequences of bundles.• Management Agent – See page 32.• Framework Event – See page 93.• Framework Listener – See page 93.

OSGi Service Platform Release 4 195-268

Page 204: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Start Level Service Specification Version 1.0

Figure 36 Class Diagram org.osgi.service.startlevel package

8.2 Start Level ServiceThe Start Level Service provides the following functions:

• Controls the beginning start level of the OSGi Framework. • Is used to modify the active start level of the Framework.• Can be used to assign a specific start level to a bundle.• Can set the initial start level for newly installed bundles.

Defining the order in which bundles are started and stopped is useful for the following:

• Safe mode – The Management Agent can implement a safe mode. In this mode, only fully trusted bundles are started. Safe mode might be nec-essary when a bundle causes a failure at startup that disrupts normal operation and prevents correction of the problem.

• Splash screen – If the total startup time is long, it might be desirable to show a splash screen during initialization. This improves the user’s per-ception of the boot time of the device. The startup ordering can ensure that the right bundle is started first.

• Handling erratic bundles – Problems can occur because bundles require services to be available when they are activated (this is a programming error). By controlling the start order, the Management Agent can prevent these problems.

• High priority bundles – Certain tasks such as metering need to run as quickly as possible and cannot have a long startup delay. These bundles can be started first.

a managementbundle impl.

an event listener impl.

<<interface>>FrameworkListener

<<interface>>StartLevel

0..*

0..*

FrameworkImplementation

a Framework impl.

<<class>>FrameworkEvent

gets

is notified by

start levelchanged

1

0..*

196-268 OSGi Service Platform Release 4

Page 205: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Specification Version 1.0 Start Level Service

8.2.1 The Concept of a Start LevelA start level is defined as a non-negative integer. A start level of 0 (zero) is the state in which the Framework has either not been launched or has com-pleted shutdown (these two states are considered equivalent). In this state, no bundles are running. Progressively higher integral values represent pro-gressively higher start levels. For example, 2 is a higher start level than 1. The Framework must support all positive int values (Integer .MAX_VALUE) for start levels.

The Framework has an active start level that is used to decide which bundles can be started. All bundles must be assigned a bundle start level. This is the minimum start level to start a bundle. The bundle start level can be set with the setBundleStartLevel(Bundle, int) method. When a bundle is installed, it is initially assigned the bundle start level returned by get Init ia lBundle-StartLevel() . The initial bundle start level to be used when bundles are installed can be set with set Init ia lBundleStartLevel( int) .

In addition, a bundle can be persistently marked as started or stopped with the Bundle sta rt and stop methods. A bundle cannot run unless it is marked started, regardless of the bundle’s start level.

8.2.2 Changing the Active Start LevelA Management Agent can influence the active start level with the set-StartLevel( int) method. The Framework must then increase or decrease the active start level by 1 until the requested start level is reached. The process of starting or stopping bundles, which is initiated by the setStartLevel( int) method, must take place asynchronously.

This means that the active start level (the one that is active at a certain moment in time) must be changed to a new start level, called the requested start level. The active and requested levels differ during a certain period when the Framework starts and stops the appropriate bundles. Moving from the active start level to the requested start level must take place in increments of one (1).

If the requested start level is higher than the active start level, the Frame-work must increase the start level by one and then start all bundles that meet the following criteria:

• Bundles that are persistently marked started, and• Bundles that have a bundle start level equal to the new active start level.

The Framework continues increasing the active start level and starting the appropriate bundles until it has started all bundles with a bundle start level that equals the requested start level.

The Framework must not increase to the next active start level until all started bundles have returned from their BundleAct ivator .start method normally or with an exception. A FrameworkEvent.ERROR must be broad-cast when the BundleAct ivator .start method throws an exception.

If the requested start level is lower than the active start level, the Framework must stop all bundles that have a bundle start level that is equal to the active start level. The Framework must then decrease the active start level by 1. If the active start level is still higher than the requested start level, it should

OSGi Service Platform Release 4 197-268

Page 206: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Start Level Service Specification Version 1.0

continue stopping the appropriate bundles and decreasing the active start level until the requested start level is reached. A FrameworkEvent.ERROR must be broadcast when the BundleActivator .stop method throws an excep-tion.

If the requested start level is the active start level, the Framework will not start or stop any bundles.

When the requested start level is reached and all bundles satisfy the condi-tion that their bundle start level <= active start level in order to be started, then the FrameworkEvent .STARTLEVEL_CHANGED event must be sent to all registered FrameworkListener objects. If the requested start level and active start level are equal, then this event may arrive before the setStartLevel method has returned.

It must therefore always be true that:

• A bundle is started, or will be started soon, if the start level is less or equal to the active start level.

• A bundle is stopped, or will be stopped soon, when it has a start level more than the active start level.

These steps are depicted in the flow chart in Figure 37.

Figure 37 Move to requested start level R, active level is A, B is a bundle’s start level

If the Framework is currently involved in changing the active start level, it must first reach the previously requested start level before it is allowed to continue with a newly requested start level. For example, assume the active start level is 5 and the Framework is requested to transition to start level 3. Before start level 3 is reached, another request is made to transition to start level 7. In this case, the OSGi Framework must first complete the transition to start level 3 before it transitions to start level 7.

move to R

A<R

Start All

A = A+1

A==R

bundles whereB = A A = A-1

A>R

Stop Allbundles where

B = A

A==R

A==RA==RA<R A>R

publish event

198-268 OSGi Service Platform Release 4

Page 207: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Specification Version 1.0 Start Level Service

8.2.3 Startup SequenceAt startup, the Framework must have an active start level of zero. It must then move the active start level to the beginning start level. The beginning start level is specified with an argument when starting the Framework or through some other means, which is left undefined here. If no beginning start level is given, the Framework must assume a beginning start level of one (1).

The Framework must launch and then set the requested start level to the beginning start level. It must then follow the procedure described in Chang-ing the Active Start Level on page 197 to make the active start level equal the beginning start level, with the exception of the FrameworkEvent .START_LEVEL_CHANGED event broadcast. During launching, the Framework must broadcast a FrameworkEvent.STARTED event when the initial start level is reached.

8.2.4 Shutdown SequenceWhen the Framework shuts down, the requested start level must be set to zero. The Framework must then follow the process described in Changing the Active Start Level on page 197 to make the active start level equal to zero.

8.2.5 Changing a Bundle’s Start LevelBundles are assigned an initial start level when they are installed. The default value for the initial start level is set to one, but can be changed with the set Init ia lBundleStartLevel( in t) method. A bundle’s start level will not change when the set Init ia lBundleStartLevel( int) method later modifies the default initial start level.

Once installed, the start level of a bundle can be changed with setBundle-StartLevel(Bundle , int) . When a bundle’s start level is changed and the bun-dle is marked persistently to be started, then the OSGi Framework must compare the new bundle start level to the active start level. For example, assume that the active start level is 5 and a bundle with start level 5 is started. If the bundle’s start level subsequently is changed to 6 then this bun-dle must be stopped by the OSGi Framework but it must still be marked per-sistently to be started.

8.2.6 Starting a BundleIf a bundle is started by calling the Bundle .startmethod, then the OSGi Framework must mark the bundle as persistently started. The OSGi Frame-work must not actually start a bundle when the active start level is less than the bundle’s start level. In that case, the state must not change.

8.2.7 Exceptions in the Bundle ActivatorIf the BundleAct ivator.start or stop method throws an Except ion , then the handling of this Exception is different depending who invoked the start or stop method.

OSGi Service Platform Release 4 199-268

Page 208: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Compatibility Mode Start Level Service Specification Version 1.0

If the bundle is started/stopped due to a change in the active start level or the bundle’s start level, then the Exception must be wrapped in a BundleExcept ion and broadcast as a FrameworkEvent.ERROR event. Other-wise, a new BundleException must be created containing the exception and this BundleException is then thrown to the caller.

8.2.8 System BundleThe System Bundle is defined to have a start level of zero. The start level of the System Bundle cannot be changed. An I l legalArgumentException must be thrown if an attempt is made to change the start level of the System Bun-dle.

8.3 Compatibility ModeCompatibility mode consists of a single start level for all bundles. All bun-dles are assigned a bundle start level of 1. In compatibility mode, the OSGi Framework is started and launched with an argument specifying a begin-ning start level of 1. The Framework then starts all bundles that are persis-tently marked to be started. When start level 1 is reached, all bundles have been started and the FrameworkEvent.STARTED event is published. This is considered compatible with prior OSGi Framework versions because all bundles are started and there is no control over the start order. Framework implementations must support compatibility mode.

8.4 Example ApplicationsThe Start Level service allows a Management Agent to implement many dif-ferent startup schemes. The following sections show some examples.

8.4.1 Safe Mode Startup SchemeA Management Agent can implement a safe mode in which it runs trusted bundles at level 1 and runs itself on level 2. When the Management Agent gets control, it constructs a list of all applications to be started. This list can be constructed from BundleContext .getBundles() . The Management Agent checks each bundle to determine if it is not started but is marked to be started persistently by calling the i sBundlePersistentlyStarted(Bundle) method of the Start Level service.

Before it starts each bundle, the Management Agent persistently records the bundle to be started and then starts the bundle. This continues until all bun-dles are started. When all bundles are successfully started, the Management Agent persistently records that all bundles started without problems.

If the Service Platform is restarted, the Management Agent should inspect the persistently recorded information. If the persistently recorded informa-tion indicates a bundle failure, the Management Agent should try to restart the system without that application bundle since that bundle failed. Alter-natively, it could contact its Remote Manager and ask for assistance.

200-268 OSGi Service Platform Release 4

Page 209: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Specification Version 1.0 Security

8.4.2 Splash Screen Startup SchemeA splash screen is a popup containing startup information about an applica-tion. The popup provides feedback to the end user indicating that the sys-tem is still initializing. The Start Level service can be used by a bundle to pop-up a splash screen before any other bundle is started, and remove it once all bundles have been started. The splash-screen bundle would start at start level 1 and all other bundles would start at start level 2 or higher.

class SplashScreen implements BundleActivator, FrameworkListener {Screen screen;public void start(BundleContext context) {

context.addFrameworkListener( this );screen = createSplash();screen.open();

}public void stop(BundleContext context) {

screen.close();}public void frameworkEvent( FrameworkEvent event ) {

if ( event.getType() == FrameworkEvent.STARTED )screen.close();

}Screen createSplash() { ... }

}

8.5 SecurityWhen the Start Level service is available, it is crucial to protect its usage from non-trusted bundles. A malicious bundle that can control start levels can control the whole service platform.

The Start Level service is for use by a Management Agent. This means that bundles that use this service must have AdminPermiss ion[bundle ,EXECUTE] to be able to modify a bundle’s start level or AdminPermiss ion[System Bundle,STARTLEVEL] to modify the Framework’s active start level. Bundles that need only read access to this service should have ServicePermission[StartLevel , GET] .

The Start Level service must be registered by the Framework so there is no reason for any bundle to have ServicePermiss ion[StartLevel , REGISTER] .

8.6 org.osgi.service.startlevelThe OSGi StartLevel service Package. Specification Version 1.0.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle’s manifest. For example:

Import-Package: org.osgi.service.startlevel; version=1.0StartLevel

OSGi Service Platform Release 4 201-268

Page 210: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.startlevel Start Level Service Specification Version 1.0

8.6.1 public interface StartLevelThe StartLevel service allows management agents to manage a start level assigned to each bundle and the active start level of the Framework. There is at most one StartLevel service present in the OSGi environment.

A start level is defined to be a state of execution in which the Framework exists. StartLevel values are defined as unsigned integers with 0 (zero) being the state where the Framework is not launched. Progressively higher inte-gral values represent progressively higher start levels. e.g. 2 is a higher start level than 1.

Access to the StartLevel service is protected by corresponding ServicePer-mission. In addition AdminPermission is required to actually modify start level information.

Start Level support in the Framework includes the ability to control the beginning start level of the Framework, to modify the active start level of the Framework and to assign a specific start level to a bundle. How the beginning start level of a Framework is specified is implementation depen-dent. It may be a command line argument when invoking the Framework implementation.

When the Framework is first started it must be at start level zero. In this state, no bundles are running. This is the initial state of the Framework before it is launched. When the Framework is launched, the Framework will enter start level one and all bundles which are assigned to start level one and are persistently marked to be started are started as described in the Bundle.start method. Within a start level, bundles are started in ascending order by Bundle.getBundleId. The Framework will continue to increase the start level, starting bundles at each start level, until the Framework has reached a beginning start level. At this point the Framework has completed starting bundles and will then fire a Framework event of type Frame-workEvent.STARTED to announce it has completed its launch.

The StartLevel service can be used by management bundles to alter the active start level of the framework.getBundleStartLevel(Bundle)

8.6.1.1 public int getBundleStartLevel( Bundle bundle )

bundle The target bundle.

Return the assigned start level value for the specified Bundle.

Returns The start level value of the specified Bundle.

Throws IllegalArgumentException – If the specified bundle has been uninstalled. getInitialBundleStartLevel()

8.6.1.2 public int getInitialBundleStartLevel( )

Return the initial start level value that is assigned to a Bundle when it is first installed.

Returns The initial start level value for Bundles.

See Also setInitialBundleStartLevel[p.203]getStartLevel()

202-268 OSGi Service Platform Release 4

Page 211: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Specification Version 1.0 org.osgi.service.startlevel

8.6.1.3 public int getStartLevel( )

Return the active start level value of the Framework. If the Framework is in the process of changing the start level this method must return the active start level if this differs from the requested start level.

Returns The active start level value of the Framework.isBundlePersistentlyStarted(Bundle)

8.6.1.4 public boolean isBundlePersistentlyStarted( Bundle bundle )

bundle The bundle for which to return the persistently started state.

Return the persistent state of the specified bundle.

This method returns the persistent state of a bundle. The persistent state of a bundle indicates whether a bundle is persistently marked to be started when it’s start level is reached.

Returns true if the bundle is persistently marked to be started, false if the bundle is not persistently marked to be started.

Throws IllegalArgumentException – If the specified bundle has been uninstalled. setBundleStartLevel(Bundle,int)

8.6.1.5 public void setBundleStartLevel( Bundle bundle, int startlevel )

bundle The target bundle.

startlevel The new start level for the specified Bundle.

Assign a start level value to the specified Bundle.

The specified bundle will be assigned the specified start level. The start level value assigned to the bundle will be persistently recorded by the Frame-work. If the new start level for the bundle is lower than or equal to the active start level of the Framework, the Framework will start the specified bundle as described in the Bundle.start method if the bundle is persistently marked to be started. The actual starting of this bundle must occur asynchronously. If the new start level for the bundle is higher than the active start level of the Framework, the Framework will stop the specified bundle as described in the Bundle.stop method except that the persistently recorded state for the bundle indicates that the bundle must be restarted in the future. The actual stopping of this bundle must occur asynchronously.

Throws IllegalArgumentException – If the specified bundle has been uninstalled or if the specified start level is less than or equal to zero, or the specified bun-dle is the system bundle.

SecurityException – If the caller does not have AdminPermission[bundle,EXECUTE] and the Java runtime environment supports permissions. setInitialBundleStartLevel(int)

8.6.1.6 public void setInitialBundleStartLevel( int startlevel )

startlevel The initial start level for newly installed bundles.

Set the initial start level value that is assigned to a Bundle when it is first installed.

The initial bundle start level will be set to the specified start level. The ini-tial bundle start level value will be persistently recorded by the Framework.

When a Bundle is installed via BundleContext.installBundle, it is assigned the initial bundle start level value.

OSGi Service Platform Release 4 203-268

Page 212: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.startlevel Start Level Service Specification Version 1.0

The default initial bundle start level value is 1 unless this method has been called to assign a different initial bundle start level value.

Thie method does not change the start level values of installed bundles.

Throws IllegalArgumentException – If the specified start level is less than or equal to zero.

SecurityException – If the caller does not have AdminPermission[System Bundle,STARTLEVEL] and the Java runtime environment supports permis-sions. setStartLevel(int)

8.6.1.7 public void setStartLevel( int startlevel )

startlevel The requested start level for the Framework.

Modify the active start level of the Framework.

The Framework will move to the requested start level. This method will return immediately to the caller and the start level change will occur asyn-chronously on another thread.

If the specified start level is higher than the active start level, the Frame-work will continue to increase the start level until the Framework has reached the specified start level, starting bundles at each start level which are persistently marked to be started as described in the Bundle.start method. At each intermediate start level value on the way to and including the target start level, the framework must:

1 Change the active start level to the intermediate start level value. 2 Start bundles at the intermediate start level in ascending order by

Bundle.getBundleId.

FrameworkEvent.STARTLEVEL_CHANGED to announce it has moved to the specified start level.

If the specified start level is lower than the active start level, the Framework will continue to decrease the start level until the Framework has reached the specified start level stopping bundles at each start level as described in the Bundle.stop method except that their persistently recorded state indi-cates that they must be restarted in the future. At each intermediate start level value on the way to and including the specified start level, the frame-work must:

1 Stop bundles at the intermediate start level in descending order by Bundle.getBundleId.

2 Change the active start level to the intermediate start level value.

FrameworkEvent.STARTLEVEL_CHANGED to announce it has moved to the specified start level.

If the specified start level is equal to the active start level, then no bundles are started or stopped, however, the Framework must fire a Framework event of type FrameworkEvent.STARTLEVEL_CHANGED to announce it has finished moving to the specified start level. This event may arrive before the this method return.

Throws IllegalArgumentException – If the specified start level is less than or equal to zero.

204-268 OSGi Service Platform Release 4

Page 213: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Start Level Service Specification Version 1.0 org.osgi.service.startlevel

SecurityException – If the caller does not have AdminPermission[System Bundle,STARTLEVEL] and the Java runtime environment supports permis-sions.

OSGi Service Platform Release 4 205-268

Page 214: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.startlevel Start Level Service Specification Version 1.0

206-268 OSGi Service Platform Release 4

Page 215: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Introduction

9 Conditional Permission Admin SpecificationVersion 1.0

9.1 IntroductionThe OSGi security model is based on the powerful and flexible Java 2 secu-rity architecture, specifically the permission model. This specification adds the several new features to the Java 2 model to adapt it to the typical use cases of OSGi deployments.

In contrast with other Java execution models, the OSGi Framework specifi-cation provides a well-defined API to manage permissions. Other execution models tend to leave the permission management up to implementations.

A key aspect of this security management API is the real time management of the permissions. This enables management applications to control the permissions of other applications with immediate effect; no restart is required.

Permission Management is based on the very general mode of conditional permissions. Conditional permissions match permissions to bundles using OSGi Alliance or user-defined conditions. The advantage of this model is that groups of permissions can be shared based on signers and locations. Conditions can also be used to enable a group of permissions when an exter-nal condition is true, for example, an inserted SIM card, an online connec-tion to the management system is established, or a user has approved a permission after prompting. This model allows an operator to create and enforce a dynamic security policy for its devices.

This specification defines a Conditional Permission Admin that supersedes the Permission Admin (albeit its relation to Permission Admin is well-defined in this specification). It provides a security model based on condi-tional permissions where the conditions define the selection of the bundles that these permissions apply to.

9.1.1 Essentials• Policies – Provide a security policy system where external conditions

control the actual permissions that bundles have at a certain moment in time.

• Java 2 Security – Provide full compatibility with the existing Java 2 security model, existing applications must not require modifications.

• Delegation – Support a management delegation model where an Operator can delegate securely part of the management of a device to another party.

OSGi Service Platform Release 4 207-268

Page 216: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction Conditional Permission Admin Specification Version 1.0

• Digital Signatures – Support the use of digital signatures in a bundle’s policy decisions.

• Real Time – Changes in the environment must be reflected immediately in the bundle’s permissions.

• Operator Specific Conditions – It must be possible for operators, manufac-turers, selected developers, and others to provide custom conditions.

• User Confirmation – The policy model must support end user prompting and confirmations.

• Backward Compatibility – The model must be backward compatible with the Permission Admin of earlier releases.

9.1.2 Entities• Conditional Permission Admin – The administrative service that provides

the functions to manipulate the permission table.• Permission Table – A conceptual table containing all the Conditional Per-

mission Info tuples.• Conditional Permission Info – A tuple of a set of Condit ionInfo objects and a

set of PermissionInfo objects.• Permission Info – Holds a string based encoding of a Permission object.• Condition Info – Holds a string based encoding of a Condit ion object.• Condition – Condit ion objects is associated with a Bundle Protection

Domain and abstract an external condition that can be evaluated at any time.

• Bundle Location Condition – An immutable Condit ion object that is sat-isfied when the associated bundle has the given location.

• Bundle Signer Condition – An immutable Condit ion object that is satisfied when the associated bundle is signed by a certificate that matched the given DN.

• Permission – An object that defines a certain permission type.• Bundle Protection Domain – The class that implements the Protection

Domain of a bundle, this specification does not define an interface for this class, but it plays an important role in this specification.

208-268 OSGi Service Platform Release 4

Page 217: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Introduction

Figure 38 org.osgi.service.condpermadmin package

9.1.3 SynopsisA Conditional Permission Admin service maintains a system wide table of Condit ionalPermissionInfo objects, which are an encoded form of condi-tions and permissions. A manager can enumerate, delete, and add new tuples to this table.

When a bundle is created, it creates a single Bundle Protection Domain. This protection domain calculates the system permissions for that bundle by instantiating the conditions and permissions defined in the permission table, potentially pruning any entries that can never apply to that bundle and optimizing entries that always apply.

A bundle can have local permissions defined in a Bundle Permission Resource. These are the actual permissions needed by this bundle to operate. A bundle’s effective permissions are the intersection of the local permis-sions and the system permissions. During the permission check of the Java Security Manager, each Protection Domain is first checked for the local per-missions, if this fails, the check fails.

Otherwise, the Bundle Protection Domains of the calling bundles are con-sulted to see if they imply the requested permission. To imply the requested permission, the Bundle Protection Domain must find a tuple in its permis-sion table where all conditions are satisfied and where the tuple’s permis-sions imply the requested permission. However, certain conditions must

<<interface>>Conditional Perm. Admin

selects by

<<interface>>Condition Info

<<interface>>Conditional Perm. Info

<<interface>>Condition

<<interface>>Permission Info

Conditional Permission Admin Impl.

Permission

Manager Impl.

BundleProtection Domain

<<class>>Bundle Loc. Condition

Protection Domain

a Bundle

<<class>>Bundle Signer. Condition

locationselects bysigner

*

1

1 *

*

*

User Condition Impl

administers

has

searches

has

encodes

encodes

OSGi Service Platform Release 4 209-268

Page 218: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Management Model Conditional Permission Admin Specification Version 1.0

postpone their evaluation so that their evaluation can be grouped. For example, a user prompt must be postponed to remove any redundant ques-tions to the end user. Such conditions are only postponed when their related permissions imply the requested permission and the request cannot be satis-fied immediately.

At the end of the permission check, the postponed conditions are evaluated grouped by their class.

9.1.4 What to Read9.1.4.1 Architects

• Permission Management Model on page 210• Conditional Permissions on page 217• Conditions on page 230• Digitally Signed JAR Files on page 14

9.1.4.2 Application Programmers• Digitally Signed JAR Files on page 14

9.1.4.3 Management Programmers• Permission Management Model on page 210• Conditional Permissions on page 217• Conditions on page 230• Conditional Permissions on page 217• Permission Management on page 228• Digitally Signed JAR Files on page 14• Standard Conditions on page 234

9.2 Permission Management ModelThe Conditional Permission Admin provides an extremely flexible security model for bundles. However, the price of this flexibility is additional com-plexity. In this case, the amount of configuration necessary to setup a work-ing system can easily overwhelm anybody. It is therefore necessary to be very careful implementing a deployment security model. This section defines a series of possible deployment security models while simulta-neously defining the terminology that is used in later sections that explain the available mechanisms in detail.

9.2.1 Local PermissionsA good working principle is to minimize permissions as much as possible, as early as possible. This principle is embodied with the local permissions of a bundle. Local permissions are defined by a Bundle Permission Resource that is embodied in the bundle; it defines a set of permissions. These permissions must be enforced by the Framework for the given bundle. That is, a bundle can get less permissions than the local permissions but it can never get more permissions. If no such resource is present then the local permissions must be All Permission. The Bundle Permission Resource is defined in Bundle Per-mission Resource on page 235.

210-268 OSGi Service Platform Release 4

Page 219: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Permission Management Model

For example, if the local permissions do not imply ServicePermission[org.osg i.service . log.LogServ ice ,GET] , then the bundle can never get the LogService object, regardless of any other security setup in the device.

The fine-grained permissions allowed by the OSGi Service Platform are very effective with the local permissions because they can be defined by the developer instead of the deployer. The developer knows exactly what ser-vices are needed, what packages the bundle requires, and what network hosts are accessed. Tools can be used that analyze bundles and provide the appropriate local permissions to simplify the task of the developer. How-ever, without detailed knowledge of the bundle’s intrinsics, it is very diffi-cult to create the local permissions due to their fine-grained granularity.

At first sight, it can seem odd that a bundle carries its own permissions. However, the local permissions define the maximum permissions that the bundle needs, providing more permissions to the bundle is irrelevant because the Framework must not allow the bundle to use them. The pur-pose of the local permissions is therefore auditing by the deployer. Analyz-ing a bundle’s byte codes for its security requirements is cumbersome, if not impossible. Auditing a bundle’s permission resource is (relatively) straight-forward. For example, if the local permissions request permission to access the Internet, it is clear that the bundle has the potential to access the net-work. By inspecting the local permissions, the Operator can quickly see the security scope of the bundle. It can trust this audit because it must be enforced by the Framework when the bundle is executed.

An Operator that runs a fully closed system can use the local permissions to run third party applications that are not trusted to run unchecked, thereby mitigating risks. The Framework guarantees that a bundle is never granted a permission that is not implied by its local permissions. A simple audit of the application’s local permissions will reveal any potential threats.

This scenario is depicted in Figure 39. A developer creates a bundle with local permissions, the operator verifies the local permissions, and if it matches the expectations, it is deployed to the device where the Framework verifies that the local permissions are never exceeded.

Figure 39 Local permissions and Deployment

installsauditsdevelops

Fram

ewor

k

local permissionsbundle, unsigned

code, classes

deve

lope

r

oper

ator

and ships

security scope

OSGi Service Platform Release 4 211-268

Page 220: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Management Model Conditional Permission Admin Specification Version 1.0

Summarizing, the benefits of local permissions are:

• Fine-grained – The developer has the knowledge to provide the fine-grained permissions that are necessary to minimize the sandbox of the bundle without constraining it.

• Auditable – The Operator has a relatively small and readable file that shows the required sandbox. It can therefore asses the risk of running a bundle.

• Sandboxed – The Operator has the guarantee from the Framework that a bundle cannot escape its local permissions.

9.2.2 Open Deployment ChannelsFrom a business perspective it is sometimes too restrictive to maintain a fully closed system. There are many use cases where users should be able to deploy bundles from a CD, via a PC, or from an Internet web sites. In those scenarios, relying on the local permissions is not sufficient because the Framework cannot verify that the local permissions have not been tam-pered with.

The de facto solution to tampering is to digitally sign the bundles. The rules for OSGi signing are defined in Digitally Signed JAR Files on page 14. A digital signing algorithm detects modifications of the JAR as well as authenticating the signer. A Framework therefore must refuse to run a bundle when a sig-nature does not match the contents or it does not recognize the signer. Sign-ing therefore makes it possible to use an untrusted deployment channel and still rely on the enforcement of the local permissions.

For example, an Operator can provision its applications via the Internet. When such an application is downloaded from an untrusted site, the Frame-work verifies the signature. It should install the application only when the signature is trusted or when it has default permissions for untrusted bun-dles.

Figure 40 Local Scope and Deployment with signing

local permissionsinstallsaudits and

signsdevelops

local permissionsbundle, unsigned

code, classes

bundle, signed

deve

lope

r

oper

ator

end

user

OSGi Service Platform

and ships

212-268 OSGi Service Platform Release 4

Page 221: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Permission Management Model

9.2.3 DelegationA model where the local permissions are secured with a signature works for an Operator that fully controls a device. The operator must sign all bundles before they are provisioned. In this case, the Operator acts as a gatekeeper, no authority is delegated.

This can become expensive when there are third parties involved. For exam-ple, an Enterprise could provide applications to its employees on a mobile phone that is managed by an Operator. This model is depicted in Figure 41. If the Enterprise always has to contact the Operator before it can provision a new version, bottlenecks quickly arise.

Figure 41 Delegation model

This bottleneck problem can also be solved with signing. Signing does not only provide tamper detection, it also provides an authenticated principal. The principal is authenticated with a certificate chain. The device contains a set of trusted certificates (depending on implementation) that are used to authenticate the certificate of the signer.

The operator can therefore safely associate a principal with a set of permis-sions. These permissions are called the system permissions. Bundles signed by that principal are then automatically granted those system permissions.

In this model, the Operator is still fully in control. At any moment in time, the Operator can change the system permissions associated with the princi-pal and thereby immediately deny access to all bundles of that principal, while they are running. Alternatively, the Operator can add additional sys-tem permissions to the principal if a new service has become available to the signer’s applications. For example, if the Operator installs a org .tourist .PointOf Interest service, it can grant the ServicePermission[org. tour ist .PointOf Interest,GET] and PackagePermission[org. tour ist , IMPORT] to all principals that are allowed to use this service. The Operator can inform the involved parties after the fact, if at all. This model therefore does not create a bottleneck.

Using digital signing to assign system permissions can therefore delegate the responsibility of provisioning to other parties. The Operator completely defines the limits of the permissions of the principal, but the signing and deployment can be done by the other parties.

Developer

Operator

Enterprise

OSGi Service PlatformEmployee

grantsuses

provides

installs

permissions

provides signingcertificate

OSGi Service Platform Release 4 213-268

Page 222: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Management Model Conditional Permission Admin Specification Version 1.0

For example, an Operator can define that the ACME company can provision bundles without any intervention of the Operator. The Operator has to pro-vide ACME once with a signing certificate and the Operator must associate the ACME principal with the appropriate system permissions on the device.

The key advantage of this model is the reduced communication between ACME and the Operator: The Operator can modify the system permissions of ACME applications and be in control at any moment in time. The ACME company can develop new applications without the need to coordinate these efforts in any way. This model is depicted in Figure 42, which also shows the possible sandboxes for Daffy Inc. and unsigned bundles.

Figure 42 Typical Delegation model

The local permissions can still play an important role in the delegation model because it provides the signer the possibility to mitigate its risk, just as it did for the Operator. Signers can verify the local permissions before they sign a bundle. Like the Operator in the earlier scenario, the signer can quickly verify the security requirements of a bundle. For example, if a game bundle requests AdminPermission[*,*] , it is likely that the bundle will not pass the security audit of the signer. However, in the unlikely case it did, it will not be granted this permission unless the Operator gave such a permis-sion to the signer’s principal on the device.

9.2.4 GroupingThe grouping model is traditionally used because it minimizes the adminis-tration of the security setup. For example, an operator can define the follow-ing security levels:

• Untrusted – Applications that are not trusted. These applications must run in a very limited security scope. They could be unsigned.

• Trusted – Applications that are trusted but that are not allowed to manage the device or provide system services.

• System – Applications that provide system services.• Manage – Applications that manage the device.

The operator signs the bundle with an appropriate certificate before it is deployed, when the bundle is installed, it will be automatically be assigned to the appropriate security scope.

However, the behavior can also be obtained using the local permissions of a bundle.

unsigned

signed by

signed by Operator

ACME

signed by Daffy

send certificate

send certificate

set systempermissions

Daffy Inc.

ACMEsign & deploy

sign & deploy

sandboxes

214-268 OSGi Service Platform Release 4

Page 223: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Permission Management Model

9.2.5 Typical ExampleThis example provides a simple setup for a delegation model. The example is intended for readability, certain concepts will be explained later. Also for readability, package prefixes that can be guessed are replaced with . . . .

Basic permissions define the permissions that are available to all bundles. The basic permissions therefore have no conditions associated with them so all bundles will be able to use these permissions:

{ (..ServicePermission "..LogService" "get" )(..PackagePermission "..log "import" )(..PackagePermission "..framework" "import" )

}

The next permission tuple has a condition that limits the permissions to bundles that are signed by ACME. ACME signed bundles are given the per-mission to manage other ACME bundles. Conditions are encapsulated in square brackets (’ [ ] ’).

{ [ ..BundleSignerCondition "* ; o=ACME" ]

( ..AdminPermission "(signer=\* ; o=ACME)" "*" )( ..ServicePermission "..ManagedService" "register" )( ..ServicePermission "..ManagedServiceFactory"

"register" )( ..PackagePermission "..cm" "import" )

}

The last permission tuple is for bundles signed by the operator. The operator bundles get full managing capabilities as well as permissions to provide sys-tem services.

{[ ..BundleSignerCondition "*; o=Operator" ]( ..AdminPermission "*" "*" )( ..ServicePermission "*" "get,register" )( ..PackagePermission "*" "import,export" )

}

The resulting permissions are summarized in Table 11 on page 215.

Table 11 Assigned Permission, implied by another permission, x=direct, i=implied by another permission

Signed by:

Uns

igne

d

ACM

E

Ope

rato

r

Service Permission . .LogService GET x x x/i

. .ManagedService* REGISTER x i

GET i

* * x

PackagePermission . . log IMPORT x x x/i

. .cm IMPORT x i

OSGi Service Platform Release 4 215-268

Page 224: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Effective Permissions Conditional Permission Admin Specification Version 1.0

9.3 Effective PermissionsOnce a bundle is installed, it has Java 2 permissions associated with it. This set is called the effective permissions. The effective permissions are consulted when the checkPermission method of the Security Manager is called.

The Permission Admin service and the Conditional Permission Admin ser-vice can be used by a managing application to define the system permissions. Additionally, a bundle can carry its own permissions; these are called the local permissions. All these permission sets interact in a non-trivial way to give the effective permissions.

The purpose of the local permissions is to mitigate the bundle signer’s risk. The Framework guarantees that a bundle’s effective permissions are always smaller or equal than the local permissions because the effective permis-sions are the intersection of the local permissions with the system permis-sions.

The system permissions have two possible sources. The system permissions can be bound via the Permission Admin service to a locat ion . This mecha-nism is provided for backward compatibility only. New management appli-cations should use the Conditional Permission Admin service if possible.

If the Permission Admin locat ion is not bound, all the conditional permissions from Conditional Permission Admin act as the system permissions. The relationship between the system permissions and local permissions is depicted in Figure 43.

Figure 43 System, Local and Security permissions

. . f ramework IMPORT x x x/i

* * x

AdminPermission (signer=\*;o=ACME) * x i

* * x

Table 11 Assigned Permission, implied by another permission, x=direct, i=implied by another permission

Signed by:

Uns

igne

d

ACM

E

Ope

rato

rEffective Local System∩=

system permissions

local permissions

effective

location

Bundle PermissionResource

permissions Condition[]

Permission Admin

Conditional Permission Admin

or otherwise

216-268 OSGi Service Platform Release 4

Page 225: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Conditional Permissions

9.4 Conditional PermissionsThe conditional permissions provide a very general model that is related to, but different from the Java 2 Policy model. The Java 2 Policy model assigns a set of permissions to a code base or signer.

The Conditional Permission Admin service model assumes a more general approach. It conceptually has a system wide permission table. Each entry in this table is applicable for any bundle if it fulfills the right conditions.

The tuples of this table consist of:

• A set of conditions• A set of permissions

The permissions of a tuple are only applicable when all conditions in the set of conditions are satisfied at the time of the permission check. Certain con-dition types are provided by this specification, other conditions can be pro-vided by user code. For example, the Bundle Signer Condition is satisfied when the associated bundle is signed by a specific principal. If the bundle is not signed by that principal, the tuple’s permissions must not apply during the check.

An instantiated condition is represented by the Condit ion interface; it repre-sents an expression that can be evaluated to t rue or fa lse during permission checking. The condition set must be treated as an AND operation. Only if all conditions are satisfied, then the tuple is said to match and its permissions apply. That is, a permission P is implied by a tuple (condit ions , permissions) when

• All of its condit ions are satisfied • At least one of its permissions implies P , as defined by Java 2 security.

An additional feature of the Condition objects is that they can postpone their evaluation until the end of a permission check. Postponing allows a Condi-tion type to group the evaluation of the same conditions. This is, for exam-ple, important for prompting a user. An immediate condition is evaluated directly. This is further discussed in Condition Life Cycle on page 234.

For example, assume the following setup for bundle A :

{ [ ...BundleSignerCondition "cn=*, o=ACME, c=US" ] [ com.acme.Online ] (...AdminPermission "*", "lifecycle") }

The curly brackets {} delimit a single tuple. Conditions are delimited by square brackets [] and the permissions are delimited by parentheses () . As usual, package prefixes are left out for brevity. This syntax is used in the remainder of the document.

The example shows that both the condition org.osgi.service.condpermadmin.BundleSignerCondition must be sat-isfied as well as the com.acme.Onl ine condition, before Admin Permission is granted to perform a life cycle operation on any bundle.

OSGi Service Platform Release 4 217-268

Page 226: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permissions Conditional Permission Admin Specification Version 1.0

Binding conditional permissions to bundles is very common, though not obligatory. Therefore, a number of Condit ion classes are provided to define the system permissions of a bundle. This association can depend on a bun-dle’s:

• Signer – Implemented with the BundleS ignerCondit ion class.• Location – Implemented with the BundleLocat ionCondit ion class

The system permissions of a bundle are dynamic and volatile, the answer to an impl ies method call depends therefore on the conditions that are satis-fied when a permission is checked. In principle, any of the tuples in the sys-tem wide permission table can match.

9.4.1 Encoding versus InstantiationThe system wide permission table is maintained with the addCondit ionalP-ermiss ion Info(Condit ionInfo[] ,PermissionInfo[]) or setCondit ionalPer-missionIn fo(Str ing,Condit ionInfo[] ,Permission Info[])method. These methods use an encoded form of the conditions and the permissions. This encoded form is stored in the permission table. The permission table acts as a dynamic template for the Bundle Protection Domain, the Bundle Protection Domain creates instances with the associated bundle as their context. It is dynamic because a Bundle Protection Domain must track the changes to the permission table immediately and update any instances from the new encoded forms. Once the addCondit ionalPermiss ionInfo(Condit ionInfo[] ,PermissionIn fo[]) or setCondit ionalPermiss ionInfo(Str ing,Condit ion-Info[] ,PermissionInfo[]) method has returned, all subsequent use of Bundle Protection Domains must be based on the new constellation.

Figure 44 Instantiation of the permission table

The arguments to the addCondit ionalPermission Info method are Condi-t ionInfo and Permiss ionInfo (from the org.osg i .service.permiss ionadmin package) objects. The purpose of these objects is to encode the Condit ion and Permission objects without instantiating them. The return value of the addCondit ionalPermiss ion method is also an object that encodes the condi-tions and permissions: a Condit ionalPermiss ion Info object.

The conditions and permissions of the permission table must be instanti-ated before the conditions can be checked. This instantiation can happen, when a Bundle Protection Domain is created or the first time when the con-ditional permissions are needed because of a permission check.

PermissionInfo[]ConditionInfo[]

ConditionalPermissionInfo[]

BundleProtectionDomain

BundleProtectionDomain

instantiate

instantiate

System widepermission table

Name

218-268 OSGi Service Platform Release 4

Page 227: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 The Permission Check

Therefore, Condit ion objects must always belong to a single Bundle Protec-tion Domain and must never be shared. In contrast, Permission objects must be context free and their instances can potentially be shared between differ-ent Bundle Protection Domains.

9.5 The Permission CheckThe Java 2 security model has both a Security Manager and an Access Con-troller to perform a permission check. The core functionality is located in the AccessControl ler and the AccessControlContext classes that cooperate with Protect ionDomain objects and Permission objects to detect if a permis-sion is granted. Protect ionDomain objects hold the permissions for a num-ber of classes. In the OSGi Framework, a bundle must have a single Bundle Protection Domain.

The Access Controller provides the full functionality for checking a permis-sion. However, for backward compatibility, all system checks are tunneled through the Secur ityManager checkPermission methods. The Security Manager can be replaced by a custom implementation, unlike the Access Controller (it is a final class). This model is depicted in Figure 45

The Conditional Permission Admin guards permissions with a set of condi-tions. A tuple’s permission must only be granted if all its conditions are sat-isfied. Conditions can require user interaction and cause other side effects. One of the consequences of this processing model is that the execution of conditions must be highly optimized. This requires that the Framework must take over the responsibility for the permission check. Therefore, the Framework must replace the Security Manager to implement the Condi-tional Permission Admin in a compliant implementation.

If a Framework implementation is not able to take over the Security Man-ager because another part already has set it, then not all features of this spec-ification can be implemented.

Figure 45 Java 2 Permission checking in OSGi bundles

SecurityManager

Access ControllerFramework Sec. Manager Impl

Access Control Context

Protection Domain

Bundle Protection Domain Impl

active securitymanager

check

for each caller1..*

1 1

checkPermission

1

Permission

currentcall stack

OSGi Service Platform Release 4 219-268

Page 228: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Permission Check Conditional Permission Admin Specification Version 1.0

9.5.1 Check Permission AlgorithmA permission check starts when the Security Manager checkPermiss ion method is called with permission P as argument. This Security Manager must be implemented by the Framework and is therefore called the Frame-work Security Manager; it must be fully integrated with the Conditional Permission Admin service.

The Framework Security Manager must get the Access Control Context in effect. It must call the AccessControl ler getContext() method to get the default context if it is not passed a specific context.

The AccessContro lContext checkPermission method must then be called, which causes the call stack to be traversed. At each stack level the Bundle Protection Domain of the calling class is evaluated for the permission P using the ProtectionDomain impl ies method. This complete evaluation must take place on the same thread.

P must be implied by the local permissions of the Bundle Protection Domain. If this is not the case, the check must end with a failure. Local per-missions are described in Local Permissions on page 210 and Bundle Permission Resource on page 235.

The Bundle Protection Domain must now decide which tuples in its instan-tiated permission table are applicable and imply P .

It must therefore execute the following instructions or reach the same result in an alternative way:

• For each tuple T in the instantiated permission table:• If T has immediate conditions, evaluate all these immediate

Condit ion objects. If any of these objects is not satisfied, continue with next tuple.

• If T ’s permission do no imply P , continue with the next tuple.• If T contains postponed Condit ion objects then postpone the evalua-

tion of T and continue with the next tuple.• Otherwise, remove any postponements and return true

• After all tuples have been processed• If there were any postponements, then return true . Otherwise, return

fa lse .

This algorithm is visualized in a flow chart in Figure 46.

220-268 OSGi Service Platform Release 4

Page 229: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 The Permission Check

Figure 46 Flow chart for Bundle Protection Domain implies method

After the Framework Security Manager has called the checkPermission method of the Access Control Context, it must decide to fail or handle the postponed tuples. If this method returns fa lse , then the Framework Security Manager’s checkPermission method fails.

If it returns t rue , there could still be a set of postponed tuples. Each of these tuples already imply permission P , otherwise they must not have been placed on the postponed list. However, their Condit ion objects still need to be satisfied before true can be returned from the Framework Security Man-ager’s checkPermiss ion method.

implies P

get next tuple T

Any tuples left?

immediateconditions

postponedconditions?

postponethis tuple

yes

return true

return false

no

yes

no

all satisfied?

yes

no

has immediate

permissionsimply P?

no

yes

no

conditions?

yes

has any postponements

no

removepostponements

return true

can be satisfied without postponements

yes

local permissionimply P?

return false

yes

no

OSGi Service Platform Release 4 221-268

Page 230: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Permission Check Conditional Permission Admin Specification Version 1.0

The list of postponed tuples is not a linear list. A number of Bundle Protec-tion Domains can have contributed to this list. Each Bundle Protection Domain must imply the required permissions, therefore, the Framework Security Manager must find at least one tuple per Bundle Protection Domain it can satisfy before it can return t rue from the Framework Security Manager checkPermiss ion method.

For example, if bundle A contributed T1 and bundle B contributed T2to the postponed list, then both T1 and T2 must be satisfied. However, if only bun-dle A contributed T1 and T2 , then either a satisfied T1 or T2 is sufficient to return t rue . This example is depicted in Figure 47.

Figure 47 Evaluation of postponed tuples

Evaluating the tuples must be grouped so that Condit ion objects of the same implementation can be evaluated together. For example, if the user needs to be prompted it is necessary that duplicate conditions are removed and all questions are asked once.

The evaluation of multiple conditions is possible with the isSat isf ied(Condit ion[], Dict ionary) method. This is an instance method but it should be implemented as if it was static. The Condition class can use the set to remove duplicates, remove overlapping conditions, and group any required user interaction. The method can use any semantics to decide if the conditions together evaluate to true or not.

The Dictionary argument of the i sSatisf ied(Condit ion[] , D ict ionary) method is intended to be used by the Condit ion implementation class to maintain state during an invocation of the Framework Security Manager checkPermission method. It is a Dictionary object that:

• Is specific to a Condit ion implementation class, different implemen-tation classes will not share this Dictionary object.

• It is created before the i sSat isf ied(Condit ion[] ,Dict ionary) is called for the first time.

• It is only valid during the invocation of a single checkPermission session. That is, it is not maintained between checkPermission invoca-tions.

• It is shared between invocations of i sSat is f ied(Condit ion[] , Dict ionary) method for different Bundle Protection Domains.

The Framework Security Manager must find at least one tuple per Bundle Protection domain that can be satisfied. It is possible that there are multiple tuples per Bundle Protection Domain, but only one of these tuples needs to be satisfied. The i sSatisf ied(Condit ion[] ,Dict ionary) method must verify

A

B

C

A

B

C

T1

T2

T1 T2postponed

postponed

postponed

Result = T1 AND T2 Result = T2 OR T2

bundle

tuple

222-268 OSGi Service Platform Release 4

Page 231: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 The Permission Check

that all the given conditions are satisfied, not allowing for an OR operation. Grouping can therefore only take place between tuples of different Bundle Protection Domains. That is, grouping must only use the conditions of one tuple per Bundle Protection Domain.

In Figure 48, 3 Bundle Protection Domains are show with each 2 tuples on their postponed list. The Framework security manager must permute these tuples: (T1,T3,T5) , (T2,T3,T5), (T1,T4,T5), (T2,T4, T5) , (T1, T3, T6), (T2, T3, T6) , (T1, T4, T6) , (T2, T4, T6) and evaluate each permutation. Within each permutation, it must use the i sSat isf ied(Condit ion[] ,Dict ionary) to evaluate all Condit ion objects of the same type. The order of the permuta-tions is Framework dependent and can be optimized.

Figure 48 Multiple tuples per domain

The algorithm for the overall evaluation of the Framework Security Man-ager’s checkPermiss ion method is shown in Figure 49 as a flow chart.

A

B

C

T1

T3

postponed

postponed

bundle

tuple

T2

T4

T5 T6postponed

OSGi Service Platform Release 4 223-268

Page 232: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Permission Check Conditional Permission Admin Specification Version 1.0

Figure 49 Flow chart for Framework Security Manager checkPermission method

9.5.2 ExampleA permission P is checked while bundle A , B , and C are on the call stack. Their security setup is as follows (IC = a condition that is immediately evalu-ated, PC is a postponed condition, P , Q , and R are permissions. The tuples are already pre-processed to only match the given bundles. That is, all Bundle*Condit ion objects have already been evaluated and removed):

C: { (Q) } { [IC0] (P) } { [PC2] (P) }

checkPermission P

checkPermission P

success? failno

yes

on Access ControlContext

Permutate with

postponements?

yes

succeedno

one tuple perProt. Domain

failno

Group postponedConditions by class

any more groups?

group isSatisfied?

succeedno

yes

no

see Figure 46

A Permutationwas completelysatisfied ...

No permutation

No Postponements

Failed to find a (possible) solution

failnopermitted bylocal perm.?

any permutationleft?

satisfied

224-268 OSGi Service Platform Release 4

Page 233: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 The Permission Check

First, the Bundle Protection Domain of bundle C is asked if it implies per-mission P . Bundle C has three tuples. The first tuple has no conditions, only a permission that does not imply permission P . The second tuple has an immediate condition IC0 , which is not satisfied. Therefore, the tuple’s per-missions are not considered. The last tuple contains a postponed condition PC2 . Permission P is implied by its permissions. It is not possible to make the decision at this moment in time, therefore the evaluation of tuple C3 is postponed. However, t rue is returned to indicate that the bundle is poten-tially permitted.

B: { [IC1][PC1][PC2] (P) (R) } { [PC2] (P) (R) } { (Q) }

Next, bundle B is considered. Its first tuple has and immediate Condit ion object is IC1 . This condition turns out to be satisfied. This tuple is a potential candidate because it has only two postponed conditions left. It is therefore necessary to check if the tuple is a possibility. It is, because its permissions imply permission P . The tuple is therefore placed on the postponed list to be checked later.

The second tuple is similar. It must also be placed on the postponed list because it implies permission P and it has a postponed condition PC2 .

The last tuple is rejected because it does not imply permission P . However, because there are 2 tuples postponed, the bundle is potentially permitted.

A: { [IC1] [PC1] (P) (Q) } { [IC2] (P) (R) } { (S) }

Bundle A ’s IC1 is evaluated first then it is satisfied. Permission P is implied by the tuple A1 ’s permissions, therefore this tuple is postponed for evalua-tion. However, the second tuple is also satisfied and it directly implies per-mission P . Therefore, the postponed evaluation of PC1 is removed, and bundle A is directly permitted. Tuple A3 does not have to be considered.

After the checkPermiss ion method of the Access Control Context method returns, the Framework Security Manager must evaluate any postponed tuples. The list of postponed tuples looks like Figure 47.

OSGi Service Platform Release 4 225-268

Page 234: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

The Permission Check Conditional Permission Admin Specification Version 1.0

Figure 50 Evaluation of postponed tuples

The Framework Security Manager must now evaluate the permutations (T1, T3) or (T3,T2) . The order of the permutation is undefined, assume (T1, T3) gets chosen first. The condition class PC2 appears in both tuples, therefore T1:PC2 and T3:PC2 must therefore be evaluated in a group with the group version of the i sSatisf ied(Condit ion[] ,Dict ionary) method. PC1 , which must also be true to match, is evaluated with the non-grouped version of isSat isf ied() .

Further assume that (T1, T3) fails, though the user was prompted and agreed, PC1 failed. The PC2 class left a marker in the Dictionary object to prevent another prompt with the same question.

The Framework Security Manager must now try (T2,T3). This must evaluate T2:PC2 and T3:PC2 with the i sSatisf ied(Condit ion[] ,Dict ionary) method. This method was already called for the previous permutation, which could have left information in the Dictionary argument for further evaluations. However, the Dict ionary object now contains the marker from the previous invocation. The i sSatisf ied(Condit ion[] ,Dict ionary) method sees the marker and now returns t rue without prompting the user. This means that the permutation (T2,T3) matches and the Framework Security Manager’s checkPermission method succeeds.

9.5.3 Using the Access Control Context DirectlyBundle programmers can use the standard Java API to do security checks. However, when the Access Controller is used directly (or the Access Control Context) to do the check instead of the Security Manager, then the evalua-tion cannot handle postponed conditions. Therefore, the postponed condi-tions must be treated as immediate conditions by the Bundle Protection Domain in this case.

The implication of this is that the result of checking a permission can depend on the way the check is performed. The normal way of the Security Manager checkPermiss ion method can behave differently than the Access Control Context checkPermission method, depending on the way the check is executed.

A

B

C

T1

T3

postponed

postponed

bundle

tuple

T2

PC1 PC2 PC2

PC2

condition

call stack

226-268 OSGi Service Platform Release 4

Page 235: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 The Permission Check

For example, a bundle on the stack has the needed permission P tied to a User Prompt Condition and another bundle does not have the Permission P . The check would fail if the Security Manager was called and the user would never be prompted. If the Access Control Context were called directly, the user would be prompted before the check failed.

9.5.4 OptimizationsTheoretically, every checkPermiss ion method must evaluate every condi-tion for every bundle on the call stack. That is, the Framework Security Manager must iterate through all bundles on the stack, run through the instantiated permission table of that bundle, evaluate all the conditions, test the permissions, until it finds a permission that is implied. This model would be prohibitively expensive.

Implementations are therefore urged to optimize the evaluation of the per-mission checks as much as possible. They are therefore free to change the algorithms described in this specification as long as the external effect remain the same.

The first optimization is therefore pruning the instantiated permission table. A Condit ion object can be pruned if it is immutable.

If an immutable Condit ion object is satisfied, it can be removed from the tuple’s Condit ion objects because it cannot influence the evaluation any-more. If it is not satisfied, the corresponding tuple can be completely dis-carded because one of the Condit ion objects is not satisfied, making it impossible for the tuple to be used.

If a tuple has no more Condit ion objects after this pruning, the evaluation of the permissions can be optimized by placing all such permissions in a single Permission object (which contains Permiss ionCol lect ion objects). Java 2 security has highly optimized code to do the checking of permissions when they are placed together in a Permission Collection.

For example, assume the following permission table:

{[ ...BundleLocationCondition

"http://www.acme.com/*" ]( ...SocketPermission "www.acme.com" )

} {[ ...BundleLocationCondition

"http://www.et.com/*" ] [ ...Prompt "Call home?" ]

( ...SocketPermission "www.et.com" )}

Assume this table is instantiated for a bundle with a location of http://www.acme.com/bundle . jar . The first tuple’s permissions can be placed in a the special Permission Collection because the Bundle Location condition is immutable and in this case satisfied.

The second tuple can be discarded because it is immutable and not satisfied for the bundle’s location. Any condition that is not satisfied and immutable makes the tuple void.

OSGi Service Platform Release 4 227-268

Page 236: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Management Conditional Permission Admin Specification Version 1.0

9.6 Permission ManagementThe system permissions are managed with the Conditional Permission Admin service. The Conditional Permission Admin can also register the Per-mission Admin service, in that case the two must interact as described in Relation to Permission Admin on page 236.

Permissions are added in their encoded form as a tuple with the addCondi-t ionalPermiss ionInfo(Condit ionInfo[] ,Permiss ionIn fo[]) or setCondit ion-alPermissionIn fo(Str ing,Condit ionInfo[] ,Permiss ion Info[]) method. The difference between the methods is the name parameter. Condit ionalPermiss ionInfo objects can be added anonymously or by name. Each ConditionalPermissionInfo object has a name to distinguish it from others, as well as identifying it to a management server. If no name is given, or the name is nul l , the Conditional Permission Admin service will automat-ically create a name.

The methods return a Condit iona lPermissionInfo object that provides access to the tuple. These objects can also be enumerated with the getCon-dit iona lPermissionInfos() method or a specific named one with the get-Condit ionalPermiss ionInfo(Str ing) method. The name of the object is returned with the getName() method. The Condit ionalPermiss ionInfo delete() method allows a Condit iona lPermissionInfo to be deleted. The tuple consists of an array of Condit ion Infoobjects and an array of PermissionIn fo objects. This is depicted in Figure 51.

Figure 51 Structure of the Info objects.

Both the Condit ional Info and Permiss ionInfo objects can be constructed from encoded strings. The format of the encoded strings are:

ConditionalInfo ::= ’[’ qname ( quoted ) * ’]’ // See 1.4.2PermissionInfo ::= ’(’ qname quoted quoted ’)’

Extra white space must be ignored.

As a convention, Condit iona lPermissionInfo objects are enclosed in curly braces (’{} ’, \u007B, \u007D). There are no encoding and decoding meth-ods. The following example is a code snippet the reads a stream with condi-tional permissions using the curly brace convention. The method parses the file line by line. Each line is trimmed for white space, and then compared to one of the controlling characters. If a matching’} ’ is found, the current con-ditions and permissions are set.

ConditionInfo EMPTY_CS = new ConditionInfo[0];PermissionInfo EMPTY_PS = new PermissionInfo[0];

<<interface>>Conditional Permis. Info

<<class>>Conditional Info

<<class>>Permission Info

<<interface>>Conditional Permis. Admin

1 *

1

**

1

*

name

228-268 OSGi Service Platform Release 4

Page 237: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Permission Management

public void setConditionalPermissionInfo( ConditionalPermissionAdmin admin,

InputStream in) throws Exception {

Vector conditions = null;Vector permissions = null;

InputStreamReader ir = new InputStreamReader(in, "UTF-8");

BufferedReader br = new BufferedReader(ir);

String line = br.readLine();

while (line != null) {line = line.trim();switch (line.charAt(0)) {

case '[' :conditions.add(new ConditionInfo(line));break;

case '(' :permissions.add(new PermissionInfo(line));break;

case '#':break;

case '{':conditions = new Vector();permissions = new Vector();break;

case '}' :admin.addConditionalPermissionInfo(

(ConditionInfo[]) conditions.toArray(EMPTY_CS),

(PermissionInfo[])permissions.toArray(EMPTY_PS));

conditions = permissions = null;break;

default:throw new RuntimeException("Invalid format");

}line = br.readLine();

}}

OSGi Service Platform Release 4 229-268

Page 238: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditions Conditional Permission Admin Specification Version 1.0

9.6.1 Default PermissionsConditional Permission Admin does not have a specific concept of default permissions. Default permissions are derived from the Condit ionalPermiss ionInfo objects that do not have any Condit ion objects. These Condit iona lPermissionInfo objects are applied to all bundles, effec-tively making them default permissions. This is a different from Permission Admin; in Permission Admin default permissions only apply when there are no specific permissions set.

9.7 ConditionsThe purpose of a condition is to decide if a permission set is applicable or not. That is, it acts as a guard. The condition must therefore be evaluated when a Permiss ion object is checked against the effective permissions of a bundle.

The state of a Condit ion object can be obtained with its i sSat isf ied() method. A condition that returns true to this method is called satisfied. If the method throws an Exception, this should be logged and treated as if the con-dition is not satisfied.

Certain Condit ion objects could optimize their evaluations if they are acti-vated multiple times in the same permission check. For example, a user prompt could appear several times in a permission check but the prompt should only be asked once to the user. These conditions are called postponed conditions, conditions that can be verified immediately are called immediate conditions. The i sPostponed() method can inform if the condition is immedi-ate or postponed. If it returns fa lse , the i sSatisf ied method is quick and can be called during the permission check, otherwise the calling of i sSatisf ied must be postponed until the end of the check.

For example, a condition could verify that a mobile phone is roaming. That is, it is not in the home PLMN. This information is readily available in mem-ory and therefore the i sPostponed() method could always return fa lse . Alternatively, a Condit ion object that gets an authorization over the net-work should only be evaluated at most once during a permission check. Such a Condit ion object should return true for the isPostponed method so all the Condit ion objects are evaluated together at the end of the permission check.

Condit ion objects only need to be evaluated multiple times when the answer can change. A Condit ion object that can vary its satisfiability is called mutable, it can be checked with the i sMutab le() method. If the condi-tion is immutable, the Condtional Permission Admin can make significant optimizations by pruning tuples from its instantiated permission table. For example, the Bundle Protection Domain can prune any tuple from its view of the permission table that contains a Condit ion object that is immutable and not satisfied. Such conditions can never be satisfied in the future and therefore the permission tuple can be completely discarded for that Bundle Protection Domain.

230-268 OSGi Service Platform Release 4

Page 239: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Conditions

This significant optimization is leveraged by the provided BundleLocat ionCondit ion and BundleSignerCondit ion classes. The Protec-tion Domain will never have to consider conditional permissions that do not match the protection domain’s bundle. However, a Condit ion object can also start as a mutable condition and later become immutable. For example, a user prompt could have the following states:

• Prompt – The user must be prompted to get the answer, the Conditional Permission Admin will evaluate the answer to detect if it is satisfied.

• Blanket – The user, during an earlier prompt, has indicated it approves or denies access for that remainder of the lifetime of the bundle. In this state, the Condit ion object has become immutable.

This specification provides a number of condition classes to bind permis-sion sets to specific bundles. However, custom code can also provide condi-tions. The following sections first describe how to create a condition class and then define the standard Condit ion classes.

9.7.1 Custom ConditionsCondit ion objects are constructed from Condit ionInfo objects when the per-mission table is instantiated for a Bundle Protection Domain. The Condit ionInfo object supports a variable number of arguments.

The Framework Security Manager must use reflection to find a publ ic static getCondit ion method on the Condit ion implementation class that takes a Bundle object and a Condit ionInfo object as arguments. This method must return a object that implements the Condit ion interface.

However, this does not have to be a new object, the getCondit ion method can reuse objects if it so desires. For example, a Bundle Location Condition is immutable, it therefore maintain only 2 instances: One for bundles that match the given location and one for the others. In the getCondit ion method it can compare the bundle’s location with argument and return either instance.

This is such a common pattern that the Condit ion interface provides two such instances:

• TRUE – A condition object that will always evaluate to true and that is never postponed.

• FALSE – A condition object that will always evaluate to fa lse and that is never postponed.

If no static getCondit ion method can be found, the Conditional Permission Admin service must try to find a public constructor that takes a Bundle object and a Condit ionInfo object as arguments. The Conditional Permis-sion Admin must look for:

public static Condition com.acme.AcmeCondition.getCondition( Bundle, ConditionInfo )

public com.acme.AcmeCondition( Bundle, Condit ionInfo )

If it is not possible to create a condition object, the given condition must be treated as a Condit ion.FALSE object and an error should be logged.

OSGi Service Platform Release 4 231-268

Page 240: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditions Conditional Permission Admin Specification Version 1.0

A Condit ion object will be unique to a Bundle Protection Domain as explained in Encoding versus Instantiation on page 218. Thus, any queries made on a Condit ion object will be with the given Bundle object as context.

If the Framework Security Manager cannot find a proper way to construct the Condit ion object, it should log this and assume that the condition is fa lse .

The next aspect that needs to be addressed is the time of evaluation and the mutability.

The cheapest Condit ion objects are immutable; they have almost no over-head. If a Condit ion object is immutable directly after it is created, then the Framework Security Manager can immediately shortcut future evaluations. That is, if an immutable Condit ion object is not satisfied, its parent tuple can be immediately discarded, it is not even necessary to instantiate any fur-ther Condit ion or Permission objects.

Mutable Condit ion objects must be evaluated during a permission check. Permission checks are common and the evaluation of a permission should therefore be highly optimized. Additional permission checks should be avoided. A mutable condition is system code, it must be designed to work in a constrained environment. The i sSatisf ied() method should be designed to quickly return. It should normally base its decision on variables and limit its side effects.

However, side effects are sometimes necessary; a key example is user prompting. As discussed in Check Permission Algorithm on page 220, the eval-uation of the i sSatisf ied() method can be postponed towards the end of the check. The Condit ion object must return t rue for the isPostponed() method to be postponed.

Postponed Condition objects must optimize their evaluation by implement-ing an instance method i sSatisf ied(Condit ion[] ,Dict ionary) . This method must evaluate a number of conditions together; it is unrelated to the given instance. This grouped evaluation can be used to minimize the number of user prompting, minimize network access, etc.

The following is the code for a condition that verifies that an action is granted by a network server. This is a postponed condition that groups all requests before it asks the host for authorization. The network code is abstracted in a Host class that is not shown here.

public class HostCondition implements Condition {String action;

public HostCondition( Bundle, ConditionInfo info ) {

action = info.getArgs()[0];}

public boolean isSatisfied() { return false; }public boolean isPostponed() { return true; }public boolean isImmutable() { return false; }

static Host host = new Host();

232-268 OSGi Service Platform Release 4

Page 241: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Conditions

public synchronized boolean isSatisfied(Condition[] conditions, Dictionary state ) {Set granted = (Set) state.get("granted");if ( granted == null ) {

granted = new TreeSet();state.put("granted", granted );

}Set pending = new TreeSet();for ( int i=0; i<conditions.length; i++ ) {

String a = ((HostCondition)conditions[i]).action;if ( ! granted.contains(a) )

pending.add( a );}if ( pending.isEmpty() )

return true;

if ( ! host.permits( pending ) )return false;

granted.addAll( pending );return true;

}}

The Host Condition has the following Condition Info representation:

[ HostCondition "payment" ]

The majority of the code is in the i sSatisf iedmethod which takes an array of Condit ion . The constructor only stores the action.

This i sSat is f ied method first gets the set of granted permissions. The first time the method is called this set does not exist. It is then created and stored in the state dictionary for use in later invocations.

Next, a temporary set pending is created to hold all the actions of the condi-tions that are checked, minus any conditions that were already granted dur-ing this invocation of the Security Manager checkPermission method. If the pending list turns out to be empty because all actions were already granted, the method returns true. Otherwise it asks the host. If the host allows the actions, the pending actions are added to the granted set in the state dictio-nary.

9.7.2 Implementation Issues9.7.2.1 Using Permission Checks in Conditions

If there is a chance that permissions will be checked in code being called by i sSatisf ied , the implementer of the Condition should use the AccessControl ler doPr iv i leged to ensure needed permissions. For example, a User Prompt Condition has the potential to cause many permission checks as it interacts with the UI.

OSGi Service Platform Release 4 233-268

Page 242: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Standard Conditions Conditional Permission Admin Specification Version 1.0

However, the same Condition object must not be evaluated recursively. The Framework must detect the recursive evaluation of a Condit ion object and act as if the second invocation returns an unsatisfied, not postponed Condit ion object.

For example, if a User Prompt Condition is evaluated and this evaluation accesses the UI, which in its turn checks a permission that causes the evalu-ation of the same User Prompt Condition, then this second evaluation must not take place and be treated as not postponed and fa lse .

9.7.2.2 Threading

A Condition implementation is guaranteed that a all evaluations necessary for a single checkPermission invocation are carried out on the same thread. However, multiple permission checks can take place on different threads. It is the responsibility of the Condition class implementers to handle these synchronization issues.

9.7.2.3 Class Loading

All conditions must come from the boot class path or from the Framework class loader. This is due to security reasons as well as to prevent the case that there are multiple versions of the implementation packages present. Condi-tions can still be downloaded with bundles by using a Framework extension bundle, see Extension Bundles on page 72.

9.7.2.4 Condition Life Cycle

Condit ion objects will get instantiated when the framework is restarted or the Bundle Protection Domain is created. Framework implementations can also use optimizations that cause Condit ion objects to be created and destroyed multiple times within the lifetime of an instance of a Bundle Pro-tection Domain. An implementation of a Condit ion class must not make any assumptions about its creation or dereferencing.

9.8 Standard ConditionsThis specification provides a number of standard conditions. The OSGi spec-ifications JAR file, which contains all the specification classes, does contain a non-functional implementation of these conditions. Actual Framework implementers must replace these classes with an implementation that is tied to their Framework implementation for efficiency reasons.

9.8.1 Bundle Signer ConditionA Bundle Signer Condition is satisfied when the related bundle is signed with a certificate that matches its argument. That is, this condition can be used to assign permissions to bundles that are signed by certain principals.

The Bundle Signer Condition must be created through its static getCondit ion(Bundle,Condit ionInfo) method. The string argument is a matching Distinguished Name as defined in Certificate Matching on page 23. For example:

[ ...BundleSignerCondition "* ;cn=S&V, o=Tweety Inc., c=US"]

234-268 OSGi Service Platform Release 4

Page 243: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 Bundle Permission Resource

The Bundle Signer Condition is immutable and can be completely evaluated during the getCondit ion method.

9.8.2 Bundle Location ConditionThe Bundle Location Condition matches its argument against the location string of the bundle argument. Bundle location matching provides many of the advantages of signing without the overhead. However, using locations as the authenticator requires that the download locations are secured and cannot be spoofed. For example, an Operator could permit Enterprises by forcing them to download their bundles from specific locations. To make this reasonable secure, at least the HTTPS protocol should be used. The Operator can then use the location to assign permissions.

https://www.acme.com/download/* Apps from ACMEhttps://www.operator.com/download/* Operator apps

The Bundle Location Condition must be created through its static getCondit ion(Bundle,Condit ionInfo) method. The string argument is a location string with possible wildcards (’*’). Wildcards are matched using Filter string matching. For example:

http://www.acme.com/**://www.acme.com/*

The Bundle Location Condition is satisfied when its argument can be matched with the actual location.

The Bundle Location Condition is immutable and can be completely evalu-ated during the getCondit ion method.

9.9 Bundle Permission ResourceBundles can convey their local permissions using the file OSGI- INF/permissions.perm . This must be a UTF-8 encoded file. The format of the file is line based; lines are not limited in length but must be readable with the BufferedReader readLine method:

permission.perm ::= line *line ::= ( comment | pinfo ) ’\r\n’comment ::= ( ’#’ | ’//’ | /* blank */ )pinfo ::= ’(’ qname quoted-string

quoted-string ’)’ // See 1.4.2

Each permission must be listed on its own line using the encoded form of Permission Info. Comment lines are allowed. They consist of lines starting with a #or // , where leading spaces must be ignored. Multiple spaces outside quotes must be treated as a single space.

For example ( . . must be replaced with the appropriate package prefix.):

# Friday, Feb 24 2005# ACME, chess game( ..ServicePermission "..log.LogService" "GET" )( ..PackagePermission "..log" "IMPORT" )( ..ServicePermission "..cm.ManagedService" "REGISTER" )

OSGi Service Platform Release 4 235-268

Page 244: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Relation to Permission Admin Conditional Permission Admin Specification Version 1.0

( ..PackagePermission "..cm" "IMPORT" )( ..ServicePermission "..useradmin.UserAdmin" "GET" )( ..PackagePermission "..cm" "SET" )( ..PackagePermission "com.acme.chess" "IMPORT,EXPORT" )( ..PackagePermission "com.acme.score" "IMPORT" )

If this resource is present in the Bundle JAR, it will set the local permissions. If it is not present, the local permissions must be All Permission.

9.9.1 Removing the Bundle Permission ResourceAn attacker could circumvent the local permission by simply removing the permissions.perm file from the bundle. This would remove any local per-missions that were required by a signer of the bundle. To prevent this type of attack the Conditional Permission Admin must detect that the permissions.perm resource was signed, that is, present in the Manifest, but that it is not in the JAR. If the bundle is being installed when this condition is detected, the install must fail with a Bundle Exception.

9.10 Relation to Permission AdminIf the framework provides a Conditional Permission Admin service and a Permission Admin service then the location bound permission of the Per-mission Admin service must override any information of the Conditional Permission Admin service. Otherwise, the concepts of Conditional Permis-sion Admin service apply.

The Permission Admin defines a concept of Default Permissions, which is not supported by Conditional Permission Admin. Default permissions are now modeled with an empty set of conditions. Empty sets of conditions apply to all bundles, this in addition to any more specific conditions. This is very dif-ferent from the Permission Admin service where the default permissions only apply when there is no location bound permission for that bundle. The default conditions of Permission Admin are therefore never used when Con-ditional Permission Admin is present.

New applications should use the Conditional Permission Admin service. The Permission Admin service will be deprecated in a future release.

9.11 Security

9.11.1 Service Registry Security9.11.1.1 Conditional Permission Admin Service

The Conditional Permission Admin service should be part of the Frame-work and therefore has All Permission.

9.11.1.2 ClientServicePermission ..ConditionalPermissionAdmin GETPackagePermission ..condpermadmin IMPORTAllPermission

236-268 OSGi Service Platform Release 4

Page 245: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 org.osgi.service.condpermad-

Clients of the Conditional Permission Admin service that set permissions must themselves have All Permission because they can give All Permission to any bundle.

9.12 org.osgi.service.condpermadminThe OSGi Conditional Permission Admin Specification Version 1.0.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle’s manifest. For example:

Import-Package: org.osgi.service.condpermadmin; version=1.0

9.12.1 Summary• BundleLocationCondition - Condition to test if the location of a bundle

matches a pattern. [p.237]• BundleSignerCondition - Condition to test if the signer of a bundle

matches a pattern. [p.237]• Condition - The interface implemented by a Condition. [p.238]• ConditionalPermissionAdmin - Framework service to administer Condi-

tional Permissions. [p.239]• ConditionalPermissionInfo - A binding of a set of Conditions to a set of

Permissions. [p.240]• ConditionInfo - Condition representation used by the Conditional Per-

mission Admin service. [p.241]BundleLocationCondition

9.12.2 public class BundleLocationConditionCondition to test if the location of a bundle matches a pattern. Pattern matching is done according to the filter string matching rules. getCondition(Bundle,ConditionInfo)

9.12.2.1 public static Condition getCondition( Bundle bundle, ConditionInfo info )

bundle The Bundle being evaluated.

info The ConditionInfo to construct the condition for. The args of the Condition-Info must be a single String which specifies the location pattern to match against the Bundle location. Matching is done according to the filter string matching rules. Any ‘*’ characters in the location argument are used as wild-cards when matching bundle locations unless they are escaped with a ‘\’char-acter.

Constructs a condition that tries to match the passed Bundle’s location to the location pattern.

Returns Condition object for the requested condition.BundleSignerCondition

9.12.3 public class BundleSignerConditionCondition to test if the signer of a bundle matches a pattern. Since the bun-dle’s signer can only change when the bundle is updated, this condition is immutable.

OSGi Service Platform Release 4 237-268

Page 246: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.condpermadmin Conditional Permission Admin Specification Version

The condition expressed using a single String that specifies a Distinguished Name (DN) chain to match bundle signers against. DN’s are encoded using IETF RFC 2253. Usually signers use certificates that are issued by certificate authorities, which also have a corresponding DN and certificate. The certifi-cate authorities can form a chain of trust where the last DN and certificate is known by the framework. The signer of a bundle is expressed as signers DN followed by the DN of its issuer followed by the DN of the next issuer until the DN of the root certificate authority. Each DN is separated by a semico-lon.

A bundle can satisfy this condition if one of its signers has a DN chain that matches the DN chain used to construct this condition. Wildcards (̀*’) can be used to allow greater flexibility in specifying the DN chains. Wildcards can be used in place of DNs, RDNs, or the value in an RDN. If a wildcard is used for a value of an RDN, the value must be exactly “*” and will match any value for the corresponding type in that RDN. If a wildcard is used for a RDN, it must be the first RDN and will match any number of RDNs (includ-ing zero RDNs).getCondition(Bundle,ConditionInfo)

9.12.3.1 public static Condition getCondition( Bundle bundle, ConditionInfo info )

bundle The Bundle being evaluated.

info The ConditionInfo to construct the condition for. The args of the Condition-Info specify a single String specifying the chain of distinguished names pat-tern to match against the signer of the Bundle.

Constructs a Condition that tries to match the passed Bundle’s location to the location pattern.

Returns A Condition which checks the signers of the specified bundle.Condition

9.12.4 public interface ConditionThe interface implemented by a Condition. Conditions are bound to Permis-sions using Conditional Permission Info. The Permissions of a ConditionalP-ermission Info can only be used if the associated Conditions are satisfied. FALSE

9.12.4.1 public static final Condition FALSE

A Condition object that will always evaluate to false and that is never post-poned. TRUE

9.12.4.2 public static final Condition TRUE

A Condition object that will always evaluate to true and that is never post-poned. isMutable()

9.12.4.3 public boolean isMutable( )

Returns whether the Condition is mutable.

Returns true to indicate the value returned by i sSat isf ied() [p.239] can change. Other-wise, false if the value returned by i sSat is f ied()[p.239] will not change.isPostponed()

238-268 OSGi Service Platform Release 4

Page 247: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 org.osgi.service.condpermad-

9.12.4.4 public boolean isPostponed( )

Returns whether the evaluation must be postponed until the end of the per-mission check. This method returns true if the evaluation of the Condition must be postponed until the end of the permission check. If this method returns false, this Condition must be able to directly answer the i sSatisf ied() [p.239] method. In other words, isSatisfied() will return very quickly since no external sources, such as for example users, need to be con-sulted.

Returns true to indicate the evaluation must be postponed. Otherwise, false if the evaluation can be immediately performed.isSatisfied()

9.12.4.5 public boolean isSatisfied( )

Returns whether the Condition is satisfied.

Returns true to indicate the Conditions is satisfied. must be postponed. Otherwise, false if the Condition is not satisfied.isSatisfied(Condition[],Dictionary)

9.12.4.6 public boolean isSatisfied( Condition[] conditions, Dictionary context )

conditions The array of Conditions.

context A Dictionary object that implementors can use to track state. If this method is invoked multiple times in the same permission evaluation, the same Dic-tionary will be passed multiple times. The SecurityManager treats this Dic-tionary as an opaque object and simply creates an empty dictionary and passes it to subsequent invocations if multiple invocatios are needed.

Returns whether a the set of Conditions are satisfied. Although this method is not static, it must be implemented as if it were static. All of the passed Conditions will be of the same type and will correspond to the class type of the object on which this method is invoked.

Returns true if all the Conditions are satisfied. Otherwise, false if one of the Condi-tions is not satisfied.ConditionalPermissionAdmin

9.12.5 public interface ConditionalPermissionAdminFramework service to administer Conditional Permissions. Conditional Per-missions can be added to, retrieved from, and removed from the framework. addConditionalPermissionInfo(ConditionInfo[],PermissionInfo[])

9.12.5.1 public ConditionalPermissionInfo addConditionalPermissionInfo( ConditionInfo[] conds, PermissionInfo[] perms )

conds The Conditions that need to be satisfied to enable the corresponding Permis-sions.

perms The Permissions that are enable when the corresponding Conditions are sat-isfied.

Create a new Conditional Permission Info. The Conditional Permission Info will be given a unique, never reused name.

Returns The ConditionalPermissionInfo for the specified Conditions and Permis-sions.

Throws SecurityException – If the caller does not have AllPermission. getAccessControlContext(String[])

9.12.5.2 public AccessControlContext getAccessControlContext( String[] signers

OSGi Service Platform Release 4 239-268

Page 248: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.condpermadmin Conditional Permission Admin Specification Version

)

signers The signers for which to return an Access Control Context.

Returns the Access Control Context that corresponds to the specified sign-ers.

Returns An AccessControlContext that has the Permissions associated with the sign-er.getConditionalPermissionInfo(String)

9.12.5.3 public ConditionalPermissionInfo getConditionalPermissionInfo( String name )

name The name of the Conditional Permission Info to be returned.

Return the Conditional Permission Info with the specified name.

Returns The Conditional Permission Info with the specified name.getConditionalPermissionInfos()

9.12.5.4 public Enumeration getConditionalPermissionInfos( )

Returns the Conditional Permission Infos that are currently managed by Conditional Permission Admin. Calling Condit ionalPermiss ionInfo.delete() [p.240] will remove the Conditional Permission Info from Conditional Permission Admin.

Returns An enumeration of the Conditional Permission Infos that are currently man-aged by Conditional Permission Admin.setConditionalPermissionInfo(String,ConditionInfo[],PermissionInfo[])

9.12.5.5 public ConditionalPermissionInfo setConditionalPermissionInfo( String name, ConditionInfo[] conds, PermissionInfo[] perms )

name The name of the Conditional Permission Info, or null.

conds The Conditions that need to be satisfied to enable the corresponding Permis-sions.

perms The Permissions that are enable when the corresponding Conditions are sat-isfied.

Set or create a Conditional Permission Info with a specified name. If the specified name is null, a new Conditional Permission Info must be created and will be given a unique, never reused name. If there is currently no Con-ditional Permission Info with the specified name, a new Conditional Per-mission Info must be created with the specified name. Otherwise, the Conditional Permission Info with the specified name must be updated with the specified Conditions and Permissions.

Returns The ConditionalPermissionInfo that for the specified name, Conditions and Permissions.

Throws SecurityException – If the caller does not have AllPermission. ConditionalPermissionInfo

9.12.6 public interface ConditionalPermissionInfoA binding of a set of Conditions to a set of Permissions. Instances of this interface are obtained from the Conditional Permission Admin service. delete()

9.12.6.1 public void delete( )

Removes this Conditional Permission Info from the Conditional Permission Admin.

240-268 OSGi Service Platform Release 4

Page 249: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 org.osgi.service.condpermad-

Throws SecurityException – If the caller does not have AllPermission. getConditionInfos()

9.12.6.2 public ConditionInfo[] getConditionInfos( )

Returns the Condition Infos for the Conditions that must be satisfied to enable the Permissions.

Returns The Condition Infos for the Conditions in this Conditional Permission Info.getName()

9.12.6.3 public String getName( )

Returns the name of this Conditional Permission Info.

Returns The name of this Conditional Permission Info.getPermissionInfos()

9.12.6.4 public PermissionInfo[] getPermissionInfos( )

Returns the Permission Infos for the Permission in this Conditional Permis-sion Info.

Returns The Permission Infos for the Permission in this Conditional Permission Info.ConditionInfo

9.12.7 public class ConditionInfoCondition representation used by the Conditional Permission Admin ser-vice.

This class encapsulates two pieces of information: a Condition type (class name), which must implement Condition, and the arguments passed to its constructor.

In order for a Condition represented by a ConditionInfo to be instantiated and considered during a permission check, its Condition class must be avail-able from the system classpath.

The Condition class must either:

• Declare a public static getCondition method that takes a Bundle object and a ConditionInfo object as arguments. That method must return an object that implements the Condition interface.

• Implement the Condition interface and define a public constructor that takes a Bundle object and a ConditionInfo object as arguments.

ConditionInfo(String,String[])

9.12.7.1 public ConditionInfo( String type, String[] args )

type The fully qualified class name of the Condition represented by this Condi-tionInfo.

args The arguments for the Condition. These arguments are available to the new-ly created Condition by calling the getArgs() [p.242] method.

Constructs a ConditionInfo from the specified type and args.

Throws NullPointerException – If type is null. ConditionInfo(String)

9.12.7.2 public ConditionInfo( String encodedCondition )

encodedCondition The encoded ConditionInfo.

Constructs a ConditionInfo object from the specified encoded Condition-Info string. White space in the encoded ConditionInfo string is ignored.

Throws IllegalArgumentException – If the encodedCondition is not properly for-matted.

OSGi Service Platform Release 4 241-268

Page 250: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.condpermadmin Conditional Permission Admin Specification Version

See Also getEncoded[p.242]equals(Object)

9.12.7.3 public boolean equals( Object obj )

obj The object to test for equality with this ConditionInfo object.

Determines the equality of two ConditionInfo objects. This method checks that specified object has the same type and args as this ConditionInfo object.

Returns true if obj is a ConditionInfo, and has the same type and args as this Condi-tionInfo object; false otherwise.getArgs()

9.12.7.4 public final String[] getArgs( )

Returns arguments of this ConditionInfo.

Returns The arguments of this ConditionInfo. An empty array is returned if the Con-ditionInfo has no arguments.getEncoded()

9.12.7.5 public final String getEncoded( )

Returns the string encoding of this ConditionInfo in a form suitable for restoring this ConditionInfo.

The encoding format is:

[type “arg0” “arg1” ...]

where argN are strings that are encoded for proper parsing. Specifically, the “, \, carriage return, and linefeed characters are escaped using \”, \\, \r, and \n, respectively.

The encoded string contains no leading or trailing whitespace characters. A single space character is used between type and “arg0“ and between the arguments.

Returns The string encoding of this ConditionInfo.getType()

9.12.7.6 public final String getType( )

Returns the fully qualified class name of the condition represented by this ConditionInfo.

Returns The fully qualified class name of the condition represented by this Condi-tionInfo.hashCode()

9.12.7.7 public int hashCode( )

Returns the hash code value for this object.

Returns A hash code value for this object.toString()

9.12.7.8 public String toString( )

Returns the string representation of this ConditionInfo. The string is created by calling the getEncoded method on this ConditionInfo.

Returns The string representation of this ConditionInfo.

242-268 OSGi Service Platform Release 4

Page 251: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Conditional Permission Admin Specification Version 1.0 References

References9.13 References

[46] Java 1.3http://java.sun.com/j2se/1.3

OSGi Service Platform Release 4 243-268

Page 252: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References Conditional Permission Admin Specification Version 1.0

244-268 OSGi Service Platform Release 4

Page 253: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Admin Service Specification Version 1.2 Introduction

10 Permission Admin Service SpecificationVersion 1.2

10.1 IntroductionIn the Framework, a bundle can have a single set of permissions. These per-missions are used to verify that a bundle is authorized to execute privileged code. For example, a Fi lePermission defines what files can be used and in what way.

The policy of providing the permissions to the bundle should be delegated to a Management Agent. For this reason, the Framework provides the Per-mission Admin service so that a Management Agent can administrate the permissions of a bundle and provide defaults for all bundles.

Related mechanisms of the Framework are discussed in Security Overview on page 13.

10.1.1 Essentials• Status information – The Permission Admin Service must provide status

information about the current permissions of a bundle.• Administrative – The Permission Admin Service must allow a Man-

agement Agent to set the permissions before, during, or after a bundle is installed.

• Defaults – The Permission Admin Service must provide control over default permissions. These are the permissions for a bundle with no spe-cific permissions set.

10.1.2 Entities• PermissionAdmin – The service that provides access to the permission

repository of the Framework.• PermissionInfo – An object that holds the information needed to con-

struct a Permission object.• Bundle location – The string that specifies the bundle location. This is

described in Bundle Identifiers on page 81.

OSGi Service Platform Release 4 245-268

Page 254: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Admin service Permission Admin Service Specification Version 1.2

Figure 52 Class Diagram org.osgi.service.permissionadmin.

10.1.3 OperationThe Framework maintains a repository of permissions. These permissions are stored under the bundle location string. Using the bundle location allows the permissions to be set before a bundle is downloaded. The Frame-work must consult this repository when it needs the permissions of a bun-dle. When no specific permissions are set, the bundle must use the default permissions. If no default is set, the bundle must use java.security .Al lPermission . If the default permissions are changed, a bun-dle with no specific permissions must immediately start using the new default permissions.

The Permission Admin service is registered by the Framework’s system bun-dle under the org.osg i.service .permiss ionadmin.PermissionAdmin inter-face. This is an optional singleton service, so at most one Permission Admin service is registered at any moment in time.

The Permission Admin service provides access to the permission repository. A Management Agent can get, set, update, and delete permissions from this repository. A Management Agent can also use a SynchronousBundleListener object to set the permissions during the instal-lation or updating of a bundle.

10.2 Permission Admin serviceThe Permission Admin service needs to manipulate the default permissions and the permissions associated with a specific bundle. The default permis-sions and the bundle-specific permissions are stored persistently. It is possi-ble to set a bundle’s permissions before the bundle is installed in the Framework because the bundle’s location is used to set the bundle’s permis-sions.

The manipulation of a bundle’s permissions, however, may also be done in real time when a bundle is downloaded or just before the bundle is down-loaded. To support this flexibility, a SynchronousBundleListener object may be used by a Management Agent to detect the installation or update of a bundle, and set the required permissions before the installation completes.

Permissions are activated before the first time a permission check for a bun-dle is performed. This means that if a bundle has opened a file, this file must remain usable even if the permission to open that file is removed at a later time.

<<interface>>PermissionAdmin

<<class>>PermissionInfo

0..n1

java.security.Permission

constructs

1

1

bundle location

246-268 OSGi Service Platform Release 4

Page 255: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Admin Service Specification Version 1.2 Permission Admin service

Permission information is not specified using java.security .Permission objects. The reason for this approach is the relationship between the required persistence of the information across Framework restarts and the concept of class loaders in the Framework. Actual Permission classes must be subclasses of Permission and may be exported from any bundle. The Framework can access these permissions as long as they are exported, but the Management Agent would have to import all possible packages that contain permissions. This requirement would severely limit permission types. Therefore, the Permission Admin service uses the Permiss ionInfo class to specify permission information. Objects of this class are used by the Framework to create Permission objects.

Permission Info objects restrict the possible Permission objects that can be used. A Permiss ion subclass can only be described by a Permiss ionInfo object when it has the following characteristics:

• It must be a subclass of java.security .Permission . • It must use the two-argument public constructor type(name,act ions) .• The class must be available to the Framework code from the system class

path or from any exported package so it can be loaded by the Framework.• The class must be public.

If any of these conditions is not met, the Permiss ionInfo object must be ignored and an error message should be logged.

The permissions are always set as an array of PermissionIn fo objects to make the assignment of all permissions atomic.

The PermissionAdmin interface provides the following methods:

• getLocat ions() – Returns a list of locations that have permissions assigned to them. This method allows a Management Agent to examine the current set of permissions.

• getPermissions(Str ing) – Returns a list of Permiss ion Info objects that are set for that location, or returns nul l if no permissions are set.

• setPermiss ions(Str ing,PermissionInfo[]) – Associates permissions with a specific location, or returns null when the permissions should be removed.

• getDefau ltPermissions() – This method returns the list of default per-missions.

• setDefaultPermissions(PermissionInfo[]) – This method sets the default permissions.

10.2.1 File Permission for Relative Path NamesA java . io .Fi lePermission assigned to a bundle via the setPermiss ions method must receive special treatment if the path argument for the Fi lePermiss ion is a relative path name. A relative path name is one that is not absolute. See the java . io .Fi le . isAbsolute method for more information on absolute path names.

When a bundle is assigned a Fi lePermission for a relative path name, the path name is taken to be relative to the bundle’s persistent storage area. This allows additional permissions, such as execute, to be assigned to files in the bundle’s persistent storage area. For example:

java.io.FilePermission "-" "execute"

OSGi Service Platform Release 4 247-268

Page 256: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Security Permission Admin Service Specification Version 1.2

can be used to allow a bundle to execute any file in the bundle’s persistent storage area.

This only applies to Fi lePermission objects assigned to a bundle via the setPermiss ion method. This does not apply to default permissions. A Fi lePermission for a relative path name assigned via the setDefaultPermission method must be ignored.

10.3 SecurityThe Permission Admin service is a system service that can be abused. A bun-dle that can access and use the Permission Admin service has full control over the OSGi Service Platform. However, many bundles can have ServicePermission[PermissionAdmin,GET] because all methods that change the state of the Framework require AdminPermission .

No bundle must have ServicePermission[PermissionAdmin,REGISTER] for this service because only the Framework should provide this service.

10.4 ChangesThe following descriptions were added relative to the previous version of this specification:

• Permission Info was updated to allow white space in the encoded format.• The Package Admin methods which change the permissions now

require the caller to have AllPermission . This is necessary because simply requiring a specific permission to change a bundle’s permissions would allow such a bundle to elevate the permission of any bundle including itself to Al lPermission .

10.5 org.osgi.service.permissionadminThe OSGi Permission Admin service Package. Specification Version 1.2.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle’s manifest. For example:

Import-Package: org.osgi.service.permissionadmin; version=1.2

10.5.1 Summary• PermissionAdmin - The Permission Admin service allows management

agents to manage the permissions of bundles. [p.248]• PermissionInfo - Permission representation used by the Permission

Admin service. [p.250]PermissionAdmin

10.5.2 public interface PermissionAdminThe Permission Admin service allows management agents to manage the permissions of bundles. There is at most one Permission Admin service present in the OSGi environment.

248-268 OSGi Service Platform Release 4

Page 257: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Admin Service Specification Version 1.2 org.osgi.service.permissionadmin

Access to the Permission Admin service is protected by corresponding Servi-cePermission. In addition AdminPermission is required to actually set per-missions.

Bundle permissions are managed using a permission table. A bundle’s loca-tion serves as the key into this permission table. The value of a table entry is the set of permissions (of type PermissionInfo) granted to the bundle named by the given location. A bundle may have an entry in the permission table prior to being installed in the Framework.

The permissions specified in setDefaultPermissions are used as the default permissions which are granted to all bundles that do not have an entry in the permission table.

Any changes to a bundle’s permissions in the permission table will take effect no later than when bundle’s java.security.ProtectionDomain is next involved in a permission check, and will be made persistent.

Only permission classes on the system classpath or from an exported pack-age are considered during a permission check. Additionally, only permis-sion classes that are subclasses of java.security.Permission and define a 2-argument constructor that takes a name string and an actions string can be used.

Permissions implicitly granted by the Framework (for example, a bundle’s permission to access its persistent storage area) cannot be changed, and are not reflected in the permissions returned by getPermissions and getDefault-Permissions.getDefaultPermissions()

10.5.2.1 public PermissionInfo[] getDefaultPermissions( )

Gets the default permissions.

These are the permissions granted to any bundle that does not have permis-sions assigned to its location.

Returns The default permissions, or null if no default permissions are set.getLocations()

10.5.2.2 public String[] getLocations( )

Returns the bundle locations that have permissions assigned to them, that is, bundle locations for which an entry exists in the permission table.

Returns The locations of bundles that have been assigned any permissions, or null if the permission table is empty.getPermissions(String)

10.5.2.3 public PermissionInfo[] getPermissions( String location )

location The location of the bundle whose permissions are to be returned.

Gets the permissions assigned to the bundle with the specified location.

Returns The permissions assigned to the bundle with the specified location, or null if that bundle has not been assigned any permissions.setDefaultPermissions(PermissionInfo[])

10.5.2.4 public void setDefaultPermissions( PermissionInfo[] permissions )

permissions The default permissions, or null if the default permissions are to be removed from the permission table.

Sets the default permissions.

OSGi Service Platform Release 4 249-268

Page 258: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.permissionadmin Permission Admin Service Specification Version 1.2

These are the permissions granted to any bundle that does not have permis-sions assigned to its location.

Throws SecurityException – If the caller does not have AllPermission. setPermissions(String,PermissionInfo[])

10.5.2.5 public void setPermissions( String location, PermissionInfo[] permissions )

location The location of the bundle that will be assigned the permissions.

permissions The permissions to be assigned, or null if the specified location is to be re-moved from the permission table.

Assigns the specified permissions to the bundle with the specified location.

Throws SecurityException – If the caller does not have AllPermission. PermissionInfo

10.5.3 public class PermissionInfoPermission representation used by the Permission Admin service.

This class encapsulates three pieces of information: a Permission type (class name), which must be a subclass of java.security.Permission, and the name and actions arguments passed to its constructor.

In order for a permission represented by a PermissionInfo to be instantiated and considered during a permission check, its Permission class must be available from the system classpath or an exported package. This means that the instantiation of a permission represented by a PermissionInfo may be delayed until the package containing its Permission class has been exported by a bundle.PermissionInfo(String,String,String)

10.5.3.1 public PermissionInfo( String type, String name, String actions )

type The fully qualified class name of the permission represented by this Permis-sionInfo. The class must be a subclass of java.security.Permission and must define a 2-argument constructor that takes a name string and an actions string.

name The permission name that will be passed as the first argument to the con-structor of the Permission class identified by type.

actions The permission actions that will be passed as the second argument to the constructor of the Permission class identified by type.

Constructs a PermissionInfo from the specified type, name, and actions.

Throws NullPointerException – if type is null.

IllegalArgumentException – if action is not null and name is null. PermissionInfo(String)

10.5.3.2 public PermissionInfo( String encodedPermission )

encodedPermission The encoded PermissionInfo.

Constructs a PermissionInfo object from the specified encoded Permission-Info string. White space in the encoded PermissionInfo string is ignored.

Throws IllegalArgumentException – If the encodedPermission is not properly for-matted.

See Also getEncoded[p.251]equals(Object)

250-268 OSGi Service Platform Release 4

Page 259: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Permission Admin Service Specification Version 1.2 org.osgi.service.permissionadmin

10.5.3.3 public boolean equals( Object obj )

obj The object to test for equality with this PermissionInfo object.

Determines the equality of two PermissionInfo objects. This method checks that specified object has the same type, name and actions as this Permission-Info object.

Returns true if obj is a PermissionInfo, and has the same type, name and actions as this PermissionInfo object; false otherwise.getActions()

10.5.3.4 public final String getActions( )

Returns the actions of the permission represented by this PermissionInfo.

Returns The actions of the permission represented by this PermissionInfo, or null if the permission does not have any actions associated with it.getEncoded()

10.5.3.5 public final String getEncoded( )

Returns the string encoding of this PermissionInfo in a form suitable for restoring this PermissionInfo.

The encoded format is:

(type)

or

(type “name”)

or

(type “name” “actions”)

where name and actions are strings that are encoded for proper parsing. Spe-cifically, the “,\, carriage return, and linefeed characters are escaped using \”, \\,\r, and \n, respectively.

The encoded string contains no leading or trailing whitespace characters. A single space character is used between type and “name“ and between “name“ and “actions“.

Returns The string encoding of this PermissionInfo.getName()

10.5.3.6 public final String getName( )

Returns the name of the permission represented by this PermissionInfo.

Returns The name of the permission represented by this PermissionInfo, or null if the permission does not have a name.getType()

10.5.3.7 public final String getType( )

Returns the fully qualified class name of the permission represented by this PermissionInfo.

Returns The fully qualified class name of the permission represented by this Permis-sionInfo.hashCode()

10.5.3.8 public int hashCode( )

Returns the hash code value for this object.

Returns A hash code value for this object.toString()

OSGi Service Platform Release 4 251-268

Page 260: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.permissionadmin Permission Admin Service Specification Version 1.2

10.5.3.9 public String toString( )

Returns the string representation of this PermissionInfo. The string is cre-ated by calling the getEncoded method on this PermissionInfo.

Returns The string representation of this PermissionInfo.

252-268 OSGi Service Platform Release 4

Page 261: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 Introduction

11 URL Handlers Service SpecificationVersion 1.0

11.1 IntroductionThis specification defines how to register new URL schemes and how to con-vert content-typed java. io. InputStream objects to specific Java objects.

This specification standardizes the mechanism to extend the Java run-time with new URL schemes and content handlers through bundles. Dynami-cally extending the URL schemes that are supported in an OSGi Service Plat-form is a powerful concept.

This specification is necessary because the standard Java mechanisms for extending the URL class with new schemes and different content types is not compatible with the dynamic aspects of an OSGi Service Platform. The reg-istration of a new scheme or content type is a one time only action in Java, and once registered, a scheme or content type can never be revoked. This singleton approach to registration makes the provided mechanism impossi-ble to use by different, independent bundles. Therefore, it is necessary for OSGi Framework implementations to hide this mechanism and provide an alternative mechanism that can be used.

The Release 4 specifications has also standardized a Connector service that has similar capabilities. See the IO Connector Service Specification on page 219.

11.1.1 Essentials• Multiple Access – Multiple bundles should be allowed to register

ContentHandler objects and URLStreamHandler objects.• Existing Schemes Availability – Existing schemes in an OSGi Service

Platform should not be overridden.• life cycle Monitored – The life cycle of bundles must be supported. Scheme

handlers and content type handlers must become unavailable when the registering bundle is stopped.

• Simplicity – Minimal effort should be required for a bundle to provide a new URL scheme or content type handler.

11.1.2 Entities• Scheme – An identifier for a specific protocol. For example, "http" is a

scheme for the Hyper Text Transfer Protocol. A scheme is implemented in a java.net .URLStreamHandler sub-class.

• Content Type – An identifier for the type of the content. Content types are usually referred to as MIME types. A content type handler is imple-mented as a java.net .ContentHandler sub-class.

OSGi Service Platform Release 4 253-268

Page 262: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Introduction URL Handlers Service Specification Version 1.0

• Uniform Resource Locator (URL) – An instance of the java.net .URL class that holds the name of a scheme with enough parameters to identify a resource for that scheme.

• Factory – An object that creates other objects. The purpose is to hide the implementation types (that may vary) from the caller. The created objects are a subclass/implementation of a specific type.

• Proxy – The object that is registered with Java and that forwards all calls to the real implementation that is registered with the service registry.

• java.net.URLStreamHandler – An instance of the java .net.URLStreamHandler class that can create URLConnection objects that represent a connection for a specific protocol.

• Singleton Operation – An operation that can only be executed once.• URLStreamHandlerService – An OSGi service interface that contains the

methods of the URLStreamHandler class with public visibility so they can be called from the Framework.

• AbstractURLStreamHandlerService – An implementation of the URLStreamHandlerServ ice interface that implements the interface’s methods by calling the implementation of the super class (java.net.u rl .URLStreamHandler). This class also handles the setting of the java.net.URL object via the java.net.URLStreamHandlerSetter interface.

• URLStreamHandlerSetter – An interface needed to abstract the setting of the java.net.URL object. This interface is related to the use of a proxy and security checking.

• java.net.URLStreamHandlerFactory – A factory, registered with the java .net.URL class, that is used to find java.net .URLStreamHandler objects implementing schemes that are not implemented by the Java environment. Only one java.net .URLStreamHandlerFactory object can be registered with Java.

• java.net.URLConnection – A connection for a specific, scheme-based pro-tocol. A java.net.URLConnection object is created by a java .net.URLStreamHandler object when the java .net.URL.openConnection method is invoked.

• java.net.ContentHandler – An object that can convert a stream of bytes to a Java object. The class of this Java object depends on the MIME type of the byte stream.

• java.net.ContentHandlerFactory – A factory that can extend the set of java .net.ContentHandler objects provided by the java .net.URLConnection class, by creating new ones on demand. Only one java .net.ContentHandlerFactory object can be registered with the java .net.URLConnection class.

• MIME Type – A name space for byte stream formats. See [49] MIME Multi-purpose Internet Mail Extension.

The following class diagram is surprisingly complex due to the complicated strategy that Java uses to implement extendable stream handlers and con-tent handlers.

254-268 OSGi Service Platform Release 4

Page 263: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 Introduction

Figure 53 Class Diagram, java.net (URL and associated classes)

11.1.3 OperationA bundle that can implement a new URL scheme should register a service object under the URLStreamHandlerService interface with the OSGi Frame-work. This interface contains public versions of the java.net .URLStreamHandler class methods, so that these methods can be called by the proxy (the object that is actually registered with the Java run-time).

The OSGi Framework implementation must make this service object avail-able to the underlying java.net implementation. This must be supported by the OSGi Framework implementation because the java.net .URL .setStreamHandlerFactory method can only be called once, making it impossible to use by bundles that come and go.

java.net.URL

java.net.URLStreamHandler

java.net.URLStreamHandlerFactory

java.net.URLConnection

java.net.ContentHandler

java.net.ContentHandlerFactory

<<interface>>URLStream HandlerServ.

URLConnection subclass impl.

URL Stream Handler Proxy impl.

Content Handler Proxy impl.

Stream Handler implement.

Content Handler implement.

URL Stream Handler Fact. impl.

URL Content handler Fact. implement.

1

0,1

gets URLStreamHandlers

0..*

1

is tracked by

gets content via

1

0,1

1 0..*

is found in registry by (keyed by mim

e)

0..*

0,1

<<interface>>URLStream HandlerSetter

setURL

AbstractURLStreamHandlerServ.

creates connections of

from

is called by

0..* 1

OSGi Service Platform Release 4 255-268

Page 264: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Factories in java.net URL Handlers Service Specification Version 1.0

Bundles that can convert a content-typed stream should register a service object under the name java .net.ContentHandler . These objects should be made available by the OSGi Framework to the java.net .URLConnect ion class.

11.2 Factories in java.netJava provides the java.net.URL class which is used by the OSGi Framework and many of the bundles that run on the OSGi Service Platform. A key bene-fit of using the URL class is the ease with which a URL string is translated into a request for a resource.

The extensibility of the java.net.URL class allows new schemes (protocols) and content types to be added dynamically using java.net.URLStreamHandlerFactory objects. These new handlers allow existing applications to use new schemes and content types in the same way as the handlers provided by the Java run-time environment. This mecha-nism is described in the Javadoc for the URLStreamHandler and ContentHandler class, see [47] Java.

For example, the URL http ://www.osgi .org/sample .txt addresses a file on the OSGi web server that is obtained with the HTTP scheme (usually a scheme provided by the Java run-time). A URL such as rsh:/ /www.acme.com/agent .z ip is addressing a ZIP file that can be obtained with the non-built-in RSH scheme. A java.net.URLStreamHandlerFactory object must be registered with the java.net .URL class prior to the successful use of an RSH scheme.

There are several problems with using only the existing Java facilities for extending the handlers used by the java.net.URL class:

• Factories Are Singleton Operations – One java .net.URLStreamHandlerFactory object can be registered once with the java.net.URL class. Similarly, one java.net.ContentHandlerFactory object can be registered once with the java.net .URLConnect ion class. It is impossible to undo the registration of a factory or register a replacement factory.

• Caching Of Schemes – When a previously unused scheme is first used by the java.net.URL class, the java.net.URL class requests a java .net.URLStreamHandler object for that specific scheme from the currently registered java.net.URLStreamHandlerFactory object. A returned java.net.URLStreamHandler object is cached and subsequent requests for that scheme use the same java.net.URLStreamHandler object. This means that once a handler has been constructed for a specific scheme, this handler can no longer be removed, nor replaced, by a new handler for that scheme. This caching is likewise done for java .net.ContentHandler objects.

Both problems impact the OSGi operating model, which allows a bundle to go through different life cycle stages that involve exposing services, remov-ing services, updating code, replacing services provided by one bundle with services from another, etc. The existing Java mechanisms are not compati-ble when used by bundles.

256-268 OSGi Service Platform Release 4

Page 265: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 Framework Procedures

11.3 Framework ProceduresThe OSGi Framework must register a java.net .URLStreamHandlerFactory object and a java.net .ContentHandlerFactory object with the java.net .URL.setURLStreamHandlerFactory and java.net .URLConnect ion.setContentHandlerFactory methods, respec-tively.

When these two factories are registered, the OSGi Framework service regis-try must be tracked for the registration of URLStreamHandlerService ser-vices and java.net .ContentHandler services.

A URL Stream Handler Service must be associated with a service registra-tion property named URL_HANDLER_PROTOCOL . The value of this url .handler.protocol property must be an array of scheme names (String[]).

A Content Handler service must be associated with a service registration property named URL_CONTENT_MIMETYPE . The value of the URL_CONTENT_MIMETYPE property must be an array of MIME types names (String[]) in the form type/subtype. See [49] MIME Multipurpose Internet Mail Extension.

11.3.1 Constructing a Proxy and HandlerWhen a URL is used with a previously unused scheme, it must query the registered java .net.URLStreamHandlerFactory object (that should have been registered by the OSGi Framework). The OSGi Framework must then search the service registry for services that are registered under URLStreamHandlerService and that match the requested scheme.

If one or more service objects are found, a proxy object must be constructed. A proxy object is necessary because the service object that provides the implementation of the java.net.URLStreamHandler object can become unregistered and Java does not provide a mechanism to withdraw a java.net .URLStreamHandler object once it is returned from a java.net .URLStreamHandlerFactory object.

Once the proxy is created, it must track the service registry for registrations and unregistrations of services matching its associated scheme. The proxy must be associated with the service that matches the scheme and has the highest value for the org.osg i. f ramework.Constants.SERVICE_RANKING service registration property (see Service Properties on page 107) at any moment in time. If a proxy is associated with a URL Stream Handler Service, it must change the associated handler to a newly registered service when that service has a higher value for the ranking property.

The proxy object must forward all method requests to the associated URL Stream Handler Service until this service object becomes unregistered.

Once a proxy is created, it cannot be withdrawn because it is cached by the Java run-time. However, service objects can be withdrawn and it is possible for a proxy to exist without an associated URLStreamHandlerServ ice /java.net .ContentHandler object.

OSGi Service Platform Release 4 257-268

Page 266: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework Procedures URL Handlers Service Specification Version 1.0

In this case, the proxy must handle subsequent requests until another appropriate service is registered. When this happens, the proxy class must handle the error.

In the case of a URL Stream Handler proxy, it must throw a java.net.MalformedURLException exception if the signature of a method allows throwing this exception. Otherwise, a java. lang. I l legalStateExcept ion exception is thrown.

In the case of a Content Handler proxy, it must return InputStream to the data.

Bundles must ensure that their URLStreamHandlerService or java.net.ContentHandler service objects throw these exceptions also when they have become unregistered.

Proxies for Content Handler services operate slightly differently from URL Stream Handler Service proxies. In the case that nul l is returned from the registered ContentHandlerFactory object, the factory will not get another chance to provide a ContentHandler object for that content-type. Thus, if there is no built-in handler, nor a registered handler for this content-type, a ContentHandler proxy must be constructed that returns the InputStream object from the URLConnection object as the content object until a handler is registered.

11.3.2 Built-in HandlersImplementations of Java provide a number of sub-classes of java.net.URLStreamHandler classes that can handle protocols like HTTP, FTP, NEWS etc. Most Java implementations provide a mechanism to add new handlers that can be found on the class path through class name con-struction.

If a registered java.net.URLStreamHandlerFactory object returns nul l for a built-in handler (or one that is available through the class name construc-tion mechanism), it will never be called again for that specific scheme because the Java implementation will use its built-in handler or uses the class name construction.

It is thus not guaranteed that a registered URLStreamHandlerService object is used. Therefore, built-in handlers should take priority over handlers from the service registry to guarantee consistency. The built-in handlers, as defined in the OSGi execution environments must never be overridden.

The Content Handler Factory is implemented using a similar technique and has therefore the same problems.

To facilitate the discovery of built-in handlers that are available through the name construction, the method described in the next section must be used by the Framework before any handlers are searched for in the service regis-try.

258-268 OSGi Service Platform Release 4

Page 267: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 Framework Procedures

11.3.3 Finding Built-in HandlersIf the system properties java.protocol .handler.pkgs or java.content .handler .pkgs are defined, they must be used to locate built-in handlers. Each property must be defined as a list of package names that are separated by a vertical bar (’ | ’ , \u007C) and that are searched in the left-to-right order (the names must not end in a period). For example:

org.osgi.impl.handlers | com.acme.url

The package names are the prefixes that are put in front of a scheme or con-tent type to form a class name that can handle the scheme or content-type.

A URL Stream Handler name for a scheme is formed by appending the string " .Handler " to the scheme name. Using the packages in the previous exam-ple, the rsh scheme handler class is searched by the following names:

org.osgi.impl.handlers.rsh.Handlercom.acme.url.rsh.Handler

MIME type names contain the ’/’ character and can contain other characters that must not be part of a Java class name. A MIME type name must be pro-cessed as follows before it can be converted to a class name:

1. First, all slashes in the MIME name must be converted to a period (’ . ’ \u002E). All other characters that are not allowed in a Java class name must be converted to an underscore (’_ ’ or \u005F).

application/zip application.ziptext/uri-list text.uri_listimage/vnd.dwg image.vnd_dwg

2. After this conversion, the name is appended to the list of packages speci-fied in java.content.handler.pkgs . For example, if the content type is appl icat ion/z ip , and the packages are defined as in the previous example, then the following classes are searched:

org.osgi.impl.handlers.application.zipcom.acme.url.application.zip

The Java run-time specific packages should be listed in the appropriate properties so that implementations of the URL Stream Handler Factory and Content Handler Factory can be made aware of these packages.

11.3.4 Protected Methods and Proxy Implementations of java .net.URLStreamHandler class cannot be registered in the service registry for use by the proxy because the methods of the URLStreamHandler class are protected and thus not available to the proxy implementation. Also, the URLStreamHandler class checks that only the URLStreamHandler object that was returned from the URLStreamHandlerFactory object can invoke the setURL method. This means that URLStreamHandler objects in the service registry would be unable to invoke the setURL method. Invoking this method is necessary when implementing the parseURL method.

OSGi Service Platform Release 4 259-268

Page 268: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Framework Procedures URL Handlers Service Specification Version 1.0

Therefore, the URLStreamHandlerService and URLStreamHandlerSetter interfaces were created. The URLStreamHandlerService interface provides public versions of the URLStreamHandler methods, except that the setURL method is missing and the parseURL method has a new first argument of type URLStreamHandlerSetter . In general, sub-classes of the URLStreamHandler class can be converted to URLStreamHandlerService classes with minimal code changes. Apart from making the relevant meth-ods public, the parseURL method needs to be changed to invoke the setURL method on the URLStreamHandlerSetter object that the URLStreamHandlerService object was passed, rather then the setURL method of URLStreamHandler class.

Figure 54 Proxy Issues

To aid in the conversion of URLStreamHandler implementation classes, the AbstractURLStreamHandlerService has been provided. Apart from making the relevant methods public, the AbstractURLStreamHandlerService stores the URLStreamHandlerSetter object in a private variable. To make the setURL method work properly, it overrides the setURL method to invoke the setURL method on the saved URLStreamHandlerSetter object rather then the URLStreamHandler .setURL method. This means that a subclass of URLStreamHandler should be changed to become a sub-class of the AbstractURLStreamHandlerService class and be recompiled.

Normally, the parseURL method will have the following form:

class URLStreamHandlerImpl {...protected URLStreamHandlerSetter realHandler;... public void parseURL(

URLStreamHandlerSetter realHandler, URL u, String spec, int start, int limit) {

this.realHandler = realHandler;parseURL(u, spec, start, limit);

}protected void setURL(URL u,

String protocol, String host,int port, String authority,String userInfo, String path,String query,String ref) {

<<<interface>>URLStream HandlerServic

forward all methodsProxy Impl, the actual URL-Stream Handler.

URLStreamHandler Impl.

java.net.URLStreamHandler

<<interface>>URLStreamHandlerSetter

setURL is called by

called byJava

260-268 OSGi Service Platform Release 4

Page 269: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 Providing a New Scheme

realHandler.setURL(u, protocol, host, port, authority, userInfo, path,query, ref);

}...

}

The URLStreamHandler.parseURL method will call the setURL method which must be invoked on the proxy rather than this . That is why the setURL method is overridden to delegate to the URLStreamHandlerSetter object in realHandler as opposed to super .

11.4 Providing a New SchemeThe following example provides a scheme that returns the path part of the URL. The first class that is implemented is the URLStreamHandlerService . When it is started, it registers itself with the OSGi Framework. The OSGi Framework calls the openConnection method when a new java.net .URLConnect ion must be created. In this example, a DataConnect ion object is returned.

public class DataProtocol extends AbstractURLStreamHandlerService implements BundleActivator {public void start( BundleContext context ) {

Hashtable properties = new Hashtable();properties.put( URLConstants.URL_HANDLER_PROTOCOL,

new String[] { "data" } );context.registerService(

URLStreamHandlerService.class.getName(), this, properties );

}public void stop( BundleContext context ) {}

public URLConnection openConnection( URL url ) {return new DataConnection(url);

}}

The following example DataConnect ion class extends java.net .URLConnect ion and overrides the constructor so that it can pro-vide the URL object to the super class, the connect method, and the get InputStream method. This last method returns the path part of the URL as an java . io . InputStream object.

class DataConnection extends java.net.URLConnection {DataConnection( URL url ) {super(url);}public void connect() {}

public InputStream getInputStream() throws IOException {String s = getURL().getPath();byte [] buf = s.getBytes();return new ByteArrayInputStream(buf,1,buf.length-1);

OSGi Service Platform Release 4 261-268

Page 270: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

Providing a Content Handler URL Handlers Service Specification Version 1.0

}public String getContentType() {

return "text/plain";}

}

11.5 Providing a Content HandlerA Content Handler should extend the java .net.ContentHandler class and implement the getContent method. This method must get the InputStream object from the java .net.URLConnection parameter object and convert the bytes from this stream to the applicable type. In this example, the MIME type is text/pla in and the return object is a String object.

public class TextPlainHandler extends ContentHandler implements BundleActivator {

public void start( BundleContext context ) {Hashtableproperties = new Hashtable();properties.put( URLConstants.URL_CONTENT_MIMETYPE,

new String[] { "text/plain" } );context.registerService(

ContentHandler.class.getName(), this, properties );

}public void stop( BundleContext context ) {}

public Object getContent( URLConnection conn ) throws IOException {

InputStream in = conn.getInputStream();InputStreamReader r = new InputStreamReader( in );StringBuffer sb = new StringBuffer();int c;while ( (c=r.read()) >= 0 )

sb.append( (char) c );r.close(); in.close();return sb.toString();

}}

11.6 Security ConsiderationsThe ability to specify a protocol and add content handlers makes it possible to directly affect the behavior of a core Java VM class. The java.net.URL class is widely used by network applications and can be used by the OSGi Frame-work itself.

Therefore, care must be taken when providing the ability to register han-dlers. The two types of supported handlers are URLStreamHandlerService and java.net .ContentHandler . Only trusted bundles should be allowed to register these services and have

262-268 OSGi Service Platform Release 4

Page 271: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 org.osgi.service.url

ServicePermission[URLStreamHandlerService |ContentHandler, REGISTER] for these classes. Since these services are made available to other bundles through the java .net.URL class and java.net.URLConnection class, it is advisable to deny the use of these services (ServicePermiss ion[<name>, GET]) to all, so that only the Framework can get them. This prevents the cir-cumvention of the permission checks done by the java.net.URL class by using the URLStreamHandlerServices service objects directly.

11.7 org.osgi.service.urlThe OSGi URL Stream and Content Handlers API Package. Specification Version 1.0.

Bundles wishing to use this package must list the package in the Import-Package header of the bundle’s manifest. For example:

Import-Package: org.osgi.service.url; version=1.0

11.7.1 Summary• AbstractURLStreamHandlerService - Abstract implementation of the

URLStreamHandlerService interface. [p.263]• URLConstants - Defines standard names for property keys associated

with URLStreamHandlerServ ice [p.265] and java.net.ContentHandler ser-vices. [p.264]

• URLStreamHandlerService - Service interface with public versions of the protected java.net.URLStreamHandler methods. [p.265]

• URLStreamHandlerSetter - Interface used by URLStreamHandlerService objects to call the setURL method on the proxy URLStreamHandler object. [p.266]

AbstractURLStreamHandlerService

11.7.2 public abstract class AbstractURLStreamHandlerServiceextends URLStreamHandlerimplements URLStreamHandlerServiceAbstract implementation of the URLStreamHandlerService interface. All the methods simply invoke the corresponding methods on java.net.URL-StreamHandler except for parseURL and setURL, which use the URLStream-HandlerSetter parameter. Subclasses of this abstract class should not need to override the setURL and parseURL(URLStreamHandlerSetter,...) methods. realHandler

11.7.2.1 protected URLStreamHandlerSetter realHandler

The URLStreamHandlerSetter object passed to the parseURL method. AbstractURLStreamHandlerService()

11.7.2.2 public AbstractURLStreamHandlerService( ) equals(URL,URL)

11.7.2.3 public boolean equals( URL u1, URL u2 )

This method calls super.equals(URL,URL).

See Also java.net.URLStreamHandler.equals(URL,URL)getDefaultPort()

11.7.2.4 public int getDefaultPort( )

This method calls super.getDefaultPort.

OSGi Service Platform Release 4 263-268

Page 272: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

org.osgi.service.url URL Handlers Service Specification Version 1.0

See Also java.net.URLStreamHandler.getDefaultPortgetHostAddress(URL)

11.7.2.5 public InetAddress getHostAddress( URL u )

This method calls super.getHostAddress.

See Also java.net.URLStreamHandler.getHostAddresshashCode(URL)

11.7.2.6 public int hashCode( URL u )

This method calls super.hashCode(URL).

See Also java.net.URLStreamHandler.hashCode(URL)hostsEqual(URL,URL)

11.7.2.7 public boolean hostsEqual( URL u1, URL u2 )

This method calls super.hostsEqual.

See Also java.net.URLStreamHandler.hostsEqualopenConnection(URL)

11.7.2.8 public abstract URLConnection openConnection( URL u ) throws IOException

See Also java.net.URLStreamHandler.openConnectionparseURL(URLStreamHandlerSetter,URL,String,int,int)

11.7.2.9 public void parseURL( URLStreamHandlerSetter realHandler, URL u, String spec, int start, int limit )

realHandler The object on which the setURL method must be invoked for the specified URL.

Parse a URL using the URLStreamHandlerSetter object. This method sets the realHandler field with the specified URLStreamHandlerSetter object and then calls parseURL(URL,String,int,int).

See Also java.net.URLStreamHandler.parseURLsameFile(URL,URL)

11.7.2.10 public boolean sameFile( URL u1, URL u2 )

This method calls super.sameFile.

See Also java.net.URLStreamHandler.sameFilesetURL(URL,String,String,int,String,String)

11.7.2.11 protected void setURL( URL u, String proto, String host, int port, String file, String ref )

This method calls realHandler.setURL(URL,String,String,int,String,String).

See Also java.net.URLStreamHandler.setURL(URL,String,String,int,String,String)

Deprecated This method is only for compatibility with handlers written for JDK 1.1.setURL(URL,String,String,int,String,String,String,String,String)

11.7.2.12 protected void setURL( URL u, String proto, String host, int port, String auth, String user, String path, String query, String ref )

This method calls realHandler.setURL(URL,String,String,int,String,String,String,String).

See Also java.net.URLStreamHandler.setURL(URL,String,String,int,String,String,String,String)toExternalForm(URL)

11.7.2.13 public String toExternalForm( URL u )

This method calls super.toExternalForm.

See Also java.net.URLStreamHandler.toExternalFormURLConstants

264-268 OSGi Service Platform Release 4

Page 273: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

URL Handlers Service Specification Version 1.0 org.osgi.service.url

11.7.3 public interface URLConstantsDefines standard names for property keys associated with URLStreamHandlerService[p.265] and java.net.ContentHandler services.

The values associated with these keys are of type java.lang.String[], unless otherwise indicated.URL_CONTENT_MIMETYPE

11.7.3.1 public static final String URL_CONTENT_MIMETYPE = “url.content.mimetype”

Service property naming the MIME types serviced by a java.net.Con-tentHandler. The property’s value is an array of MIME types. URL_HANDLER_PROTOCOL

11.7.3.2 public static final String URL_HANDLER_PROTOCOL = “url.handler.protocol”

Service property naming the protocols serviced by a URLStreamHandlerSer-vice. The property’s value is an array of protocol names. URLStreamHandlerService

11.7.4 public interface URLStreamHandlerServiceService interface with public versions of the protected java.net.URLStream-Handler methods.

The important differences between this interface and the URLStreamHan-dler class are that the setURL method is absent and the parseURL method takes a URLStreamHandlerSetter [p.266] object as the first argument. Classes implementing this interface must call the setURL method on the URL-StreamHandlerSetter object received in the parseURL method instead of URLStreamHandler.setURL to avoid a SecurityException.

See Also AbstractURLStreamHandlerService[p.263]equals(URL,URL)

11.7.4.1 public boolean equals( URL u1, URL u2 )

See Also java.net.URLStreamHandler.equals(URL, URL)getDefaultPort()

11.7.4.2 public int getDefaultPort( )

See Also java.net.URLStreamHandler.getDefaultPortgetHostAddress(URL)

11.7.4.3 public InetAddress getHostAddress( URL u )

See Also java.net.URLStreamHandler.getHostAddresshashCode(URL)

11.7.4.4 public int hashCode( URL u )

See Also java.net.URLStreamHandler.hashCode(URL)hostsEqual(URL,URL)

11.7.4.5 public boolean hostsEqual( URL u1, URL u2 )

See Also java.net.URLStreamHandler.hostsEqualopenConnection(URL)

11.7.4.6 public URLConnection openConnection( URL u ) throws IOException

See Also java.net.URLStreamHandler.openConnectionparseURL(URLStreamHandlerSetter,URL,String,int,int)

11.7.4.7 public void parseURL( URLStreamHandlerSetter realHandler, URL u, String spec, int start, int limit )

realHandler The object on which setURL must be invoked for this URL.

OSGi Service Platform Release 4 265-268

Page 274: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

References URL Handlers Service Specification Version 1.0

Parse a URL. This method is called by the URLStreamHandler proxy, instead of java.net.URLStreamHandler.parseURL, passing a URLStreamHandlerSet-ter object.

See Also java.net.URLStreamHandler.parseURLsameFile(URL,URL)

11.7.4.8 public boolean sameFile( URL u1, URL u2 )

See Also java.net.URLStreamHandler.sameFiletoExternalForm(URL)

11.7.4.9 public String toExternalForm( URL u )

See Also java.net.URLStreamHandler.toExternalFormURLStreamHandlerSetter

11.7.5 public interface URLStreamHandlerSetterInterface used by URLStreamHandlerService objects to call the setURL method on the proxy URLStreamHandler object.

Objects of this type are passed to the URLStreamHandlerService .parseURL [p.265] method. Invoking the setURL method on the URLStreamHandlerSetter object will invoke the setURL method on the proxy URLStreamHandler object that is actually registered with java.net.URL for the protocol.setURL(URL,String,String,int,String,String)

11.7.5.1 public void setURL( URL u, String protocol, String host, int port, String file, String ref )

See Also java.net.URLStreamHandler.setURL(URL,String,String,int,String,String)

Deprecated This method is only for compatibility with handlers written for JDK 1.1.setURL(URL,String,String,int,String,String,String,String,String)

11.7.5.2 public void setURL( URL u, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref )

See Also java.net.URLStreamHandler.setURL(URL,String,String,int,String,String,String,String)

11.8 References[47] Java

http://java.sun.com/j2se/1.4/docs/api/java/net/package-summary.html

[48] URLshttp://www.ietf.org/rfc/rfc1738.txt

[49] MIME Multipurpose Internet Mail Extensionhttp://www.nacs.uci.edu/indiv/ehood/MIME/MIME.html

[50] Assigned MIME Media Typeshttp://www.iana.org/assignments/media-types

266-268 OSGi Service Platform Release 4

Page 275: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

OSGi Service Platform Release 4 267-268

Page 276: OSGi Service Platform Core Specificationsmarthome.cs.iastate.edu/documents/Manuals and Tutorials/OSGi/OS… · OSGi Service Platform Release 4 ii-268 OSGi Member Companies Alpine

268-268 OSGi Service Platform Release 4

End Of Document