Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

OSGI overview


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

OSGI overview

  1. 1. OSGi, Apache Felix and JNI introductionName/Dept.: Lawrence HoDate: 2012.10.19
  2. 2. 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?
  3. 3. What Is OSGi?• The simplest answer to this question is that it’s a modularity layer for the Java platform.
  4. 4. The Functional Layers• The components in the OSGi framework are grouped into distinct functional layers. 1. The execution environment layer 2. The module layer 3. The lifecycle layer 4. The service layer 5. The security layer
  5. 5. The Execution Environment Layer• It is the bottom layer on which the bundles live, is selected to fit the underlying hardware or operating system.
  6. 6. 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.
  7. 7. What Is Modularity?• Designing a complete system from a set of logically independent pieces.• These logically independent pieces are called modules.
  8. 8. 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.
  9. 9. 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.
  10. 10. 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.
  11. 11. The bundle’s role in modularity
  12. 12. 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
  13. 13. 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.
  14. 14. Bundle Dependencies(3)
  15. 15. Bundle Dependencies(4)
  16. 16. 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.
  17. 17. Modular and nonmodularversions of the paint program
  18. 18. 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.
  19. 19. 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.
  20. 20. The Bundle Lifecycle States(2)
  21. 21. 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.
  22. 22. What’s Service Layer?(2)• Bundles can register services, search for them, or receive notifications when their registration state changes Service Registry Publish Find Service Description Service Service Provider Requester Bind
  23. 23. 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.
  24. 24. Essentials of Service Layer• Essentials: – Collaborative – Dynamic – Secure – Reflective – Versioning – Persistent Identifier
  25. 25. Entities of Service Layer• Entities: – Service – Service Registry – Service Reference – Service Registration – Service Permission – Service Factory – Service Listener – Service Event – Filter – Invalid Syntax Exception
  26. 26. 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.
  27. 27. 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.
  28. 28. 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.
  29. 29. 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.
  30. 30. Registering Services(3)• registerService(String,Object,Dictionary)– 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
  31. 31. 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)
  32. 32. Service Layer Implement(1)• A bundle is named “”, and to write an interface (Service) named ” SimpleShape”: public interface SimpleShape { public static final String NAME_PROPERTY = ""; 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.
  33. 33. 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); Need import } public void stop(BundleContext context) { bundle first } 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(; g2.setStroke(wideStroke); g2.draw(new Ellipse2D.Double(x, y, 50, 50)); } }}
  34. 34. Service Layer Implement(3)
  35. 35. 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); }}
  36. 36. 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()); }}
  37. 37. Listening for services• REGISTERED• MODIFIED• UNREGISTERING
  38. 38. Service Event LogBundle re-started and registered a serviceBundle stopped, uninstalled and unregistered serviceBundle started and registered service
  39. 39. 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.
  40. 40. 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.
  41. 41. 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.
  42. 42. The Security Layer• It extends the Java 2 security architecture, is optional. When active, it validates bundle signatures, and controls component access rights.
  43. 43. Some of The Interaction Between The Layers of The Framework
  44. 44. OSGi Implementations• Open Source Implementations – Apache Felix – Eclipse Equinox – Knopflerfish – Spring DM• Commercial Implementations – ProSyst • Knopflerfish Pro
  45. 45. 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.
  46. 46. What Is Apache Felix Framework?(2)1. Log Service2. Http Service3. Configuration Admin Service4. Metatype service5. Preferences service6. Service Component Runtime7. Event Admin Service8. UPnP Device service
  47. 47. What Is Apache Felix Framework?(3)• Dependency Manager• File Install• Gogo• Maven Bundle Plugin• OSGi Bundle Repository Service• Shell Service• Web Console Service
  48. 48. 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: .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
  49. 49. Setting up the Felix Framework(2)
  50. 50. Setting up the Felix Framework(3)
  51. 51. Setting up the Felix Framework(4)
  52. 52. 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.
  53. 53. 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 implementations javah 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
  54. 54. 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(); }
  55. 55. 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 – Step 2: javah Joystick
  56. 56. 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"); }
  57. 57. Building the Native Interface Library(2)• 2. On the Windows platform, installing MinGW(, and following instruction.• 3. Execute the following command to compile joystick.c into joystick.o: gcc -g - I/System/Library/Frameworks/JavaVM.framew ork/Headers -c -o joystick.o joystick.c
  58. 58. 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!!