osgi overview

58
OSGi, Apache Felix and JNI introduction Name/Dept.: Lawrence Ho Date: 2012.10.19

Upload: laurence-ho

Post on 08-Apr-2017

417 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: OSGI overview

OSGi, Apache Felix and JNI introduction

Name/Dept.: Lawrence HoDate: 2012.10.19

Page 2: OSGI overview

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?

Page 3: OSGI overview

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

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

Page 4: OSGI overview

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

Page 5: OSGI overview

The Execution Environment Layer

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

Page 6: OSGI overview

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.

Page 7: OSGI overview

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

logically independent pieces.• These logically independent pieces are

called modules.

Page 8: OSGI overview

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.

Page 9: OSGI overview

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.

Page 10: OSGI overview

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.

Page 11: OSGI overview

The bundle’s role in modularity

Page 12: OSGI overview

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

Page 13: OSGI overview

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.

Page 14: OSGI overview

Bundle Dependencies(3)

Page 15: OSGI overview

Bundle Dependencies(4)

Page 16: OSGI overview

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.

Page 17: OSGI overview

Modular and nonmodular versions of the paint program

Page 18: OSGI overview

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.

Page 19: OSGI overview

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.

Page 20: OSGI overview

The Bundle Lifecycle States(2)

Page 21: OSGI overview

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.

Page 22: OSGI overview

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

Page 23: OSGI overview

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.

Page 24: OSGI overview

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

Page 25: OSGI overview

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

Page 26: OSGI overview

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.

Page 27: OSGI overview

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.

Page 28: OSGI overview

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.

Page 29: OSGI overview

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.

Page 30: OSGI overview

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

Page 31: OSGI overview

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)

Page 32: OSGI overview

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.

Page 33: OSGI overview

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

Page 34: OSGI overview

Service Layer Implement(3)

Page 35: OSGI overview

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);}

}

Page 36: OSGI overview

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());

}}

Page 37: OSGI overview

Listening for services• REGISTERED• MODIFIED• UNREGISTERING

Page 38: OSGI overview

Service Event LogBundle re-started and registered a service

Bundle stopped, uninstalled and unregistered service

Bundle started and registered service

Page 39: OSGI overview

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.

Page 40: OSGI overview

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.

Page 41: OSGI overview

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.

Page 42: OSGI overview

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

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

Page 43: OSGI overview

Some of The Interaction Between The Layers of The Framework

Page 44: OSGI overview

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

• Commercial Implementations– ProSyst• Knopflerfish Pro

Page 45: OSGI overview

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.

Page 46: OSGI overview

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

Page 47: OSGI overview

What Is Apache Felix Framework?(3)

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

Page 48: OSGI overview

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

Page 49: OSGI overview

Setting up the Felix Framework(2)

Page 50: OSGI overview

Setting up the Felix Framework(3)

Page 51: OSGI overview

Setting up the Felix Framework(4)

Page 52: OSGI overview

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.

Page 53: OSGI overview

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

Page 54: OSGI overview

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();}

Page 55: OSGI overview

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

Page 56: OSGI overview

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");}

Page 57: OSGI overview

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

Page 58: OSGI overview

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!!