OSGI overview

Preview:

Citation preview

OSGi, Apache Felix and JNI introduction

Name/Dept.: Lawrence HoDate: 2012.10.19

Outline• What Is OSGi?• An Architectural Overview of OSGi• What Is Modularity?• An Overview of Bundle• An Overview of Apache Felix Framework• What Is JNI?• How to Bundle Native Libraries?

What Is OSGi?• The simplest answer to this question is

that it’s a modularity layer for the Java platform.

The Functional Layers• The components in the OSGi framework

are grouped into distinct functional layers.1. The execution environment layer2. The module layer3. The lifecycle layer4. The service layer5. The security layer

The Execution Environment Layer

• It is the bottom layer on which the bundles live, is selected to fit the underlying hardware or operating system.

The Module Layer• The Module Layer defines a modularization

model for Java. • It’s the bundle space, holds the bundles

that are installed on the framework and are managed through the lifecycle layer.

What Is Modularity?• Designing a complete system from a set of

logically independent pieces.• These logically independent pieces are

called modules.

What Is Bundle?• 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.

What Are in a Bundle?• The main thing that

makes a bundle JAR file different than a normal JAR file is its module metadata, which is used by the OSGi framework to manage its modularity characteristics.

• In the META-INF/MANIFEST.MF entry of the JAR file is where OSGi places its module meta-data.

Is a bundle a JAR file or a JAR file a bundle?

• What about using a standard JAR file as a bundle?– It doesn’t do anything useful.

• What about bundle JAR files? can they be used as a standard JAR file outside of an OSGi environment?– It depends.

The bundle’s role in modularity

Bundle Dependencies(1)• What is a dependency? It is a set of

assumptions made by a program or block of code about the environment in which it will run.– Explicit – Declarative– Versioned

Bundle Dependencies(2)• Bundle A’s class space is defined as the

union of its bundle class path with its imported packages, which are provided by bundle B’s exports.

Bundle Dependencies(3)

Bundle Dependencies(4)

Bundle Dependencies(5)• Issues with bundle dependencies

1. Using Import-Package and Export-Package is the preferred way to share code because they couple the importer and exporter to a lesser degree.

2. Using Require-Bundle entails much higher coupling and lower cohesion between the importer and the exporter.

Modular and nonmodular versions of the paint program

The Lifecycle Layer• The OSGi lifecycle layer provides a

management API and a well-defined lifecycle for bundles at execution time in the OSGi framework.

The Bundle Lifecycle States(1)• INSTALLE--The bundle has been successfully

installed.• RESOLVED--This state indicates that the bundle

is either ready to be started or has stopped.• STARTING--The bundle is being started.• ACTIVE--The bundle has been successfully

activated and is running.• STOPPING--The bundle is being stopped. • UNINSTALLED--The bundle has been

uninstalled.

The Bundle Lifecycle States(2)

What’s Service Layer?(1)• The 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.

What’s Service Layer?(2)• Bundles can register services, search for

them, or receive notifications when their registration state changes

Service Registry

Service Description

Service Provider

Service Requester

Publish Find

Bind

Publish-Find-Bind model • A providing bundle can publish Plain Old Java

Objects (POJOs) as services. • A consuming bundle can find and then bind to

services.

Essentials of Service Layer• Essentials:– Collaborative– Dynamic– Secure– Reflective– Versioning– Persistent Identifier

Entities of Service Layer• Entities:– Service– Service Registry– Service Reference– Service Registration– Service Permission– Service Factory– Service Listener– Service Event– Filter– Invalid Syntax Exception

Service References

• Registered services are referenced through ServiceReference 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.

Service Interfaces• A service interface is the specification of

the service’s public methods.• Many service interfaces are defined and

specified by organizations such as the OSGi Alliance.

• It has been accepted as a standard can be implemented and used by any number of bundle developers.

Registering Services(1)• A 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.

Registering Services(2)• The Framework permits bundles to register

and unregister service objects dynamically. • 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.registerService methods on its BundleContext object.

Registering Services(3)• registerService(String,Object,Dictiona

ry)– Under a single service interface.• registerService(String

[],Object,Dictionary)– Under multiple service interfaces.

• Parameters:– String: The name of Service– Object: Service Object Entity– Dictionary: Contains the properties of the

service as a collection of key/value pairs

Service Factory• A Service Factory allows customization of

the service object that is returned when a bundle calls BundleContext.getService(ServiceReference)

• The ServiceFactory interface defines the following methods:– getService(Bundle,ServiceRegistration)– ungetService(Bundle,ServiceRegistration,

Object)

Service Layer Implement(1)• A bundle is named “org.apache.felix.example.servicebased.host”, and to

write an interface (Service) named ” SimpleShape”:public interface SimpleShape {

public static final String NAME_PROPERTY = "simple.shape.name";public static final String ICON_PROPERTY = "simple.shape.icon";public void draw(Graphics2D g2, Point p);

}If I need use this service(interface) in other bundle, I must export packages in bundle configuration.

Service Layer Implement(2)• Build another bundle is named “Circle”, this bundle will implement SimpleShape:public class Activator implements BundleActivator {

private BundleContext m_context = null;public void start(BundleContext context) {

m_context = context;Dictionary<String, Object> dict = new Hashtable<String, Object>();dict.put(SimpleShape.NAME_PROPERTY, "Circle");dict.put(SimpleShape.ICON_PROPERTY, new ImageIcon(this.getClass().getResource("circle.png")));m_context.registerService(SimpleShape.class.getName(), new Circle(), dict);

}public void stop(BundleContext context) {}public class Circle implements SimpleShape {

public void draw(Graphics2D g2, Point p) {int x = p.x - 25;int y = p.y - 25;GradientPaint gradient = new GradientPaint(x, y, Color.RED, x + 50, y, Color.WHITE);g2.setPaint(gradient);g2.fill(new Ellipse2D.Double(x, y, 50, 50));BasicStroke wideStroke = new BasicStroke(2.0f);g2.setColor(Color.black);g2.setStroke(wideStroke);g2.draw(new Ellipse2D.Double(x, y, 50, 50));}

}}

Need import org.apache.felix.example.servicebased.host bundle first

Service Layer Implement(3)

Service Layer Implement(4)• When a bundle wishes to use the service, it can be obtained by

passing the ServiceReference object to BundleContext.getService (ServiceReference).

public class HelloWorldActivator implements BundleActivator {public void start(BundleContext context) throws Exception {

ServiceReference helloServiceReference = context.getServiceReference(HelloService.class.getName());

HelloService helloService = (HelloService)context.getService(helloServiceReference);System.out.println(helloService.sayHello());

}public void stop(BundleContext context) throws Exception {

context.ungetService(helloServiceReference);}

}

Service Layer Implement(5)public class HelloServiceFactory implements ServiceFactory {

public Object getService(Bundle bundle, ServiceRegistration registration) {

System.out.println(“Create object of HelloService for " +bundle.getSymbolicName());/*當 bundle要求此服務,工廠會 new一個實體給他 */HelloService helloService = new HelloServiceImpl();return helloService;

}public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {

System.out.println(“Release object of HelloService for “ +bundle.getSymbolicName());

}}

Listening for services• REGISTERED• MODIFIED• UNREGISTERING

Service Event LogBundle re-started and registered a service

Bundle stopped, uninstalled and unregistered service

Bundle started and registered service

Summary of Service(1)• A service is “work done for another.” • Service contracts define responsibilities

and match consumers with providers. • Services encourage a relaxed,

pluggable, interface-based approach to programming.

• You don’t need to care where a service comes from as long as it meets the contract.

Summary of Service(2)• The best place to use services is

between replaceable components. • Think carefully before using services in

tightly coupled or high-performance code.

• Services can replace the listener pattern with a much simpler whiteboard pattern.

• OSGi services use a publish-find-bind model.

Summary of Service(3)• OSGi services are truly dynamic and can

appear or disappear at any time. • The easiest and safest approach is to

use the OSGi ServiceTracker utility class. • OSGi services build on and interact with

the previous module and lifecycle layers. • OSGi defines core framework services

and additional compendium services.

The Security Layer• It extends the Java 2 security architecture,

is optional. When active, it validates bundle signatures, and controls component access rights.

Some of The Interaction Between The Layers of The Framework

OSGi Implementations• Open Source Implementations– Apache Felix– Eclipse Equinox– Knopflerfish– Spring DM

• Commercial Implementations– ProSyst• Knopflerfish Pro

What Is Apache Felix Framework?(1)

• Apache Felix is an open-source community effort to implement the OSGi Service Platform Release 4 Core specification under the Apache license.

What Is Apache Felix Framework?(2)

1. Log Service 2. Http Service3. Configuration Admin Service4. Metatype service5. Preferences service6. Service Component Runtime 7. Event Admin Service 8. UPnP Device service

What Is Apache Felix Framework?(3)

• Dependency Manager• File Install• Gogo• Maven Bundle Plugin• OSGi Bundle Repository Service• Shell Service• Web Console Service

Setting up the Felix Framework(1)• Checking that a JDK is installed• Download and unpack the Felix distribution

1. Go to the downloads section of the Apache Felix website:http://felix.apache.org/site/downloads.cgi

2. Download the Felix Framework Distribution to a temporary location.

3. Unzip the downloaded archive to a location of your choice.

• starting Felix:java -jar bin/felix.jar

Setting up the Felix Framework(2)

Setting up the Felix Framework(3)

Setting up the Felix Framework(4)

What Is JNI?• The Java Native Interface (JNI) is a native

programming interface that lets Java code running in a JVM interoperate with native libraries written in other languages (e.g., C, C++, or even assembly language).

• It is a bridge between the JVM and the platform.

How to Bundle Native Libraries?(1)• Java Native Interface (JNI)– Using the native method modifier

static native int joyGetNumDevs(); – The javah command is used to generate C

header and stub files, which are used to create the native method implementationsjavah Joystick

– The native code is compiled into a library– Includes code to invoke System. loadLibrary()– Invoke the native method as if it were a normal

method

How to Bundle Native Libraries?(2)• A simple Java example:

class Joystick { static boolean init() { try { System.loadLibrary("joystick"); return true; } catch (UnsatisfiedLinkError ule) { return false; } } public static void main(String[] args){ if (!Joystick.init()){ System.err.println("unable to load joystick library"); return; }else{ Joystick.joyGetNumDevs(); } } static native int joyGetNumDevs();}

How to Bundle Native Libraries?(3)

• use javah tool to generate the header file with a function prototype for the joyGetNumDevs method automatically: – Step 1: javac Joystick.java– Step 2: javah Joystick

Building the Native Interface Library(1)

1. Writing a simple C code:#include <stdio.h>#include "Joystick.h"JNIEXPORT jint JNICALL Java_Joystick_joyGetNumDevs(JNIEnv *pEnv, jclass clazz) { printf("Hello Lawrence!! \n");}

Building the Native Interface Library(2)

• 2. On the Windows platform, installing MinGW(http://www.mingw.org/), and following instruction.

• 3. Execute the following command to compile joystick.c into joystick.o:gcc -g -I/System/Library/Frameworks/JavaVM.framework/Headers -c -o joystick.o joystick.c

Building the Native Interface Library(3)

• 4. Execute the following command to create native library:gcc -dynamiclib -o libjoystick.jnilib joystick.o -framework JavaVM

• 5.Excute the Java file:java Joystick

• When the program is run, the following output is displayed:Hello Lawrence!!

Recommended