P. 1
JTJ-2011-04

JTJ-2011-04

|Views: 1,318|Likes:
Published by AnilKumar Bpl

More info:

Published by: AnilKumar Bpl on Jun 17, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

09/08/2011

pdf

text

original

Sections

  • A Gentle Introduction to OSGi
  • Developing OSGi with BndTools
  • Tutorial: Using JPA in an OSGi environment
  • OSGi and JPA
  • The Cure for Complexity
  • The Enterprise OSGi Specifcation

Issue May 2011 | presented by

www.jaxenter.com
TM

In this issue of Java Tech Journal, we take a closer look at the OSGi dynamic module system for Java, with articles that address the controversial topic of OSGi's place in

enterprise development, a deep dive into the Core 4.3 specification, and a tour through some OSGi projects you may not have heard of.

OSGi
A Gentle Introduction to OSGi
The Perfect Starter

#8

OSGi Update: What’s New in Core 4.3?
OSGi Alliance's Latest Update

Developing OSGi with BndTools
Combining the power of Eclipse and Bnd

OSGi A La Carte
Bundles, Bnd, PAX, Maven and more

OSGi and JPA
Tutorial: using JPA in an OSGi environment

The Cure for Complexity
OSGi and the Enterprise?

The Enterprise OSGi Specification
Using OSGi in the Enterprise

Editorial

OSGi in the Java ecosystem
OSGi has been a solid part of the Java ecosystem for years, but it’s still a much-talked about technology, with the OSGi Alliance releasing the Core 4.3 speci cation just last month, and a host of new OSGi projects such as Libra in the Eclipse ecosystem, and the Pojo Service Registry project (which has been referred to as “OSGi-lite”) ensuring OSGi remains in the spotlight. The OSGi framework was introduced as a module system and service platform, as part of an attempt to standardise module deployments for Java. Frameworks that implement the OSGi standard achieve application lifecycle management via APIs, and components and applications can be remotely installed, started, updated, stopped and uninstalled without rebooting. Originally focusing on service gateways (the OSGi Alliance’s original moniker was the Open Services Gateway initiative) the OSGi speci cations have increasingly pushed the technology into new areas, as seen in the formation of the OSGi Alliance’s Mobile Expert Group in October 2003, and the Enterprise Expert Group, which addresses Enterprise/ Server-side applications. Despite many successes (not least when Eclipse settled on OSGi for the underlying runtime of the plugin architecture used for the Eclipse RCP and IDE platform) two questions have dogged OSGi throughout: is OSGi too complex, and is it ready for the enterprise? Some argue that instead of simplifying server application development, OSGi has actually made it more complex, and the readiness of OSGi for enterprise applications has been another area of contention. Those who see a place for OSGi in the enterprise point to examples of vendors such as IBM building OSGi into their products, while those who believe OSGi isn’t ready for the enterprise, use examples such as SpringSource donating dm Server to the Eclipse foundation, as proof that OSGi-based technologies don’t always enjoy a healthy adoption rate in an enterprise environment. Despite these two on-going debates, currently, a complete and dynamic component model does not exist in standalone Java environments - meaning that OSGi is in no danger of losing its spot in the Java ecosystem anytime soon. In this issue of Java Tech Journal, we deep dive into OSGi, with two articles that examine the controversial issue of OSGi’s place in the enterprise, a look at the latest OSGi speci cation, a tour through some OSGi projects you may not have heard of, and lots more OSGi-related goodness. Happy reading! Jessica Thornsby

Index

A Gentle Introduction to OSGi
The Perfect Starter

3 15 20 24 30 37 41

OSGi Update: What’s New in Core 4.3?
OSGi Alliance’s Latest Update

Developing OSGi with BndTools
Combining the power of Eclipse and Bnd

OSGi A La Carte
Bundles, Bnd, PAX, Maven and more

OSGi and JPA
Tutorial: using JPA in an OSGi environment

The Cure for Complexity
OSGi and the Enterprise?

The Enterprise OSGi Specification
Using OSGi in the Enterprise

www.JAXenter.com | May 2011

2

Starting OSGi

A New Approach to Software Development

A Gentle Introduction to OSGi
This is an attempt to give readers the necessary clues to start developing on the OSGi platform. This article will offer reasons to use such technology, and introduce philosophy and key tools.
By Jerome Moliere
For over a decade a group of companies interested in providing software for embedded devices, then for more usual platforms (desktop or server side ones,) started to work on writing specifications for a logical platform aimed at hosting applications while placing emphasis on different criteria: • modularity • efficiency • small footprint • dynamic aspect Among them we can find: • BMW Automotive • Siemens, etc... OSGi specifications are divided into two major books: • OSGi Core, contains the base API for working with OSGi, especially the stuff related to bundles. • OSGi compendium, offering specifications for the whole set of standard services, services available to any compliant OSGi container. • This tale, which started with a focus on embedded devices, turned out to embrace the whole spectrum of software. Success stories, products based on OSGi, are the best way to show what you can do with OSGi: Eclipse (based on an OSGi implementation called Equinox since 3.1 release), Glassfish 3 or Jonas 5 (JEE application servers). For extended features, we may look to extended specifications with: • Enterprise OSGi, offering an enhanced set of APIs aimed at easing enterprise centric development (JPA integration.) • Distributed OSGi, offering mechanisms to distribute applications running on top of a collection of Java Virtual machines.

OSGi Keypoints
OSGi specifications use Java as a base while avoiding classic Java headaches with a special classloading policy. The OSGi classloader deviates from the standard Java classloading policy while offering a way to support these impossible features: • running several versions of the same component inside the same JVM • true class reloading With such power, efficient application reloading becomes possible. So OSGi needs to extend standard Java to deliver components, that's why it just wraps the standard Java deployment format (.jar) while adding metadata into the misunderstood META-INF/MANIFEST.MF file. The OSGi platform hosts components offering services to other components (called bundles in OSGi jargon) and may depend on services offered by other bundles. It’s a real microcosm but with a dynamic facet, where services can appear or disappear at any time. Figure 1 models such relationships between bundles. MANIFEST.MF file will contain all meta information required to express such relationships for each bundle. The following listing shows contents from one bundle requiring at runtime one service for logging purpose (it’s the standard OSGi logging service), this service may have different imple-

Figure 1: Relationships between Bundles

www.JAXenter.com | May 2011

3

Starting OSGi

What can a shell do for you? Just getting full access to the bundles lifecycle while also providing an elegant way to integrate your own commands. If the commands list may change from one product to another, every shell will give you at least access to the bundles lifecycle, so you will be able to : • install/uninstall a bundle • start/stop a bundle • get the list of installed bundles with their current state. Choosing a Shell … It’s a matter of choice but the writer uses felix for its very low footprint and tests its plugins with knopflerfish for convenience (graphic shell is very close to the specifications).
Figure 2: Different States

mentations but that’s not the problem for our code. Please refer to the sample code provided in this article.

Bundle Lifecycle
In such a dynamic environment, components (packaged as jar files called bundles) may be installed, deployed, stopped or removed. Figure 2 from the OSGi Alliance website shows transitions into the different states possible for a bundle. The next section introduces OSGi shells, offering commands to control bundles states.

Services & Tracking From the OSGi point of view, a service is just a plain Java interface, this interface may be implemented in different manners. In such a dynamic environment, getting references to one of the compatible implementations is an absolute requirement. You may use one of the following ways to achieve this goal: • use standard OSGi API. • use the ServiceTracker to get a more convenient result. • use the SCR or Declarative Services, to have an easy and powerful way to inject dependencies at runtime, like Spring Core does (Spring simply does dependency injection) OSGi Standard Services List OSGi defines the following list of services: • http service, to expose with a Web interface resources contained in one bundle. • logging service, to trace events encountered during runtime. • event services, is a mono JVM (OSGi container related only) messages broker. • configadmin, offers a complete API dedicated to storing configuration data for your bundles. • preferences, describes how to store user preferences. • metatype, enables modelling of meta data related to your structures and to handle them gently into GUIs. • SCR or Declarative Services, is the way to inject dependencies into any service at runtime. We’ll have a closer look at… … two of these services: LoggingService and EventAdmin with complete code samples. In the first sample, we will send traces and retrieve them with the LogService API. Sending traces is trivial, just injecting a reference to the LogService, then using it to store LogEntries. Reading these

OSGi Shells
OSGi defines containers made to host applications delivered as bundles (the unit of deployment). The runtime controlling your applications is called a shell like Unix shells manage programs. Working with OSGi means delivering (provisioning) your application as bundles and deploying them into a shell. You may choose between different equivalent OSGi implementations: • Apache Felix, • Eclipse Equinox, • Knopflerfish from Makewave You may use extensions from the OSGi specifications and use: • Paremus shell (for Distributed OSGi) • Apache CXF • Eclipse ECF or for Enterprise OSGi products like: • Apache Aries • Apache Karaf is a useful shell too

www.JAXenter.com | May 2011

4

} } Sample code : retrieving log entries package com.addLogListener(this).component.JAXenter. } } Listing 1: adding logging entries package com.out. "une trace info"). import aQute. logReaderService.LogService.annotation. import aQute.LogEntry. import org.component.osgi.println("dereferencement LogReaderService").println("activating LogProvider bundle").LogListener.annotation.bnd. } } // activate and deactivate methods are ways to avoid // to write dedicated Bundle Activator class @Activate public void activate(BundleContext bc){ System. import org.out.Deactivate.annotation.println("dropping LogProvider bundle"). import aQute. if(logService==log){ logService=null. import org. if(logReaderService==lrs){ logReaderService=null. @Component /** * <p> * sample code showing how to add log entries * here .logprovider.getMessage()). Figure 4 shows events in action.LOG_ERROR.osgi.log. import org.osgi.out. * logged() method is the method to override to implement the * LogListener interface * </p> * @author jerome@javaxpert. the object storing messages (events in the EventAdmin wording). Listing 2 illustrates how OSGi provides a smart way to master coupling between bundles using a ‘messages broker’like : EventAdmin..out..framework.log(LogService.annotation.Component.osgi.MOLIERE .. } } @Override public void logged(LogEntry entry) { System.framework.Activate."+ entry.jerome@javaxpert.annotation.bnd.log. "une trace debug"). System.Reference.bnd.bnd.LOG_DEBUG.println("injecting logservice reference").annotation. Figure 3 shows the results of two such bundles installed in a Felix container.println("desactivation bundle lecture logs").com * @see LogListener */.bnd.component.bnd. } @Deactivate public void deactivate(BundleContext bc){ System. it comes from the import org.Deactivate.Component.LOG_INFO. www.println("entry added .out.the LogService is injected through SCR services * but standard way using ServiceReferences work too.out. logService.logreader.out. "une fausse erreur").out.books.Activate.annotation.out. import aQute.Reference.osgi.service.").log(LogService.javaxpert.BundleContext. Modularity & OSGi Where does modularity come from in the OSGi world? Modularity in the OSGi jargon is not just bullshit.books.service. Sending events with EventAdmin.println("removing log service .logservice. import aQute.Starting OSGi traces is not difficult while using the LogReaderService (Listing 1). @Reference public void setLogReaderService(LogReaderService lrs){ System.bnd.component.println("injecting LogReaderService"). } public void unsetLogService(LogService log){ System. It's important to ensure to use the same name in both bundles to get a working communication.osgi. import org.println("Bundle LogReader active").log(LogService. if(logService!=null){ logService.out.LogReaderService.com */ public class LogProvider { private LogService logService. logService=log. } public void unsetLogReaderService(LogReaderService lrs){ System.component. public class LogReader implements LogListener { private LogReaderService logReaderService.osgi.bnd. } } @Deactivate public void deactivate(BundleContext bc){ System. import aQute. logReaderService=lrs..service. logService.osgi.logservice.BundleContext.log.javaxpert.component..log. } // logged() @Activate public void activate(BundleContext bc){ System..com | May 2011 5 . import aQute. @Reference public void setLogService(LogService log){ System. import aQute..component.println("enregistrement du listener OK"). @Component(immediate=true) /** * <p> * show log entries written by previous sourcecode * LogReaderService is injected through SCR. *</p> * @author J. The two bundles use a naming convention while sharing a common topic.component.service.annotation.

Scrum or whatever methodology you want). it is the ‘black box’ principle. This contract lists explicitly what the component offers to the platform and what it requires from it. enables us to change the implementation bundles without any impact on the client components. It's just a ‘component aware’ manner to translate the TAO of object modelling.JAXenter. With such a low level of coupling between components. If using the basic OSGi API raises many problems and induces a lot of codelines. good design principles become trivial. Many solutions may exist while trying to use a service. using the ServiceTracker while injecting service references directly into your component may be the better solution. where you should use the most generic interface of a class rather than the most specific one. SCR is a very dynamic and powerful solution. it is materialized using the META-INF/MANIFEST. using it can be as simple as using the XML form or annotation as provid- Figure 5: Releases www.com | May 2011 6 .Starting OSGi Figure 4: Events in Action Figure 3: Results of two bundles installed in a Felix container strict cutting of responsibilities between components deployed into the OSGi container (bundles). The contract between a bundle and the container is the key point. the whole application feature list is being completed with the next releases if you follow an agile scheduling (XP. Such design is the key to get working architectures in very short timeframes. Defining services as Java interfaces into API bundles (delivering concrete implementations of this service in separate bundles) and specifying dependencies to the only API bundle. You don't need to be a mechanical specialist to start your car. Conforming to this rule is necessary to do modular development. A component requiring a service does not need to know the implementation delivering this service.MF file. like the one of mocking components while testing your applications following Test Driven methodologies.

Activate.out.Starting OSGi ed by bnd (refer to the tooling section).util.. import org.put(EventConstants.bnd. if(eventService!=null){ int number_messages = (int)(Math. System.EventConstants. d ).osgi.demo.Event.osgi. private EventAdmin eventService. } @Override public void handleEvent(Event event) { System.put(EventConstants.util.util. for(int i=0.out.println("dropping EventAdmin test bundle").annotation.registerService( EventHandler. System.framework.JAXenter. It’s not the only one because since early releases of specifications.Map.out.service. import java.javaxpert. System. topics ).annotation. import aQute. import aQute.service.bnd.i++){ properties.component.annotation.osgi.bnd. context. System.Hashtable. import aQute. d.out."). System.component. } //set public void unsetEventService(EventAdmin admin){ eventService= null.event.eventadmin. import aQute. } } Listing 2 package com.random()*10). /** * <p> * Publishes events using the OSGi internal broker * EventAdmin is injected through SCR * </p> * @author romje. OSGi provided different ways to do this job (ServiceTracker or through the Service API ).component. System. /** * <p> * receives messages from well defined topics those * following the following naming convention : * com/javaxpert/osgi/tests/topicTest* * </p> * @author romje * @see EventHandler * */ @Component(immediate=true) public class EventReceiver implements EventHandler { private BundleContext bc..out.com * */ @Component(immediate=true) public class EventPublisher { private BundleContext bc. eventService.Component.getProperty(EventConstants.BundleContext.out.. import org."message number = "+ i).").out. public void deactivate(BundleContext context){ bc=null.osgi. } } //activate @Deactivate www.class.println("dropping test receiver. @Reference public void setEventService(EventAdmin admin){ eventService= admin.Deactivate.println("Event service injected through SCR"). import java.bnd.getProperty(EventConstants.osgi.javaxpert. System. It’s the best architectural response to the problems raised while trying to handle dependencies to services appearing/disappearing during the runtime phase. import aQute. @Activate public void activate(BundleContext context){ bc=context.i< number_messages.println("Sent asynchronously a number of messages = "+ number_messages).getName().annotation.annotation. Map properties = new HashMap().Activate.demo. } //unset @Activate public void activate(BundleContext context){ bc=context.osgi. import aQute.component. } //deactivate } Receiving events through EventAdmin package com.osgi. import aQute. jerome@javaxpert.osgi.util.Component.println("Receiver is ready soon.com | May 2011 7 .println(eventService!=null?"OK service ready to send msg":"oops no EVentService yet").HashMap. import org.postEvent(new Event( "com/javaxpert/osgi/tests/topicTest".MESSAGE) ).osgi.Deactivate. import org.EventHandler.event.service.event.eventadmin.println("unset Event Service").sender.event. import org.bnd. import org. Dictionary d = new Hashtable().osgi.Reference.event.receiver.service.component.EventAdmin.MESSAGE.bnd.service.EventConstants. import org. import java. this.Event.service.EVENT_TOPIC.println("Received a message from topic =" + event.annotation. final static String [] topics = new String[] { "com/javaxpert/osgi/tests/topicTest" }.EVENT_TOPIC) + " containing : " + event. properties)). import org. import java.component.Dictionary.bnd.component.BundleContext.annotation.event.out. } @Deactivate public void deactivate(BundleContext context){ bc=null.framework.

Bnd by Peter Kriens. As with any Java based environment. Figures 8: SCR configuration pane Figures 9: runtime configuration for your OSGi shell www. the Swiss army knife OSGi tool. more quickly. that is to say: • Development • Debugging • Deployment • Integration into an integration process (Continuous Integration) 1. Basic Brick. Bnd scans your code to fetch imports so it computes for you the long list of imported packages.JAXenter. OSGi Alliance fellow. is a versatile tool. you just need to code into Java. Bnd has three main roles. but instead to delegate the generation of this file to a dedicated tool. and it can perform three kind of jobs for you: • inspecting a bundle • wrapping a library into a compliant bundle • creating a bundle from your code Bnd comes with its own syntax and set of directives.Starting OSGi Figure 6 and 7: BndTools in different Situations Working with OSGi What is the arsenal of weapons to deploy to work with OSGi? The answer will include different facets of work. This text based format has many traps and it sounds like a good idea not to handle them directly.com | May 2011 8 . it’s very rich and only dedicated to one thing: having more compliant bundles. but providing metadata requires you to master the tricky MANIFEST.MF file format. Here comes bnd to the rescue.

You need to provide the privatepackage clause too.JAXenter.com | May 2011 9 .Starting OSGi Figures 10 . It can’t guess what services you want to expose so you must take care of this. It is an Eclipse plugin wrapping bnd features with a clear and intuitive interface. It just works!!! BndTools provides a new kind of project with a Bnd OSGi project. each one providing a concrete answer to a frequent need Here’s how to wrap an existing library into a ready to use OSGi bundle.12 show different tabs of this versatile tool . 2. After creating such a project you’ll be able to access the following features: www.MF for you. IDE integration BndTools by Neil Barlett is the most powerful environment for OSGi development. Easy isn’t it? Bnd inspects contents from your code and generates the import-package clause from MANIFEST.

apache. using a single configuration file you will be able to configure one or several repositories (directories) targeted to host bundles and configuration properties file (for the ConfigAdmin Service).JAXenter. 3.bnd descriptor to suit your needs • run the bnd. • bundles implement the expected services Moreover the WebConsole can be used to view trace entries as issued by LogService and last but not least it is an extensible component.org/Repository/HomePage www. powerful and easy. you have created your first bundle with BndTools.org/ [9] OBR repository: http://www.amazonaws. He is doing consulting and training for his own company Mentor/J.fileinstall.The following listings contain the complete source code for Java code and bnd files required in our context. To conclude with this tool we should mention these requirements: • code makes usage from NIO so ensure your JVM offers this API • webconsole is just a war deployed into the HttpService.osgi. You may use the different tabs offered to ensure that: • all bundles have the expected state • all dependencies are met messages (events in the EventAdmin wording).dir = deploy felix.org [2] Equinox project: http://www. felix. providing bundles close to the specifications and close to the state of the art in OSGi development.apache. BndTools used in conjunction with Peter Kriens’s annotations provide a very convenient way to inject components without even writing a single line of XML as used by SCR. It’s important to ensure to use the same name in both bundles to get a working communication. fun because of the pleasure felt in designing applications that just work! I have still many things to write about this technology but it is time for me to conclude. Jerome Moliere discovered Java early 1996. He can be reached at jerome@javaxpert. so it requires you to install the Jetty Web bundle • optional dependency to LogService • Provisioning with Felix FileInstall FileInstall provides an easy way to install bundles into your OSGi container.blogspot. This is a very nice tool. Using this tool involves using a workflow like the following: • create a new Bnd OSGi project • create a Java package • create some code (interface + implementation for a service or a single concrete Java class for a client) • create a new bnd bundle descriptor • adjust the bnd. he is a SCJP2 and JBoss certified architect. He blogs at http:// romjethoughts. It has a few dependencies as shown in the next picture.org JMS specifications [6] Bnd: http://aQute. We’ll take our simple use case once again and rewrite it using BndTools and Bnd annotations. success because of its efficiency and great design.org/equinox [3] Knopflerfish project: http://www. This tool is an incredible one. Conclusion I wish you a good trip into this new approach to software development. He is about to deliver the first French book dedicated to OSGi.dir) and the polling interval (one second here). These properties may be integrated into the Felix config file (living into ${felix. Please ensure to modify the Components tab view from each bundle using Declarative Services and adding one or more (maybe a joker) list of components. This bundle used in conjunction with the SCR is the perfect way to automate application starting. This sample shows properties used by Felix FileInstall to configure one deployment directory (felix. Happy coding. It is a very convenient way to configure your application simply by setting a few properties as shown in the next sample. not so easy to find while the application is running (tricky indeed).knopflerfish.com.fileinstall.OSGi specifications [1] Felix project: http://felix.paremus.com [8] Felix Web Console: http://felix.com [5] Apache Aries: http://aries. easy to use and install.com | May 2011 10 . OBR is an http repository like the ibiblio one for Maven storing many Java projects ready to use in OSGi environments. I am convinced that it should bring you success and fun.Starting OSGi • directly test your code in Eclipse with your preferred shell • watch/edit the contents from your MANIFEST.apache.poll = 1000 Felix FileInstall can be used as a replacement or in conjunction with the OBR (Bundles repository).eclipse. The best solution is to install Felix WebConsole and to connect to this console through your browser to diagnose the origins of your problem.biz/bnd [7] BndTools: http://bndtools-updates. while having no hassles with the runlevels.dir}/conf/config. Debugging with Felix Web bundles What can go wrong during runtime? You may have unsatisfied dependencies.fileinstall. because Felix Install acts as a watchdog. Figure 6 and 7 show BndTools in different situations.org [4] Paremus distributed OSGi: http://www.s3.MF file • inspect the contents from one bundle • declare dependencies injection graphically with a dedicated wizard • manage your runtime environment (adding bundles to be included in your shell at runtime) • handle import/export clauses of your bundles graphically without any other intervention besides drag and drop. Figures 10-12 show some facets from this very useful tool.properties).bnd with a Run As OSGi application (right click) Here you are.com/ References Pointers .

San Jose CA www.com/JAXconf JAXConf JAXConf Organized by: .JAX – The Premier Java.jaxconf. 2011.com Java EE Java Core Java Languages UI/Ajax/Components Agile ALM Android Cloud Web Architecture Portals Webtech & JavaScript Just JSF Fullstack Spring OSGi Technical presentations and tutorials In-depth coverage of the latest technologies Practical implementation techniques Neutral coverage of the most important Java Ecosystem topics follow us: JAXconf Partners: twitter. Architecture & Agile Experience 2 GREAT CONFERENCES COMBINED June 20 – 23.

Then we will use an Open Source Java PaaS (Stratos) as an example to look at issues of multi-tenancy. JAX has become internationally renowned for its unique blend of topics. It needs to be polished and have that design stuff too. Romain Guy (Google) Come hear engineers on Android's UI toolkit team talk about features of the UI toolkit that you should understand to write better. Architecture & Agile Experience JAX 2011 – It’s about you. project managers and architects to learn about all the latest Technology. Using these services allows you to build highly scalable applications without the pain and cost of having to build your own infrastructure. jQuery Mobile is a touch optimized framework designed to provide a common look and feel across a wide variety of today's mot popular platforms. Android Graphics and UIs Chet Haase (Google). This year JAX is pleased to be working in collaboration with the popular JSF Summit.JAX – The Premier Java. Java EE. It will cover Paas in public and private cloud. isolation. There are also a growing number of cloud-based web services that you can use to develop your application. Architecture and Agile Methodologies. Going Mobile with jQuery Nathaniel Schutta (ntschutta. Oh and it needs to be on all the major platforms in time for the big marketing push next month. Please find more updates on www. we'll take a look at all that jQuery Mobile has to offer and we'll convert a native application to an HTML5. CLOUD COMPUTING DAY Moderator: Tobias Kunze Briseño Understanding Platform as a Service Paul Fremantle (WSO2) This session examines Platform as a Service (PaaS) in detail. Architecture. After a moment of panic. Apps Ben Galbraith (Set Direction) With the recent release of Firefox 4. We’d like to provide you a snapshot of our programme. truly graduating from markup renderers to sophisticated app run-times. the mobile ecosystem is white hot. since its conception in 2001. how do developers target all of these different platforms? Join Ben and Dion as they share their thoughts on these and other issues. MOBILE DAY Android 3. animation. At the same time. solution architects. and more usable applications. it’s about Web. resource sharing and security. it’s about Java. and project managers who develop applications with JavaServer Faces (JSF). Looking first at the definition and various PaaS offerings. We're sure to see some amazing new web applications just over the horizon that take advantage of these new capabilities. you wonder if it's too late to become a plumber but don't worry.com! MOBILE KEYNOTE Web vs. jQuery Mobile masterpiece. But did you know jQuery could also help you with your mobile needs as well? That's right. Romain Guy (Google) Come hear engineers from the Android team at Google talk about the latest advancements in the Android platform. It provides the ideal forum for software developers. In this session. Seam. we're reminded that today's browsers sport amazing capabilities. What relationship do mobile "apps" have with the web and how will these two communities co-exist into the future? Also. and related technologies. . the session will cover the benefits and disadvantages of PaaS offerings. Developing Java applications with Cloud Services Chris Richardson (SpringSource) Cloud computing isn't just about application deployment.jaxconf.com) The word just came down from the VP . faster. and performance. Cloud & Agile JAX is one of the world's most comprehensive conferences on web and enterprise development. there's hope! More and more developers are falling in love with the "write less do more" library and for good reason. it simplifies the job of today's front end engineer. This talk will cover such user interface technologies as views.you need a mobile app and you need it yesterday. and how you can take advantage of these features to create great Android applications. graphics. a conference for application developers. In this talk you will learn about the benefits and drawbacks of some of these web services.0: Honeycomb Highlights Chet Haase (Google).

But what exactly is this “platform”? What am I. however. but also good engineering practice. For instance. JPA. In this talk your learn about some popular NoSQL database including Redis.messaging or other lowlevel services can be combined with higher-level business services SPRING DAY Moderator: Rod Johnson Party-to-Go: Adding Social and Mobile Capabilities to your Spring Applications Craig Walls (SpringSource) This session will look at the various strategies for utilizing a Spring back-end with social and mobile platforms. offering decent service at a low price point or even no cost at all. going to monitor and manage? Also. more importantly. cloud platforms impose constraints on guest applications as part of their design. Using Spring with non-relational Databases Chris Richardson (SpringSource) The needs of many enterprises have stretched traditional RDBMS based solutions to the breaking point and as a result. Architecture & Agile Experience JavaEE on Google App Engine: CDI to the Rescue! Ales Justin (RedHat) Google App Engine (GAE) is among the most popular cloud application platforms today. A common theme is the need to assess modularity and services differently as architectural styles in the cloud.JAX – The Premier Java. authentication and authorization via Oauth to integrate with social network sites such as Facebook.0 features such as the Spring Expression Language. or spawn threads. Twitter. We draw from several examples of public and private cloud services. or something in between. JDBC. Cassandra and MongoDB. ConversionService. By bringing traditional Spring values such as portability. as a developer. This talk presents a number of tips and tricks on how to use top JavaEE specs--CDI. a division of VMware) Spring Framework 3. and Spring's new caching abstraction. It will then look at how Red Hat promotes Open Choice of middleware and programming models with its recently unveiled OpenShift Express and OpoenShift Flex platforms. . a plethora of new non-relational storage options have appeared. and for sound economic reasons. you can't write files. What's new in Spring 3. make arbitrary network connections. Spring in the Cloud Dave Syer (SpringSource VMware) Writing an application for cloud deployment can be a different proposition than writing it for local. we'll cover Spring's ongoing support for enterprise Java specifications: in particular our Servlet 3. JSF2. going to code against? And what am I. feature specifications within configuration classes. Key takeaway is that JavaEE on GAE is not only possible. as well as some of the solutions currently on offer in the industry. Whether they are public or private. productivity and a unified POJO based programming model to this style of data access this session will show how the Spring Framework is evolving to support non relational ('NoSQL') databases as well as complex data processing via Hadoop and updated JPA support. and LinkedIn. you will learn about Spring Integration's support for Spring Framework 3. Cloudy Innovation: Platform-as-a-Service and Open Choice Tobias Kunze Briseño (Red Hat) Platform-as-a-Service (PaaS) lures developers with the promise of worry-free deployment and application management. its Java environment is also a fairly restrictive. and RestTemplate. We show some tips and tricks on using and enabling features of Spring in the cloud and draw examples and demos from a wide range of application styles and cloud platforms. There are also increasingly many software services that have an integration aspect . Along the way.0. TCP/UDP. You will also learn about several new adapters including AMQP. JMX.0 support. and more. or it could be a home-grown private in-house service. with my operator hat on.1 continues Spring's mission with a focus on flexible Java-based configuration. A cloud platform could mean a commercial public offering like EC2 or vCloud. its strengths and opportunities.1? Jeremy Grelle (SpringSource. server-push style messaging. Unfortunately. to create a system that is more than the sum of its parts. such as consumption of RESTful services.0 Josh Long (SpringSource) This session provides a practical hands-on introduction to the capabilities in Spring Integration 2. This presentation introduces foundational 3. where's the catch? What do I have to give up in exchange? This talk sheds some light on the fundamental tradeoffs of PaaS. We will demonstrate how CDI can be used to abstract from GAE's services and how state-of-the-art testing frameworks such as ShrinkWrap and Arquillian can be made to work with such an application. XMPP. physical use. Attendees will get a feel for how PaaS can revolutionize their operations and the way the think about applications. and show how the target system influences application design. and BeanValidation. Finally. They will also learn how to make informed decisions when selecting a platform for their application needs.1 facilities such as environment profiles for application contexts. Introduction to Spring Integration 2. for instance-within GAE's restrictive sandbox while still benefitting from the highly scalable environment it provides and maintaining portability to other JavaEE containers. In this presentation we explore the practical consequences of designing and implementing applications targeted at a cloud platform or software services.

0. We'll demonstrate how to get the most out of RichFaces client-side validation. including what really makes them tick. bringing each of the independent EE technologies together into a cohesive whole.com.JAX – The Premier Java. Examples will include partial table updates. and our new push architecture with Atmosphere. Seam Faces further integrates JSF and CDI and leverages frameworks such as PrettyFaces to make JSF a full-featured web application framework and the JSF developer's life easier. Seam 3 brings Java EE improvements of tomorrow. RichFaces 4. All JSF Summit talks can be found here: http://jaxconf. This session will review the best ideas from Trinidad and ADF. Seam. today Daniel Allen (Red Hat. enhances and extends Java EE platform. Inc. Ajax queues.com . CDI and Seam Faces realize the full potential of JSF Daniel Allen (Red Hat.) This presentation will show developers how they can deploy JSF 2 portlets within Liferay Portal via the PortletFaces Bridge. solution architects. client-side validation. There will be plenty of tips and tricks.) This talk reintroduces Seam as a portable. the integration falls short in JSF. Inc. AlloyFaces. Inc.) This sessions will get into the weeds of some of RichFaces newest and most advanced components. developers will learn how to use JSF UI components from AlloyFaces and LiferayFaces within their JSF 2 portlets. Discover the possibilities Seam brings to Java EE. and a component development kit (CDK). So bring your laptops and you can follow along with online source.) Mobile applications for iPhone and Android can be effectively developed with JSF 2. Productive RIA Development with Spring Web Flow and JSF 2. Brian Leathem (TRIUMF) CDI is the glue of the Java EE 6 Platform.0 Ted Goddard (ICEsoft Technologies. and skins. it's time for a fresh look at what Java development tools make up the ideal web stack. You're given a brief tour of the CDI programming model and learn how it unifies.). Java EE. Additionally. cloud deployment. and project managers who develop applications with JavaServer Faces (JSF). by Red Hat Inc.jaxconf. Then you see how Seam 3 takes it further.0 and ICEfaces. In this session you'll learn what is important from a Spring developer's point of view: What can I do with Spring and JSF 2? What is the status of the Spring Web Flow integration for JSF? What JSF 2 features are supported and what value does Spring Web Flow provide in a JSF 2 world? Developing JSF 2 portlets with ICEfaces.0 Jeremy Grelle (SpringSource. a division of VMware) With the onset of JSF 2. Ajax Applications with JSF 2 and New RichFaces 4 Max Katz (Exadel) RichFaces is a JSF framework with Ajax components. highlighting more general JSF development problems and solutions that are of interest regardless of your choice of framework. This session will briefly cover JSF2 Ajax features and then the extra value the new RichFaces adds on top of JSF2 through its advanced features. Mobile Ajax Push with ICEfaces 2. Inc. including automatic Ajax and ICEpush for rich Inter-Portlet Communication (IPC). JSF Summit is a conference for application developers.0 Component Deep Dive Jay Balunas (JBoss. and related technologies. arguably where it's needed the most.0 brings to portlets. GAE deployment. Join this session to learn how to use Ajax Push to build a collaborative mobile application with ICEfaces 2. they also offer a range of APIs and services that simplify both component and application development.com/2011/jsfsummit/ More talks and tutorials on all important Java related topics can be found here: www. client-side validation. skins. It will explore the benefits that ICEfaces 2. not to mention code. Architecture & Agile Experience JSF SUMMIT Moderator: Kito Mann Originally produced by Kito Mann and JSFCentral. However. modular and type-safe framework built atop CDI: Contexts and Dependency Injection for Java EE. We look at how and why Seam 2 evolved into CDI. Beyond Components: JSF Development with Trinidad and ADF Andy Schwartz (Oracle) While Trinidad and ADF provide an extensive set of components. and LiferayFaces Neil Griffin (Liferay.

Let’s take a look at these new features.3 [1]. based upon the Java 1.3 release.LogService”).osgi. The main place in the OSGi Framework API where generics are used is in the Service Layer APIs for type safety. The OSGi Alliance did not want to do that. But Java Micro Edition (CDC-1. Several methods have been overridden to take Class objects and the service related interfaces have formal types. LogService log = context. Capabilities and Requirements OSGi bundles have always been able to export packages to and import package from other bundles.3? The OSGi Alliance has recently published the OSGi Service Platform Release 4 Core Specification Version 4. by BJ Hargrave and Peter Kriens Release 1 of the OSGi specifications came out in 2000 well before Java 5 introduced a number of new and useful language features.getService(lr). the OSGi Framework API does not use these language features.service. LogService log = (LogService)context. is still a target platform for OSGi development. Instead we took advantage of the undocumented compiler option -target jsr14 [2] to allows the use of Java 5 generics in the API while still supporting the Java ME platform. we have generalized this into the concepts of bundles offering capabilities to other bundles and bundles expressing requirements for a capability from another bundle.getServiceReference (“org.JAXenter.OSGi Update New Features for the Framework What’s New in Core 4. Both javac from the JDK and the Eclipse Compiler for Java support this option in their current releases. For example: ServiceReference lr = context. The changes provide type safe references to OSGi services and avoid the need for explicit casts. For the Core 4. Becomes: ServiceReference<LogService> lr = context. The specifi- Figure 1: Requirements and Capabilities and their Wiring www.getServiceReference(LogService. We define a capability as a set of attributes (key/value pairs) in a namespace and a requirement as a filter expression over the attribute set of a capability in a namespace. So to update the OSGi Framework API for Java 5 language features would mean abandoning the Java ME users of OSGi.getService(lr).4 language and class libraries. Some of the new features are useful to application programmers while other new features are meant for systems programmers.log.1). The OSGi Framework API looks a bit old fashioned in the absence of the use of any of these new language features.1/Foundation-1. Since enums and annotations require class library support which does not exist in Java ME. So now one can use the Service Layer in a type safe manner. The resolver in the OSGi Framework has to match exporters to importers in order to resolve bundles for execution. This update to the Core specification adds a number of new features to the OSGi Framework.com | May 2011 15 .class).

osgi.bundle and osgi.OSGi Update Figure 2: Relationship between Bundle and the Bundle Wiring types cation defines the built-in namespaces: osgi. requiring bundles and being a fragment respectively.capabilities. within the osgi.package namespace.framework. www. Now bundles can use the Require-Capability manifest header to declare a requirement in the osgi. Frameworks can be configured with the new org.osgi. A bundle cannot be resolved unless its mandatory requirements can be satisfied by a capability from some bundle.host. capabilities and org.ee namespace on the execution environment. For example.system. Using a service to supply framework function was an important choice at the time.executionenvironment framework launching property and the Bundle-RequiredExecutionEnvironment manifest header.wiring.framework.extra framework launching properties to provide capabilities in the osgi. the specification defines the new osgi.package. to represent the existing concepts of exporting and importing packages. In addition to the built-in namespaces.system.framework.wiring. The built-in namespaces cannot be used on the new Provide-Capability and RequireCapability manifest headers). It enabled additional function to be added in an optional manner so resource constrained systems could implement the OSGi Framework without implementing the PackageAdmin service.wiring. osgi.osgi.ee namespace to replace the org. This will result in the system bundle providing the specified capabilities which can then satisfy the requirement from a bundle. It also avoided adding methods to the core framework types such as Bundle which would only be interesting to systems pro- Figure 3: The wiring for an update bundle that has not been refreshed. The idea of generic capabilities and requirements is also added. Bundle Wiring API The PackageAdmin framework service was introduced by Release 2 in 2001. an export package is represented by a capability and an import package is represented by a requirement.com | May 2011 16 .JAXenter. These requirements become additional constraints to the resolver in the OSGi Framework and are visible in the new Bundle Wiring API (Figure 1).ee namespace representing the current execution environment.wiring. This allows bundle programmers to define their own namespaces so a bundle can provide a capability with the new Provide-Capability manifest header and have a requirement for a capability with the new Require-Capability manifest header.

it first calls the weaving hooks to give them an opportunity to mutate the class file for the class. The most recent wiring of a bundle is called the current wiring and can be obtained by adapting the bundle to the BundleWiring type (Figure 2). version and declared capabilities and requirements. Start Level API The StartLevel framework service was introduced by Release 3 in 2003. The Framework will create a WovenClass object for the class being loaded and call the WeavingHook services in service ranking order. it was also provided as a framework service as a way to add function to the Framework that could be optional and not complicate the core types. the weaver needs to be able to modify the woven bundle’s wiring so the bundle can access these classes. Whenever a bundle is resolved. a new revision of the bundle is created. Since it is quite common for a weaver to add code which may call classes which are not originally used by the bundle. Whenever the Framework is preparing to load a class from a bundle. A BundleWiring for a bundle contains information about a specific wiring of the bundle such as the capabilities and requirements that are wired together.3. The most recent revision of a bundle is called the current revision and can be obtained by adapting the bundle to the BundleRevision type. While StartLevel has been deprecated and replaced by the Start Level API.3. Using the FrameworkWiring object.com | May 2011 17 .JAXenter. older revisions and wirings of the bundle may still be in use. type safe adapt method on Bundle. For example: BundleWiring wiring = bundle. the system bundle can be adapted to the FrameworkStartLevel type (Figure 5). framework implementations will still implement the StartLevel service for some time to come to support existing bundles that use the StartLevel service. But the cost of this design choice was an API that is not very object oriented since you have to pass the Bundle objects to the methods. All of these operations are very useful for management code (Figure 4). The removal pending bundles.class). To inspect or modify the start level information for a bundle. While PackageAdmin has been deprecated and replaced by the Bundle Wiring API. To inspect or modify the start level information for the Framework. Refreshing a bundle will result in the non-current revisions and wirings to be released by the Framework. was not very object oriented. tracing or logging APIs. In 4. A BundleRevision for a bundle contains information about a specific revision of the bundle such as the symbolic name.OSGi Update grammers. The system bundle can be adapted to the FrameworkWiring type which provides access to framework wide wiring operations. that is. we introduce the new Start Level API which replaces the StartLevel framework service. In 4. Weaving Hooks are services registered by bundles that are prepared to weave the class files loaded from other bundles. we introduce the new Bundle Wiring API which replaces PackageAdFigure 4: Relationship between the min and provides a much system bundle and the Framework richer model of the wiring Wiring type relationship between bundles. with the introduction of the adapt method to Bundle. the bundles which have non-current revisions and wirings. But this design. So the WovenClass object lets the weaving Figure 5: Relationship between bundles and the Start Level types www. The wiring can also be used to scan the class path of a bundle and to obtain the class loader of a bundle. In 4. we introduce Weaving Hooks. Instead of using a service to deliver the new API.adapt(BundleWiring. Ten years later. for example. There has long been interest in bytecode weaving in OSGi but there has never been an OSGi standard way to do it. and we also find that the PackageAdmin service does not well model the actual wiring of bundles in the Framework. framework implementations will still implement the PackageAdmin service for some time to come to support existing bundles that use the PackageAdmin service.3. Weaving Hooks Bytecode weaving is becoming very popular particularly in enterprise applications such as those using JPA. Whenever a bundle is installed or updated. bundles can be resolved and refreshed. today’s resource constrained systems are much bigger. like PackageAdmin. Each weaving hook will have the opportunity to mutate the byte array containing the class file of the class to be loaded. All the available revisions of a bundle can be obtained by adapting the bundle to the BundleRevisions type (Figure 3). adapt the Bundle object to the desired bundle wiring type. the bundle can be adapted to the BundleStartLevel type. To learn about the wiring state of a bundle. a new wiring of the bundle is created. can also be obtained. If a bundle has been updated. the API is available via the new. Like the PackageAdmin service.

Since resolver hooks can modify how. Using these hooks allows different grouping policies to be created rather than specifying a single grouping policy into the Framework. Once all the weaving hooks have been called. care must be taken in developing and deploying weaver bundles to ensure the integrity and security of the system.JAXenter. The missing piece is how to limit which bundles are visible to a bundle. the Service Hooks introduced by 4.3.3 specification with the introduction of Resolver Hooks and Bundle Hooks. and even if. This allows a resolver hook to create a grouping policy for bundles with respect to how the bundles can be wired. when the Framework must decide whether a bundle can observe Figure 8: Bundle Hook services www. Resolver Hooks In previously released drafts for Core 4. Bundle Hooks are services registered by bundles that are called by the Framework. For each resolve operation. Bundle Hooks The Service Hooks introduced by 4. With Resolver Hooks you can place limits on how bundles are wired together at resolve time. care must be taken in developing and deploying resolver hooks to ensure the integrity and reliability of the system. the Framework will call the ResolverHookFactory services. there were specification proposals for Composite Bundles and virtual frameworks. provide low level primi- tives upon which grouping policies for bundles can be implemented. So. requesting a ResolverHook object that will be used for the duration of the resolve operation. These proposals were attempts at defining a grouping model for bundles such that bundles in a group would be able to share packages and services while bundles outside the group would have more limited access. The Resolver Hooks.com | May 2011 18 .OSGi Update Figure 6: Weaving Hook service Figure 7: Resolver Hook Factory service hook add DynamicImport-Package entries to the bundle’s wiring. This is the purpose of the newly introduced Bundle Hooks. Since weaving hooks can modify classes from other bundles. a complete grouping model can be implemented [3]. bundles are resolved. it can influence the choices the resolver can make.2 and the new Resolver Hooks are important parts of implementing a grouping policy for bundles. Both of these design proposals have been replaced in the final Core 4. in service ranking order. With Service Hooks you can place limits on what services are visible to a bundle. in service ranking order. A ResolverHookFactory is a service that is registered by bundles that wish to influence the Framework’s resolver and how it wires bundles together. while a resolver hook can’t actually make the decisions about how the bundles are wired together. These entries can refer to the packages which contain the classes used by the newly woven class. Using the new Resolver Hooks. Each resolver hook object will be called and given the opportunity to influence the resolve operation by restricting the bundles that can be resolved and which candidate capabilities can be used to satisfy a requirement (Figure 7). and the new Bundle Hooks.2. along with Bundle Hooks and Service Hooks. the Framework will put the new DynamicImport-Package entries into effect and call the VM to define the woven class (Figure 6).

Web or any other method.html [3] http://underlap. His focus is small computer operating systems (kernels. He is currently CTO of the OSGi Alliance and chair of the OSGi Core Platform Expert Group. any of their clients. Tim Diekmann. That is.com/2011/02/stumbling-towards-better-design.html [4] http://www. These methods are used by bundles to find other bundles. Lisa Pychlau Creative Director: Jens Mainz Layout: Dominique Kalbassi Sales Clerk: Mark Hazell +44 (0)20 7401 4845 markh@jaxlondon. Ericsson. The basic abstractions of OSGi: modularity. completeness. He has worked for many years as a consultant for a large number of international companies.ibm. Alexander Broekhuis. Marcel Offermanns. or Publisher.jaxenter. Jerome Moliere. Publisher disclaims all warranties as to the accuracy. At the OSGi Alliance.com Editor in Chief: Editors: Authors: Sebastian Meyen Jessica Thornsby. Peter Kriens is the OSGi Director of Technology and CEO of aQute. omissions. redistributed. All rights reserved.blogspot. BJ is also a committer on the Eclipse Equinox project. a bundle should see either all or none of the life cycle events for a bundle. file systems. misuse. application binary interface specifications) and Java technology. He is the primary editor of all the specification releases since release 2 in May 2001. References [1] http://www. This prevents the removed bundles from observing the Bundle Event (Figure 8). www. He holds multiple patents related to Java and is the IBM expert and lead architect for OSGi technologies. and is not responsible for any errors.JAXenter.3 of the Core specification is another incremental improvement over past specifications.org Imprint Publisher Software & Support Media GmbH Editorial Office Address Geleitsstraße 14 60599 Frankfurt am Main Germany www. These new features add to the level of introspection and control of the Framework. inadequacies. Dmytro Pishchukhin Copy Editor: Claudia Fröhling. without prior written permission of Software & Support Media GmbH The views expressed are solely those of the authors and do not reflect the views or position of their firm.com Entire contents copyright ©2011 Software & Support Media GmbH.osgi. or adequacy of any information. An EventHook can remove bundles from the set of bundles whose listeners would receive the bundle event. No part of this publication may be reproduced. The Find Hooks are called by the Framework during the processing of the getBundle(long) and getBundles() methods of BundleContext. or reused by any means in any form. All mentioned trademarks and service marks are copyrighted by their respective owners. Regarding the information. The Event Hooks are called by the Framework during the delivery of Bundle Events. development tools.com | May 2011 19 . Bundle Hook implementations must take care to ensure that bundles consistently observe or don’t observe other bundles. In 2001 he was hired by the OSGi Alliance to run their specification process. Take care if you decide to use these low level features since they can have a significant effect on other bundles. IBM. or the consequences of using any information provided by Publisher.org/Download/Release4V43 [2] http://www. BJ Hargrave is a Senior Technical Staff Member at IBM with over 20 years of experience as a software architect and developer. In 2002 he became one of the original two OSGi Fellows. posted online. Holly Cummins.OSGi Update another bundle. He lives in France travels the world to help the different OSGi expert groups to accomplish their tasks. electronic.com/developerworks/java/library/j-jtp02277/index. we are continuing to work on new specifications and enhancements to the existing specifications. please check out the OSGi Alliance web site [4] for information on joining the OSGi Alliance or providing feedback. Richard Nicholson. dynamic life cycle and services. Rights of disposal of rewarded articles belong to Publisher. with the Event Hook. Peter Kriens. A FindHook is able to remove bundles from the result set thus preventing the calling bundle from observing the removed bundles.osgi. BJ Hargrave. all continue as before. internal network. BJ has been a leader in the development of the OSGi technology since its inception and was named an OSGi Fellow in 2002 for his technical contributions and leadership in the OSGi Alliance. including print. Seeing only a partial set of events can result in undefined behavior for the observing bundle. If you have input or want to participate in the effort. BJ holds a Bachelor of Science in Computer Science from Rensselaer Polytechnic Institute and a Master of Science in Computer Science from the University of Miami. Two bundle hooks are defined. Claudia Fröhling David Bosschaert. The other bundle hook is the Event Hook. Intel. and others. including Adobe. Some of the new features enable new and powerful capabilities to be built upon the Framework. Summary Version 4. photocopy. Valentin Mahrwald.

resources etc. how processes interact. This overview is often a structural decomposition which describes the components of the system. With this growth there is also a need for better and easier tools needed to develop. code.name/bndtools. Maven and the OSGi bundle plugin. extend and maintain projects. A tool. build and release applications based on OSGi. is a view on components of the system and the deployment of these components to nodes.JAXenter. the manifest has to be created before actual coding starts. It is based on 4 views. manage. within Eclipse a new application can be created by including/excluding bundles. tries to solve this. it's now also a great contender for ever larger and more dynamic systems. they are centered around a “manifest first” model. Maven and Eclipse rely on the concept that one project is one bundle. This includes packages. results in a forced separation of components. Two last two views within the 4+1 model are the development view and the physical view. The 4 views are: • Logical View • Process • Development • Physical www. existing code has to be split into several projects. OSGi is becoming the de-facto standard for modular Java applications. Also migrating existing applications to a component based solution becomes very difficult. By Marcel Offermans and Alexander Broekhuis Building an OSGi based project is mostly done using either custom made build files (Ant in combination with Bnd). using the separation of development and deployment view makes it possible to include classes (from one source) into multiple bundles. This makes it difficult to understand. which can’t and shouldn’t be combined when developing large applications. The developer always needs to keep in mind how source is grouped and what components are available. so each project has its own manifest file. Maven and Ant. Architectural views are used to describe the system from the viewpoint of different stakeholders. The logical view provides a high level overview of the system. source code and additional resources which are included when building the bundle. When adding a new bundle. which amongst others. from an IDE. more complex applications. is BndTools. To explain this problem.com | May 2011 20 . each bundle requires its own project. And this is exactly what Maven and the Eclipse PDT do. In this article these problems are explained and a solution provided by BndTools is introduced. An actual application consists of several bundles. Because doing so. often called deployment view. And even though both views are related. What is needed is the ability to have both a development and a physical view on projects: the development view for development. The physical view. The development view can be described as the view the developer has on the project. without any flexibility regarding reuse of classes and deployment of bundles. using them for complex applications shows some inherent problems. for example. what asynchronous aspects are important etc. With a background of being designed for small embedded systems. and the physical view displays the deployment of (a subset of) artifacts resulting from the development view. All these tools support some kind of automation/abstraction for editing/generating manifest files. and while they are well suited for smaller and simple applications. a problem arises when trying to use this model for larger. on top of which use case scenarios are used to describe interaction within the system. but as well for legacy applications being converted to OSGi. Some well known build tools are Eclipse PDE. Other features of BndTools are explained in detail on the BndTools website (http://njbartlett. Both views are closely related.html). or using the Eclipse Plugin Development environment. and the physical view for division and deployment of components. For example.The Eclipse-based Development Environment Combining the Power of Eclipse and Bnd Developing OSGi with BndTools With the rapid rise of modular software development. For Eclipse this is through the Manifest editor. the 4+1 view will be used. While this provides a model which is easy to learn and use. Even though Maven and Eclipse make it rather easy to update the bundle manifest. 4+1 View The 4+1 views method is a popular method for describing architectures. The process view is used to describe dynamic aspects of the system. so creating a new bundle is simple and straightforward. and with Maven this is via the pom file. for example. The next part of this article will introduce BndTools and how it solves this problem. they provide a different view.

the workspace will contain one project called “cnf”. This build path can consist of other bundles. Its method is also especially interesting for existing projects. The configurations are used to launch an OSGi framework with a selected set of bundles. this is exactly what is needed.The Eclipse-based Development Environment BndTools BndTools is a relatively new tool for building and testing OSGi based projects in Eclipse. An OSGi project is defined by a ‘bnd. typos are easily made resulting in failing bundles. only a number of ‘. After this Figure 1: Repositories View www. This repository is visible as an Eclipse project in your workspace called ‘cnf’ and can contain both third party dependencies in different versions and stable artifacts that have been released from your own projects (so other projects can depend on them).JAXenter. This set of bundles currently automatically includes all bundles from its own project. additional bundles can be selected from a local bundle repository. This is where BndTools comes back in the picture. as is the case with Eclipse OSGi development.biz/Bnd/Bnd Bnd solves the need to completely write and maintain the manifest file of a bundle. BndTools also supports run configurations. For a declarative services project. After creating the project the “bnd. This manifest file is closely related to the classes in the bundle. the better mapping on the 4+1 views. A project can consist of one or more bundles. BndTools provides a new project type in Eclipse called an OSGi project. For example.aqute. for example. a uniform view on all the sources and resources in a project is needed. After creating the configuration. in combination with the on the fly generation of bundles. this model also keeps the source within one project. and updating it can be very error prone. Since BndTools does not impose a “project is a bundle” structure. It is assumed Eclipse with BndTools is up and running. Before detailing more about how BndTools works. Since BndTools is tightly integrated with Eclipse. The file is used to define the bundle symbolic name. the deployment view is also needed to be able to understand how bundles can and can’t interact with each other. A dialog will be shown asking to create a configuration project. This view lists all bundles installed in the repository. Besides. but are never exported. BndTools makes it possible to update bundles in the running configuration. Maintaining these files by hand can be a cumbersome process. To change this. For this example the Empty project template is used. but also a classpath containing plain old jar files. When looking at the 4+1 model. bundle classpath etc. The wizard currently has two templates. Eclipse compiles and builds bundles on code changes. This configuration project contains the bundle repository. BndTools provides the developer with a complete development view. This makes refactoring work over all bundles instead within one. Bnd uses the actual class files to create the manifest file. Its primary goal is take the pain out of developing bundles. Bnd is described on its own website as: “the Swiss army knife of OSGi. It builds on Bnd. BndTools (actually Bnd does all the work) provides support for this by analysing the imported packages in the source with the exported packages of bundles. Finally. there is no need to divide the source into bundles. but still provides enough support to add and point to restrictions which the deployment imposes on the application. Initially BndTools creates a project for a single bundle. but for example also including packages using wild cards etc. the “Enable sub-bundles” option on the “Build” tab has to be checked. A BndTools projects comes preconfigured with a list of useful bundles.bnd” file is opened. this includes dependencies to packages. Using the dynamics of OSGi. Also using one repository ensures multiple related projects within the workspace use the same available dependencies. Using this repository keeps the project clean. which is a powerful command line tool.Repositories View> Next. it is used for creating and working with OSGi bundles. packages which are used by a bundle. and each bundle is defined by a ‘. no additional bundles need to be placed inside the project. and for an empty project. Example The following simple example will be used to create an application with one “Hello World” bundle. This view should not assume anything regarding the deployment of the artifacts created out of the source.bnd’ file in which the metadata for the bundle is placed. With the OSGi perspective also comes the Repositories view. The steps followed will be: • Create a new workspace • Add a Bnd OSGi project • Setup the run configuration • Add a new bundle Create a new workspace and select the OSGi perspective.bnd’ files are needed to create the bundles. bnd’ file in which. The repository is used to store dependencies needed by the projects.” From http://www. <BndTools . Secondly.bnd files created by the developer to customize the bundle. including Felix. This bundle repository will be detailed later on. the exported and private package. Besides bundles.com | May 2011 21 . From the development viewpoint. The bundles shown in this view are all located in the “cnf” project (figure 1). The two views relevant for the developer in this case are still the development and deployment view. let’s see how this maps on the 4+1 views method. Bnd relies on . Equinox and many other compendium services. The existing project can be kept. create a new Bnd OSGi Project. BndTools also has support for a so called repository. the build path for the project is defined.

and bundles from the repository can be added. by creating a new Bundle Descriptor. The desired OSGi framework can be selected. based on OSGi. Marcel Offermans: Marcel is a fellow at Luminis and leads the competence center for OSGi at Luminis Technologies. A bundle descriptor shows private and exported packages. If the framework wasn’t shutdown before adding the bundle. Since the shell is installed. Based on these packages the imports are calculated (figure 3). as mentioned before. and every saved change has resulted in a bundle update. For this example. The run configuration can be found on the “run” tab. Since it is an open source project. using the “ps” command. Creating classes is done using the standard Eclipse method. EclipseCon. some classes have to be created. including ApacheCon. Apache Felix is used as framework and the Apache Felix Shell bundles are added. anyone can look at the source and contribute via patches (using github). the framework can be kept running (figure 2). the project can already be run. This is done on the context menu of the “bnd. The newly created bundle has been installed in the running framework. While BndTools is already very useful. but still the deployment can easily be changed and used via the Bundle Descriptors and run configurations. NLJUG and various local demo camps and user forums and has given several hands-on trainings on OSGi related subjects. This will result in starting the framework with the selected bundles.com | May 2011 22 . This method of development fits the inherent dynamic aspects of OSGi. <BndTools – Running Framework> Now a bundle needs to be added. development and support of an OSGi and cloud based software provisioning product.JAXenter. no special actions are needed for BndTools. it is still being improved. Alexander Broekhuis: Alexander Broekhuis works for Luminis and is a Java engineer since 2004 with a clear focus on OSGi. bnd” file. it is possible to inspect the running bundles. OSGi DevCon. These libraries can be added to the run configuration of the “bnd. a platform for distributed systems in C. BndTools makes it possible to develop. In the last years he has worked for embedded product companies on distributed middleware in which Java and C is used. FOSDEM. For this example a simple Hello World activator will be used. This is done. and more recently updating existing middleware to support dynamic services. and finally it must be set as Activator under the “Basic Information” section. As a software architect he has a broad experience in different operating systems. but does not burden the developer too much with deployment questions while writing the code. the project needs an OSGi framework and possibly some other bundles. Select “Run As” -> “OSGi Run”. For the next steps. the dependency to the framework is now listed. Figure 3: Bundle Descriptor Editor can be seen. <BndTools – Bundle Editor> Before private and exported packages can be added. embedded and distributed systems. it must be added to the private packages of the bundle. Larger projects with multiple bundles can greatly benefit from this model and using the features to update bundles in a running framework can result in a serious reduction of time needed for compiling. Listing the installed bundles now also shows the created bundle (figure 4). Before creating the bundle. The 4+1 model is followed and the developer has a complete view on all the project sources without being bothered with deployment issues. languages and applications.bnd" file as a bundle. After updating the run configuration. will show the system bundle as well as the shell bundles. Alexander is initiator and committer of the Apache Celix project. He has been involved in lots of commercial OSGi projects for over eight years and is responsible for the architecture. Marcel regularly speaks at conferences. ranging from enterprise applications to mobile. <BndTools – Updated Framework> While this is a very trivial and simple example. it is no longer possible to configure the “bnd.The Eclipse-based Development Environment Figure 2: Running Framework change. starting and testing bundles. He is also a member of the Apache Software Foundation and involved as a committer and PMC member in the Apache Felix. Devoxx. the power of BndTools Figure 4: Updated Framework www. Listing these bundles. To summarize. This will result in an update of the calculated imports. with a focus on interoperability with Java (OSGi). MDD). After creating the Activator. His work includes creating meta-models and transformations from which the code for the middleware is generated (MDA. Apache ACE and Apache Celix projects. test and run OSGi bundles and applications in a dynamic way. The bundle has been started and the “Hello”greeting has been printed.bnd" file. Bundles can be added by creating a new bundle descriptor. it does show the power of BndTools.

. Each issue deep dives into one topic. and 3.www. – despite al ures in Java technology e new feat ing about th circulat PDF edition The free PDF magazine powered by JAXenter! www.jaxenter. be it the Scala programming language or Agile development. we take a includ JAXmag EE 6 space. version as Last mon the new Gl 6 for Java EE leased. The magazine provides an insight into emerging trends in the Java universe.com #6 va EE 6 Ja verview lease Java EE 6 O e Latest Re ugh Th A Tour Thro e CDI in G How to Us Engine oogle App E inside G JavaE AE Arquillian JAX-RS on Tests of Integrati e Pain out Taking th va EE 6 ch to the Ja ful Approa A REST ting the Implemen API iPad edition Get the FREE App in the iTunes Store! pas tion to Siw pec n Introduc b Profile S A Java EE We Java Tech Journal is the digital-only magazine covering all the hot topics for Java and Eclipse developers.jaxente 20 Issue March 11 | presente d by r. With re ated server was n Server sl t is still a ho c Applicatio r Java EE 6 e WebLogi ea Oracl ours year. Let's EE ifi tion: a Java Profile spec e specifica e of th latest releas ag JAXm w o is n plication assFish ap e. and Java EE Web ement the illian and JA Arqu ns to impl h the what it mea tour throug and bolts of start with a ! 6 overview cation. it‘s cl abbing rum e later this e-gr complianc In l the headlin EE 7 and 8. this issue of ts g the Java t into the nu es occupyin t an insigh technologi ge X-RS.com TM ch va Teal Ja rn Jou the at some of closer look ing . and offers best practices for established technologies on a monthly basis.1 of the Gl sFish releas th.

the benefits of using OSGi for modularization as well as its inherent support for dynamics far outweighs the initial challenges in using it. we look at the tools that facilitate integration (i. bundle manifests. we have a look at deployment and distribution options. It is assumed that the reader has some familiarity with basic OSGi concepts like bundles. Correctly using OSGi and its modularity model requires discipline and forethought from developers and framework authors. More widespread interest has arisen after Eclipse adopted OSGi as the integration and plugin technology underlying the Eclipse IDE.JAXenter. Even then OSGi was much rarer in the space of individual applications. Especially assumptions made concerning classloaders often no longer hold in an OSGi environment. This move was followed by the adoption of OSGi as the modularization technology at the heart of most JEE application servers. Beyond the familiar Equinox and Felix. If you are interested in OSGi many of these projects will be useful to you but it may not be immediately obvious how. in-container) testing with OSGi. services and OSGi lifecycle. This article hopes to remove some of the biggest hurdles of using OSGi by introducing an appropriate set of tools. A missing import for a needed package can easily mean that OSGi at the very www. Developing bundles At the very simplest level an OSGi bundle is just a traditional JAR file whose manifest has some additional headers that define the identity of the bundles as well as its (package) capabilities and requirements – its imports and exports. This article hopes to alleviate this shortcoming with a whirlwind tour through the most useful open source tools the authors have encountered. Maven and more OSGi à la carte A web search on OSGi will yield a bewildering number of open source projects. The first set of tools is intended to help with the task of developing bundles.A Tour Through the OSGi Tool Chain Bundles. originally in the embedded space. Next. Readers completely new to OSGi are referred to introductory resources such as Neil Bartlett’s “OSGi in practice” [1] as well as the OSGi home page [2]. as OSGi moves into the Enterprise Java space the number of OSGi related projects is increasing. the often cited bold claim “No more NoClassDefFoundErrors with OSGi” relies on correct metadata. However. Only with the advent of a dedicated enterprise OSGi programming model with Spring dmServer have we seen widespread interest in OSGi. Finally. many of which are of recent vintage. OSGi has often been perceived as a hard technology to get started with – especially since OSGi certainly is an invasive technology. However. Bnd. By Valentin Mahrwald & Holly Cummins OSGi as a technology has been around since the late ‘90s. Historically.com | May 2011 24 .e. PAX.

A Tour Through the OSGi Tool Chain Figure 1: BndTools with open Bnd editor and running framework. Eclipse Libra [4] promises to be an interesting option. which comes in many common distributions of the Eclipse IDE (for example the distribution for JEE development). On top of that a collection of bundles can be launched directly from the IDE via an OSGi framework definition. as well as the byte code. the resulting manifest will never contain any surprises. the source code. the Bnd tool provides a holistic solution for bundle development. Web Application Bundles. supporting www. So at the minimum tools for OSGi development should help the developer to produce correct metadata and well-factored bundles. Eclipse PDE and Libra Perhaps the most well-known tooling for OSGi is the Eclipse Plugin Development environment [3]. some of the default suggestions regarding version ranges and the usage of Require-Bundle do not conform to widely accepted OSGi best practices. first usage actually introduces more missing classes rather than less. persistence bundles and the like. Peter Kriens’ Bnd tool [6] is built on that premise that most of the manifest can be described in a terse domain specific language (DSL) and the rest can be filled in at the time when the bundle is assembled by introspecting the classes. A developer needs to carefully craft the OSGi manifest and update it whenever the code changes. Beyond that development tooling should help with test running the bundles and ideally have support for the OSGi programming models such as the component models. have most of the information needed to determine dependencies. Also.JAXenter. PDE’s greatest asset is also its greatest weakness: explicitness. Bnd also honors OSGi best practices such as generating uses directives for exported packages. Loosely related to IBM's free (but not open sourced) OSGi development tools [5] this project aims to integrate existing high quality Eclipse tools for JEE development with OSGi specific functionality as defined in the corresponding chapters of the OSGi Enterprise Specification. With this approach it also becomes trivial to convert third-party JARs into functional bundles (assuming they do not make assumptions about classloaders in the code. On the other hand. there is another more convenient option. which is to let most of the hard stuff (particularly the Import-Package) be generated. More than for just converting JAR files.com | May 2011 25 . It provides all the necessities of OSGi development such as a content aware bundle manifest editor and a compiler plugin that enforces OSGi visibility rules (unless side-stepped by a custom build path) and reports errors for missing imports. After all. [7]). Bnd and BndTools While PDE’s explicit approach to authoring manifests certainly works. for example using JPA end Servlet functionality in bundles. For developing more enterprise focussed OSGi applications.

It helps to create Maven 2 OSGi projects and define individual bundles. The older component model. The complete package includes very capable editors for defining bundles (even several for a single Eclipse project). However. setting up the right infrastructure for OSGi is a time-consuming process. which especially to a Maven novice can seem daunting. BndTools [8]. which pull classes from multiple sources. offers a full dependency injection framework. which greatly simplify using the OSGi dynamism and in particular OSGi services (or μServices as Peter Kriens has dubbed them [11]). The sample component uses zero or more StockProvider services. On top of that there are prebuilt templates for defining Declarative services components (Figure 1) and integration tests.StocksGui'/> <reference name='provider' interface='org.jar # Convert a plain jar to OSGi. At runtime components are defined in XML. Neil Bartlett has even created a complete Eclipse development environment. so the configuration options for defining bundles are the same as for using Bnd directly or through the BndTools. Fortunately.jaxlondon.0' name=' org. Maven with Felix Bundle plugin and Pax Construct The above projects are IDE centric or build agnostic.jar wrap -properties props. support for running a collection of bundles and even hot swapping code changes into the running framework. which are injected by the extender. The invocations below show very basic usage for converting a JAR to a bundle (Listing 1). allows the definition of service components.jar Component Models Finally. Apart from the syntax of the XML component descriptors perhaps the most notable difference between Declarative Services and Blueprint lies in how both expose OSGi service dynamics.bnd some. Declarative services expose dynamics directly to the client code. the Bnd tool also allows a simpler property syntax as well as annotations. based on Bnd. like Bnd.JAXenter. syntactically based on the popular Spring framework.osgi. Declarative Services.stocks.com | May 2011 26 .org/xmlns/scr/v1. Components can have dependencies on other services.2. Despite many advantages of Maven.jar print -manifest some. The Felix bundle plugin uses Bnd under the covers.A Tour Through the OSGi Tool Chain complex bundle assemblies.api. by showing the GUI } @Deactivate public void stop() { // deactivate the GUI } @Reference(type='*') public void addProvider(StockProvider provider) { // respond to a new provider } public void removeProvider(StockProvider provider) { // respond to a provider becoming unavailable } } <scr:component xmlns:scr='http://www.n' bind='addProvider' unbind='removeProvider' policy='dynamic'/> </scr:component> www.jar print -verify some.jaxlondon.jar java -jar bnd.gui.1. Blueprint. the Pax Construct project [10] provides a very useful starter kit. Listing 1 # Display the manifest of some. These two models absolve the developer from the responsibility of using the complicated OSGi API for services and in part can also hide some of the dynamism where it is not desired. Although the above example shows Bnd as a stand-alone command line tool. Pax Construct also has excellent support for launching a test OSGi environment from Maven.stocks.StocksGui' activate='start' deactivate='stop'> <implementation class='org. together with first class support for interacting with the OSGi service registry.jaxlondon. Some readers may be looking for a very mature build solution. especially when confronted with large OSGi applications. Maven as a build choice for OSGi projects offers significant freedom for choosing an IDE as all major IDEs feature Maven plugins. The properties file can be used # to configure imports. Built on top of that the BndTools have a set of nice editors and project templates for working with Declarative Services.StockProvider' cardinality='0. Also Maven’s dependency management aligns advantageously with OSGi concepts of modularity. it can be integrated into Ant or Maven builds. however the Apache Felix Bundle plugin adds that capability and is widely used across Apache projects. The code sample below shows an example of an annotated component and the equivalent (generated) XML. Two component models are standardized as part of the OSGi compendium specification and are in wide use. Maven itself does not come with direct support for OSGi packaging. which can dynamically be added or removed (Listing 2).gui. These components are plain Java classes that are instantiated as well as activated and deactivated by the Declarative Services extender. The newer component model.jar # Display any unresolved (non-imported) class package references java -jar bnd. bundle verification as well as launching a framework for running an application or running integration tests. which was introduced with OSGi Compendium Specification revision 4. no section on OSGi development would be complete without mentioning the component models. exports etc java -jar bnd.. A service that is injected via one method (addProvider Listing 2 @Component public class StocksGui { @Activate public void start() { // start the component. This can be found in the Maven [9] build infrastructure that is used across almost all Apache OSGi projects.stocks.

it can also be used with plain file URLs. "stocks-ftse-random". StockProvider.pax.stocks.stocks". A basic PaxExam test (using the 2.class. Note that even though there is only one @Test annotated method the given test class actually executes two tests: one on Equinox and one on Felix. ).0-SNAPSHOT").jaxlondon.StocksGui" init-method="start" destroy-method="stop"> <property name="providers" ref="providers" /> </bean> </blueprint> Listing 4 // Execute this unit test with the Pax Exam runner @RunWith(JUnit4TestRunner.apache. assertNotNull(provider).stocks". Testing with Pax Exam Sooner or later in the life of an OSGi the question arises of how to test integration between different bundles. In fact it will continue to operate until the component tries to use the required service in some way.aries.jaxlondon. the BndTools integration test configuration based on it and PaxExam [12]. mavenBundle("jaxlondon. which in this case test drives a Blueprint exposed service. Of course Blueprint also has support for letting components listen and react directly to service lifecycle events. is removed via another method (removeProvider in the example).0.aries.gui. Eclipse Equinox [14] and Knopflerfish [15]) and then use the default console www. Instead the task of deploying an OSGi application is complicated by the need first to bootstrap an OSGi framework and then to install and activate the application bundles plus all their dependencies.open(). mavenBundle("jaxlondon. "stocks-api". "1.StockProvider" availability="optional"> <reference-listener bind-method="addProvider" unbind-method="removeProvider" ref="gui" /> </reference-list> <bean id="gui" class="org.ops4j. for example to ensure that components are defined correctly. Deployment The question of deployment arises relatively early for OSGi projects. equinox() ).logging". so we use a service // tracker rather than exposing the test to a race condition ServiceTracker tracker = new ServiceTracker(bundleContext. StockProvider provider = (StockProvider) tracker.A Tour Through the OSGi Tool Chain Listing 3 <blueprint xmlns="http://www.org/xmlns/blueprint/v1. each offering a different way to accomplish the basic goal: launching a bundle with a number of JUnit tests in an OSGi framework with specific runtime bundles. Available choices include Bnd itself. tracker.waitForService(1000).0. junitBundles() mavenBundle("org. For example if a required service dependency becomes unavailable. Blueprint.0"> <reference-list id="providers" interface="org.com | May 2011 27 . } // Define the framework configuration(s) to be tested @Configuration public static Option[] configuration() { return options( frameworks( felix().apache. especially projects that use OSGi services (for example through one of the component models discussed above). The components can be quite thoroughly unit tested but some level of in-container testing is necessary. } } in the example). Through this service damping OSGi bundles built on Blueprint can remain oblivious to short outages (due to for example live updates) of their service dependencies while still enjoying the benefits of potentially continuous updates.getName().JAXenter. "pax-logging-api"). "org. a Blueprint bean is not stopped or notified. A component is deactivated when a mandatory service dependency goes away and re-activated when a replacement becomes available.0 branch) can look like Listing 4.blueprint".stocks. The Blueprint snippet in Listing 3 shows the Blueprint descriptor equivalent to the Declarative services descriptor shown before.0-SNAPSHOT"). null). "1. mavenBundle("org. However.blueprint"). As shown in the code Pax Exam works particularly well in conjunction with a Maven build infrastructure.class) public class ServiceTest { @Test // The bundle context gets supplied by Pax Exam public void apiBundleShouldBeStarted(BundleContext bundleContext) throws Exception { // the test bundle starts together with other bundles. At the simplest one can start each of the three common open source frameworks (Apache Felix [13] . Several options exist for running in-container tests. on the other hand.osgi. At that point the Blueprint container will pause to wait for a replacement service to become available and then continues the suspended method call on the service. With OSGi it is no longer enough to run the Java command with an appropriately long classpath and point to some main class. Of these the authors have found PaxExam with its annotation based configuration and stream-lined configuration DSL particularly elegant. attempts to hide some of these dynamics. The code snippet shows a simple integration test.

Application-Content: org. There is even a feature to deploy a full-fledged Spring dmServer runtime (see below). which provides a much more full-fledged proto-runtime while still being very light-weight and fast to start..3.blog. pax-run --platform=equinox --profiles=felix. all of which make working with Karaf a real pleasure. a custom enterprisey runtime that contains just the needed features can be bootstrapped in a breeze. Finally. remote access.apache.jpa.samples. org. or the Apache Aries repository generator [21]. So provisioning bundle A.aries. based on the Apache Felix Web Console [18].ds <bundles .apache. org. With a plentitude of predefined EE features. The key challenge for features and profiles are that they are oblivious to the declared bundle dependencies (Import-Package. This command bootstraps an Equinox framework. Especially.3.SNAPSHOT".apache.apache.JAXenter. JAAS based security and provisioning – not to mention an excellent and extensible shell (based on the Felix Gogo shell). to deploy a Web Application Bundle (WAB) one can simply install the ‘war’ feature.samples. Similar to the profiles that Pax Runner offers are Karaf features. then installs all the bundles required for the Apache Felix Declarative Services implementation and finally installs all the listed files as bundles into that runtime. profiles provide a number of very useful pre-built bundle selections for common capabilities such as a Declarative Services runtime. Karaf offers an OBR provisioner in the OBR feature.samples.3. URLs as well as simple provisioning text files that list bundle resources. This approach soon becomes highly inconvenient and does not help the accessibility of OSGi frameworks.api. for complex applications that use one or more of the compendium or enterprise specifications this way clearly is not an option. Karaf One step up from Pax Runner comes Karaf [17]. Pax Runner As an alternative to the basic native launch facilities of the individual OSGi frameworks.1.version="0. Fortunately there are various options both for easily bootstrapping custom slim OSGi runtimes as well as full enterprise strength pre-built runtimes. By default Karaf comes with excellent built-in support for the Blueprint component Listing 5 Manifest-Version: 1 Application-ManifestVersion: 1 Application-SymbolicName: org.aries.samples. An OSGi bundle repository stores not just bundle binaries but also their capabilities and requirements as extracted from the bundle manifest and possibly other sources (such as component descriptors etc).version="0. Require-Bundle etc) and hence the provisioning system cannot avoid duplication. available from Apache Felix OBR [19].aries.aries. org.SNAPSHOT". the Pax Runner project [16] provides a unified way to launch any of three open source frameworks (always with the default console installed) and to provision application and support bundles into that framework. One particularly nice option that deserves separate mention is the possibility of provisioning a web console.biz. which supports just package and bundle dependencies declared in the bundle manifest.1.eba Application-Version: 0.. which of course can also be installed separately in other runtimes. the war feature needs the servlet API and will install the Geronimo servlet API bundle regardless of whether the servlet classes are already available (at the right package version) in the runtime. will install A and a bundle that provides X (plus any additional transitive dependencies of that bundle). For playing around with OBR.A Tour Through the OSGi Tool Chain of the framework – all of which are different! – or the OSGi framework API to install further bundles. This has the benefit that the concrete selection of bundles that make up a feature can be tested reliably.persistence.3. Karaf features can also be used from Pax Runner through the custom ‘scan-features’ URL scheme. For example. A collection of public OBR repositories can be found at Apache Felix Sigil [22]. Note that in some cases prerequisites that are available by default in Karaf need to be added manually in a blank Pax Runner framework.jpa. Provisioning Pax Runner profiles and Karaf features rely on pre-defined collections of bundles. This makes starting a simple OSGi application a breeze.samples. which capture commonly needed functionality. The command below shows one particular invocation. In almost all cases the various runtime bits are completely runtime-independent – as one would expect from the components of a technology focussed primarily on modularity – and can be reused in any other of the runtimes.blog. An interesting alternative that does not suffer from this problem is the OSGi Bundle repository technology (OBR).apache. Generating bundle repositories can either be done via the Bindex tool [20].> model. However.version="0. The provisioner can use these and information about the current runtime to provision exactly what is needed.blog.3. this provisioning mechanism is not able to exploit the existence of capabilities in the runtime.web.1. which also generates capabilities and requirements for Blueprint defined services and references – this allows servicebased provisioning.0 Application-Name: Apache Aries Blog Sample EBA using JPA Application-Description: This EBA contains the sample Blog application. In particular there is a lot of flexibility in the URL scheme (through the embedded use of the Pax URL projects).blog.com | May 2011 28 . For example. Bundles can be provisioned from a variety of sources: files on disk.SNAPSHOT".blog. This is a powerful provisioning model that eliminates the need to exactly specify bundle combinations once and for all and shifts the brunt of the work to the provisioning system.SNAPSHOT" www.aries.1. bundles can be sourced directly from a Maven repository by its Maven coordinates. which depends on capabilities X and Y where Y is already available in the runtime.version="0.

However. Underlying those full fledged options are a number of Enterprise specifications.html [30] http://www. the descriptor for the Apache Aries Blog sample application is shown above. the core idea is the same between Geronimo and Virgo.org/ [28] http://wiki.ops4j.html [19] http://felix.apache. Spring or Web components.org/distributed-osgi.org/documentation/tools/repositoryGenerator. which is dynamic from the start. in some cases the benefit of a smaller runtime and faster startup time will not outweigh the extra effort required to manage what is essentially a light-weight app server runtime rather than taking a pre-defined all inclusive package. she completed a doctorate in quantum computation at the University of Oxford.apache. Valentin Mahrwald is a software engineer at the IBM Hursley Development Laboratory in Hampshire.org/site/apache-felix-sigil-obr.org/display/paxweb/Pax+Web [29] http://cxf.org/display/paxconstruct/Pax+Construct [11] http://www.html [8] http://njbartlett.osgi. For example how can I make two OSGi applications running in two different frameworks talk to each other? How easily can OSGi applications be distributed across multiple deployment systems? How can I connect an OSGi application to a legacy JEE application? Apache CXF and Tuscany provide some answers. She has also authored several developerWorks articles.name/2010/08/24/osgi-compliance-levels.html [23] http://geronimo.org/gemini/ [27] http://aries. He has over two years of experience working on WebSphere Application Server.org/ecf/ [31] http://tuscany. which is available from Pax Web [28] – for separate consumption (for example via Karaf. An OSGi application.org/space/Pax+Exam [13] http://felix.org/ [17] http://karaf.html [2] http://www.org/ [14] http://eclipse. Even though the application models are syntactically different.knopflerfish. most of this time spent on the OSGi Applications feature. For this Tuscany supports SCA (Service component architecture) components to be implemented by OSGi services.html [22] http://felix.A Tour Through the OSGi Tool Chain Pre-built enterprise stacks The runtime options presented so far were all concerned with simplifying the task of managing custom runtimes with just the features needed for the desired OSGi application and no excess baggage. She is a popular speaker and has spoken at a variety of industry events including Devoxx.html [12] http://paxexam. As an example. JNDI.ops4j. He is an active Apache Software Foundation committer in the Apache Aries project. Web and JPA.apache. Holly has been with IBM for nine years. Each of these supports different types of applications. References [1] http://njbartlett. Conclusion This brief tour has hopefully inspired the reader with the sense of how much the OSGi ecosystem has to offer.org/ [10] http://wiki. Similarly OSGi services defined as SCA components can declare references to and thus consume other SCA components as services. In this way such services can be consumed by other SCA components. The Great Indian Developer Summit. and WebSphere User Groups.aqute.osgi.name/bndtools.co/ai2GUy [6] http://www. With very simple metadata additions it allows two OSGi frameworks to be connected on the OSGi service levels.apache. Holly is a software engineer at IBM's Hursley labs.html [9] http://maven. amongst others Blueprint.eclipse.apache.org/ [24] http://eclipse. Apache CXF [29] is the reference implementation of the Distributed OSGi specification. defines the collection of bundles (and even configuration artifacts in Virgo’s plans) that logically define the application.org/ [18] http://felix. The ServerSide Java Symposium. Apache Tuscany [31] can be used to connect OSGi services to non-OSGi artifacts such as traditional Java.osgi. These are available as individual components from Eclipse Gemini [26] and also Apache Aries [27] – with the exception of the Web Application Bundle support.apache.net/ [26] http://eclipse.apache.org/ [16] http://paxrunner. There are three open-source options: Apache Geronimo 3. defined via an application manifest in Geronimo.apache.org/Repository/BIndex [21] http://aries. which are not necessarily implemented in OSGi. This only goes to show the maturity of the components and benefits of OSGi as a platform for modularity and reuse. She contributes to the Apache Aries project and to WebSphere feature packs. JavaZone. or a plan in Virgo.org/pde/ [4] http://www. Valentin holds a Masters degree in Mathematics and Computer Science from the University of York.JAXenter.org/site/apache-felix-osgi-bundle-repository.apache.eclipse. Eclipse Virgo [24] and Glassfish [25]. Before joining IBM.org/site/apache-felix-web-console.org/libra/ [5] http://ibm. This method of distribution fits very nicely with the OSGi service model.java.apache. which again need no longer be implemented in OSGi.com | May 2011 29 . for which he has also authored the accompanying IBM RedBook. different tools and frameworks is staggering. which has pre-defined features for the Aries components).eclipse.html [20] http://www. In the authors’ experience the amount of reuse between the various www.0 [23].ops4j.biz/Bnd/Bnd [7] http://njbartlett.ops4j.org/equinox/ [15] http://www.org/ Distribution Soon after the first steps of OSGi development are taken many people wonder how to connect things up.org/virgo/ [25] http://glassfish.org [3] http://www.apache.org/blog/2010/03/services. As with most OSGi specification implementations there is an Eclipse equivalent for distributed OSGi in the ECF project [30].name/osgibook.

the Apache and Eclipse communities presented their implementations of the OSGi Enterprise Specifications: • Apache Aries [7] • Eclipse Gemini [8] JPA model bundle description To make our description more comprehensible and vivid let’s dwell on our tutorial model. Eclipse Gemini).xml – Listing 2). is a list of the steps that are implemented in this tutorial: www. I should mention that this model is a simple structure of two classes (Student and Group – Listing 1) that are linked to each other in one-too-many bi-directional way. • development of JPA model OSGi bundle with persistence.0. The Java Persistence API (JPA) is a specification that provides developers with a way to map objects to managing relational data in Java based environments. Here we add a persistence description file (persistence. (The tutorial does not cover any optional functionality like external transaction managers) Short overview of the tutorial steps Beneath. JPA 2.Persistence Tutorial: Using JPA in an OSGi environment OSGi and JPA The tutorial below is a simple guide to developing and running JPA code in diverse OSGi environments (Eclipse Equinox. There are three broadly-known JPA open-source providers in the market: 1. OpenJPA) and OSGi Enterprise API implementations (Apache Aries. Knopflerfish) with various JPA providers (Hibernate. JPA is a part of Java Enterprise Edition 5 and 6 [2] the latest version of which is 2.0 annotations are used to describe persistence entities and named queries.to set transaction type explicitly. xml • JPA model bundle tuning for different JPA providers • development of JPA client bundle • bundles configuration for Eclipse Gemini with EclipseLink • bundles configuration for Apache Aries with OpenJPA • build Hibernate OSGi bundle • bundles configuration for Apache Aries with Hibernate • build EclipseLink activation bundle • bundles configuration for Apache Aries with EclipseLink • bundles configuration for standalone EclipseLink JPA and OSGi: known facts. refer to [1].JAXenter.com | May 2011 30 . EclipseLink [4] 3.2 in March 2010 [6]. EclipseLink. It contains the list of model classes and some tutorial-specific settings: • transaction-type="RESOURCE_LOCAL" . Afterards. Apache Felix. OpenJPA [5] The JPA Service Specification was first introduced in OSGi Enterprise Specification 4. Hibernate [3] 2. please. By Dmytro Pishchukhin If you are interested in the source code used in this tutorial.

@Id @GeneratedValue(strategy = GenerationType. mappedBy = "group") private List<Student> students. query = "SELECT DISTINCT record" + " FROM Student record" + " ORDER BY record. private String name. } public int getId() { return id. } public void setGroup(Group group) { this. } public void setLastName(String lastName) { this.name = name. public static final String GET_STUDENT_BY_ID = "GET_STUDENT_BY_ID".firstName = firstName. this. } public void setFirstName(String firstName) { this. } public String getLastName() { return lastName. } } www.IDENTITY) private int id. public Group() { } public Group(String name) { this. } public int getId() { return id.JAXenter. } public String getName() { return name. Group group) { this. } public void setName(String name) { this.ALL.IDENTITY) private int id. @OneToMany(cascade = CascadeType. @ManyToOne(optional = false) private Group group.id = :studentId") @Entity @Table(name = "STUDENTS") public class Student { public static final String GET_STUDENTS = "GET_STUDENTS". public Student() { } public Student(String firstName. query = "SELECT DISTINCT record" }) + " FROM Student record" + " WHERE record.GET_STUDENTS. String lastName.Persistence Listing 1: Group and Student classes @NamedQueries({ @NamedQuery(name = Group.GET_GROUP_BY_ID. query = "SELECT DISTINCT record" + " FROM Group record" + " ORDER BY record.group = group. } public String getFirstName() { return firstName.lastName"). query = "SELECT DISTINCT record" + " FROM Group record" + " WHERE record.name"). } public void setStudents(List<Student> students) { this. } } @NamedQueries({ @NamedQuery(name = Student.GET_STUDENT_BY_ID.students = students.com | May 2011 31 .group = group.firstName = firstName. private String lastName. @NamedQuery(name = Student. @NamedQuery(name = Group.GET_GROUPS. @Id @GeneratedValue(strategy = GenerationType.lastName = lastName. } public Group getGroup() { return group.name = name.lastName = lastName. public static final String GET_GROUP_BY_ID = "GET_GROUP_BY_ID". private String firstName.id = :groupId") }) @Entity @Table(name = "GROUPS") public class Group { public static final String GET_GROUPS = "GET_GROUPS". this. } public List<Student> getStudents() { return students.

jdbc.tips.PCEnhancer – add OpenJPA-specific properties to persistence.persistence.javax.ddl-generation. Every JPA provider needs minor fine-tuning of the model bundle.proxy – add Hibernate-specific properties to persistence.persistence.xml <persistence version="1.jdbc.model </Export-Package> <Import-Package> javax.hibernate.knowhowlab.url .javassist.xml: .1.w3.database generation mode .connection.jpa.apache.database generation target • OpenJPA profile: º name: openjpa º run command: mvn clean install -P openjpa º details: – add to imported packages: org.jdbc).6 </Bundle-RequiredExecutionEnvironment> </instructions> </configuration> • EclipseLink profile: º name: eclipselink º run command: mvn clean install -P eclipselink º details: – add to imported packages: org. The file should be stored under META-INF/persistence. enhance.knowhowlab. (maven-bundle-plugin configuration .tips.Persistence • <exclude-unlisted-classes>true</exclude-unlisted-classes> – to disable scanning of persistence unit by persistence provider and attach only classes that are explicitly listed.model • Meta-Persistence: META-INF/persistence.dialect .url .eclipse. Maven profiles were added to meet these requirements: Listing 2: persistence.0".derby.database dialect .sun.Group</class> <exclude-unlisted-classes>true</exclude-unlisted-classes> </persistence-unit> </persistence> Listing 3: Model bundle maven-bundle-plugin configuration <configuration> <instructions> <Export-Package>org.version="1. A list of available commands (they all are listed with console “help” command): • lsstuds – print student records • lsgrps – print group records • delgrp <id> – delete group record by ID • delstud <id> – delete student record by ID • addgrp <name> – add group record • addstud <first_name> <last_name> <group_id> – add student record www.database JDBC driver class name .xml: . As an alternative.com/xml/ns/persistence" xmlns:xsi="http://www.hibernate.packages} </Import-Package> <Meta-Persistence>META-INF/persistence.jpa.jpa="2.hbm2ddl.jpa.0" xmlns="http://java.javax.0" to import JPA packages with required JPA version • Export-Package should export model package: org.SynchronizeMappings – run mapping tool to create database • Hibernate profile: º name: hibernate º run command: mvn clean install -P hibernate º details: – add to imported packages: org.JAXenter.com | May 2011 32 .model.tips.Student</class> <class>org.apache.apache.hibernate.javax.eclipselink.database connection URL JPA client bundle description A client bundle represents a simple console application that uses EntityManager to manipulate with the JPA entities that are provided by the model bundle.${extra.persistence.database generation actions .apache. org.1.openjpa.hibernate.derby.jpa.openjpa.xsd"> <persistence-unit name="jpa.ddl-generation . The application is integrated into OSGi frameworks console commands with universal shell adapters [9].jdbc.javax.jdbc. indirection – add EclipseLink-specific properties to persistence.sun.org.util – enhance model classes with org.tips.model.0".apache. proxy.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.students" transaction-type=" RESOURCE_LOCAL"> <class>org.enhance.util.persistence.auto .sun.openjpa.driver .com/xml/ns/persistence/persistence_1_0.xml </Meta-Persistence> <Bundle-RequiredExecutionEnvironment> JavaSE-1.version ="1.database-specific connection URL .url – database-specific connection URL . this is org.com/xml/ns/persistence http://java.0".Listing 3).knowhowlab.persistence.xml – is a relative path to persistence description file • Import-Package could contain used JDBC driver package (in our case.xml path. The next step for the model is to pack all classes into OSGi bundle.jpa="2.openjpa.knowhowlab.jdbc.output-mode .jdbc.driver – database JDBC driver class name .persistence.xml: .persistence. this package could be imported by client bundle to decouple model from JDBC drivers.eclipselink. The most important OSGi MANIFEST headers are: • Import-Package should contain javax.

0. dbaccess.osgi*.jpa="2.persistence/org. EntityManager em = emf.JAXenter.basedir}/libs/gemini/org. } catch (Exception e) { transaction.0" to import JPA packages with required JPA version • Import-Package should contain model package: org.1.close().0" </Import-Package> <Bundle-Activator> org.apache.persistence. try { EntityManagerFactory emf = (EntityManagerFactory) bc. } else { throw new Exception("EntityManagerFactory is not available"). jpa_1.1</param> <param>mvn:org.apache.org.0</param> <param>mvn:org.class.eclipse. if (serviceReferences != null && serviceReferences.gemini.eclipse.jpa.osgi.RC1.derby_1.0. EntityManagerFactoryBuilder.0-SNAPSHOT</param> <param>mvn:org.0.println("Group name param is missed").knowhowlab.compendium/4.jar</param> <param>mvn:org.Persistence JPA Service Specification (OSGi Enterprise Specification) describes that EntityManagerFactory service should be registered for every pair: Persistence Unit and Persistence Provider.0".. derby_10.2.0.eclipse. transaction.knowhowlab.begin().basedir}/libs/gemini/org. The client bundle OSGi configuration is represented below (maven-bundle-plugin configuration – Listing 5). args) { if (args == null || args.println(String.printStackTrace(out). EntityTransaction transaction = em.antlr/2.persistence. } em. String. Group group = new Group(args[0]).persistence/org. } } Listing 4: Client bundle code snippet private static final String STUDENTS_UNIT = "jpa.printStackTrace(out).jpa. javax.core/2.gemini. try { transaction.eclipse.gemini.client.jar@nostart</param> <param>file:///${project.length > 0) { return serviceReferences[0].M1-incubation.geronimo. The most important OSGi MANIFEST headers are as follows: • Import-Package should contain javax. return.2.eclipse.getTransaction(). em.0.ungetService(reference).version= "1.eclipse.tips.0_spec/1.1.jar</param> <param>file:///${project.tips.model Gemini with EclipseLink configuration The Gemini JPA project depicts modular implementations of Java Persistence API technology.JPA_UNIT_NAME.basedir}/libs/gemini/org.1.getName(). } Listing 5: Client bundle maven-bundle-plugin configuration <configuration> <instructions> <Export-Package/> <Import-Package> org.getService(reference).tips.eclipse.model.Activator </Bundle-Activator> <Bundle-RequiredExecutionEnvironment> JavaSE-1.osgi/org.0</param> <param>mvn:org.jar</param> <param>file:///${project. This project currently pro} catch (Exception e) { e.eclipse.0.RC1.0-SNAPSHOT</param> www.0</param> <param>file:///${project.knowhowlab.com | May 2011 33 .getServiceReferences(EntityManagerFactory.5.jpa/client/1. } } public void addgrp(PrintWriter out.2. private ServiceReference getEntityManagerFactoryServiceReference() throws Exception { ServiceReference[] serviceReferences = bc. e.createEntityManager().format("Group is persisted with ID: %d".knowhowlab.tips.length != 1) { out. out.0. weaving_1.eclipse.eclipse.commit().persistence.6</Bundle-RequiredExecutionEnvironment> </instructions> </configuration> Listing 6: Gemini JPA OPS4J Pax Runner configuration <param>mvn:org.eclipse. group.0</param> <param>mvn:org.jpa/model/1.getId())).persistence/org..students".format("(%s=%s)".2.0. String.2. STUDENTS_UNIT)).tips.osgi/org.persistence.version="1.0</param> <param>mvn:org.basedir}/libs/gemini/org.persistence.jpa. In the client bundle on every command call we use EntityManagerFactory service instance that is available in OSGi registry (Client code sample – Listing 4).jpa. } try { ServiceReference reference = getEntityManagerFactoryServiceReference().persistence/org.asm/2.osgi.enterprise/4.persistence.rollback().2.0</param> <param>mvn:org.persist(group).specs/geronimo-jpa_2.jpa/2.1.knowhowlab. } finally { bc.

@Override public void start(BundleContext context) throws Exception { HibernatePersistence persistence = new HibernatePersistence().util/0.javax.2.osgi/org.0</param> <param>mvn:org.ant* </Import-Package> <!-.0_spec/1.1@nostart</param> <param>mvn:org.openjpa/openjpa/2.5.0-SNAPSHOT</param> <param>mvn:org. String>().knowhowlab.servicemix.com | May 2011 34 .sun.apache.derby/derby/10.0</param> <param>mvn:org.tips.slf4j.0</param> <param>mvn:org.naming*.apache.osgi.knowhowlab.getClass().0-SNAPSHOT</param> <param>mvn:org.3</param> <param>mvn:org.0.jpa/model/1.sql. } @Override public void stop(BundleContext context) throws Exception { serviceRegistration.org.xml.0".aries.1_spec/1.aries.apache.0-SNAPSHOT</param> <param>mvn:org.apache.apache.osgi.!javax.aries.apache. persistence.6.getName().class.3</param> <param>mvn:org.aries.datatype.jpa/org.slf4j/slf4j-simple/1.registerService (PersistenceProvider. org.org.dom.apache.relaxng.1_3</param> <param>mvn:org.geronimo.container/0.0".!net.transaction/org.aries.tips.slf4j/slf4j-simple/1.!javax.collections*.1.transaction*.1@nostart</param> <param>mvn:org.persistence*. props.0.-split-package:=merge-first.1</param> <param>mvn:org.knowhowlab.7.transaction.serp/ 1.validation*.osgi/org.aries.7. private ServiceRegistration serviceRegistration.hibernate*.getName()).put(JAVAX_PERSISTENCE_PROVIDER_PROP.jpa. } } Listing 10: Aries with Hibernate configuration bundles <param>mvn:org.1</param> <param>mvn:org.jaxen*.apache.bundles/org.provider".tips.apache.org.apache.3</param> <param>mvn:org.bundles.bundles.1</param> <param>mvn:org.api/0.apache.sf.0</param> <param>mvn:org.apache.jpa/org.!org.sax*.apache.aries.jpa.tools.6.gjt.inline=true </Embed-Dependency> www. !org.cglib*.1.servicemix.objectweb*.enterprise/4.jpa/client/1.swing*.jpa.3</param> <param>mvn:org.apache.apache.1</param> <param>mvn:org.1.3</param> <param>mvn:org.1.aries. datatype*.6.version="1.derby/derby/10.knowhowlab.aries.inline=true.0-SNAPSHOT</param> </instructions> </configuration> Listing 9: Hibernate bundle Activator public class Activator implements BundleActivator { private static final String JAVAX_PERSISTENCE_PROVIDER_PROP = "javax.sun.apache.apache.0.aries/org.!org.1</param> <param>mvn:commons-collections/commons-collections/3.tips.4</param> <param>mvn:commons-lang/commons-lang/2.apache.security*.osgi*. String> props = new Hashtable<String. Dictionary<String.Persistence Listing 7: Aries with OpenJPA OPS4J Pax Runner configuration <param>mvn:org.0.javax.*.osgi.!com.3</param> <param>mvn:org.0. !org.!com.aries.bundles/org.unregister().servicemix.msv. props).knowhowlab.2.version="1.v1.apache.jpa/client/1.jpa.5</param> <param>mvn:commons-dbcp/commons-dbcp/1.1.Import JDBC drivers dynamically --> <DynamicImport-Package>*</DynamicImport-Package> <Bundle-Activator>org.aries.osgi/org.enterprise/4.compendium/4.apache.w3c.servicemix.0-SNAPSHOT</param> Listing 8: Hibernate bundle configuration <configuration> <instructions> <Export-Package>org. javax.compendium/4.6 </Bundle-RequiredExecutionEnvironment> <Embed-Dependency>antlr.commons.transaction/org.0</param> <param>mvn:org.xml.xpp.slf4j/slf4j-api/1.apache.aries.geronimo.1.aries/org.0_spec/1.javax. persistence.6.jpa/hibernate/1.13.specs/geronimo-jpa_2.6</param> <param>mvn:org.jdi*.slf4j/slf4j-api/1.jpa/org. serp/1.api/0. !javax.osgi/org.1</param> <param>mvn:org.apache.apache.persistence.tips.3</param> <param>mvn:org.1</param> <param>mvn:commons-collections/commons-collections/3.dom4j.!org.!org.xmlpull.jpa.util/0.javax.1</param> <param>mvn:org.2.osgi.aries.apache.javassist* </Export-Package> <Import-Package> org. serviceRegistration = context.jpa/org.specs/geronimo-jpa_2.JAXenter.aries.container/0.13.2.manager/ 0.apache.apache.jpa/model/1.apache.knowhowlab.tips. manager/0.specs/geronimo-jta_1.transaction.Activator </Bundle-Activator> <Bundle-RequiredExecutionEnvironment>JavaSE-1.3</param> <param>mvn:org.2.hibernate.2.apache.1_3</param> <param>mvn:org.geronimo.1</param> <param>mvn:commons-pool/commons-pool/1.

unregister().eclipse. serviceRegistration = context.1.eclipse.0</param> <param>mvn:org. Though EclipseLink project delivers OSGi bundles.1</param> <param>mvn:org.osgi.bundles. Listing 12 shows a list of configuration bundles. persistence.1</param> <param>mvn:org. persistence.jpa/model/1.13.7.3</param> <param>mvn:org.eclipse.persistence/org.persistence. } @Override public void stop(BundleContext context) throws Exception { serviceRegistration.getName()).manager/ 0.jpa/client/1.persistence.1</param> <param>mvn:org.PersistenceProvider persistence = new org.jpa.eclipse.eclipse.compendium/4.container/0.2.aries.0-SNAPSHOT</param> <param>mvn:org.apache.knowhowlab.6.apache.2.0</param> <param>mvn:org.knowhowlab.transaction.3</param> <param>mvn:org.servicemix.api/0.aries. @Override public void start(BundleContext context) throws Exception { org.apache.1@nostart</param> <param>mvn:org.getName(). props).eclipse.registerService(PersistenceProvider.0</param> <param>mvn:commons-collections/commons-collections/3.slf4j/slf4j-api/1.apache.persistence/org.6.2.asm/2. we have to create it ourselves with maven-bundleplugin using a simpler version of configuration described by Peter Kriens [10] (Listing 8).tips. Apache OpenJPA is a Java persistence project at The Apache Software Foundation that can be used as a stand-alone POJO persistence layer or integrated into any Java EE compliant container and many other lightweight frameworks.jpa.serp/ 1.0 but it can be used as well. } } Listing 12: Aries with EclipseLink configuration bundles <param>mvn:org.osgi.put(JAVAX_PERSISTENCE_PROVIDER_PROP.apache.transaction/org. Listing 7 shows a list of configuration bundles. you can find a list of configuration bundles: Aries with OpenJPA configuration The Aries project delivers a set of pluggable Java components enabling an enterprise OSGi application programming model. if you do not Listing 11: EclipseLink bundle Activator public class Activator implements BundleActivator { private static final String JAVAX_PERSISTENCE_PROVIDER_PROP = "javax.0</param> <param>mvn:org. The other point that we have to achieve is an activation of Hibernate Persistence Provider that will be available for Aries (Listing 9).geronimo. we have to activate EclipseLink Persistence Provider to make it available for Apache Aries (Listing 11). Hibernate EntityManager project implements Standalone EclipseLink It is possible to use EclipseLink as a standalone OSGi JPA provider.0.aries.PersistenceProvider().osgi/org.persistence/org.3</param> <param>mvn:org.3</param> <param>mvn:org.class.2.persistence.apache.servicemix. It failed with some class loading exception.apache.apache. Aries with Hibernate configuration Hibernate is an Object/Relational Mapping solution for Java environments.Persistence vides the integration with the EclipseLink JPA provider to support the OSGi JPA specification approach that clients can use to get JPA support in an OSGi framework.getClass().1</param> <param>mvn:org.jpa/2.JAXenter. the programming interfaces and lifecycle rules as defined by the JPA 2.aries.apache.0-SNAPSHOT</param> www.jpa/org. String>().aries/org.persistence/org.apache.0.bundles/org.1_3</param> <param>mvn:org.eclipse.aries.eclipse.tips.0-SNAPSHOT</param> <param>mvn:org.apache.eclipse. Aries with EclipseLink configuration The Eclipse Persistence Services Project (EclipseLink) delivers a comprehensive open-source Java persistence solution. private ServiceRegistration serviceRegistration. Dictionary<String.util/0. All tests of this configuration are passed except Knopflerfish OSGi framework test. String> props = new Hashtable<String.2.enterprise/4. props.aries. This includes implementations and extensions of application-focused specifications defined by the OSGi Alliance Enterprise Expert Group.persistence.2.jpa.jpa.aries. The latest released version 1.core/2.derby/derby/10. The EclipseLink JPA provides developers with a standards based Object-Relational persistence solution with additional support for many advanced features.0</param> <param>mvn:org.eclipse. This solution has been announced as deprecated since version 2.jpa/eclipselink/1.antlr/2.specs/geronimo-jpa_2.com | May 2011 35 . Listing 10 shows a list of configuration bundles.tips. In accordance with the fact that the Hibernate community does not supply Hibernate engine with OSGi bundle MANIFEST.osgi/org.0</param> <param>mvn:org.knowhowlab.0RC1 (25 March 2011) requires JDBC Service Specification (implemented by Gemini DBAccess) to access database and supports only Equinox as OSGi framework.2.persistence.2.slf4j/slf4j-simple/1.persistence.0_spec/1.provider".persistence.0 specification.0.apache. In Listing 6.jpa/org.

persistence/org.3 passed passed passed Standalone EclipseLink 2. I would like to emphasize that the presented tutorial is only a starting point to use JPA in your OSGi environment.com/p/osgilab/wiki/ UniversalShell [10] Using Bnd To Do a Quick Wrap of Hibernate: http://www.hibernate.tips.0-SNAPSHOT</param> OSGi framework/ Configuration Equinox 3.compendium/4.jpa/client/1.0.persistence/org.org/eclipselink/ [5] OpenJPA provider: http://openjpa.) and support of different databases. Consequently.com/javaee/6/tutorial/doc/ [3] Hibernate JPA provider: http://www.tips.6.knowhowlab.2.eclipse.knowhowlab.eclipse.eclipse.apache.0</param> <param>mvn:org.0</param> <param>mvn:org.xml -P <osgi_framework> Available configurations: • gemini • aries-eclipselink • aries-openjpa • aries-hibernate • eclipselink Available OSGi frameworks: • equinox • felix • kf Dmytro Pishchukhin is a consultant with over a decade extensive experience in Java.eclipse.7.eclipse.org/ [6] OSGi Specification Release 4 Version 4.com/dpishchukhin/org. You can see a list of configuration bundles in Listing 13.persistence.).osgi.oracle.apache.0 passed passed passed Listing 13: Standalone EclipseLink configuration bundles <param>mvn:org.0. The configurations can be run with: mvn -f pom_<configuration>.2: http://www. Run configurations and tests result One of the main goals of the tutorial is to prove.org/ [14] OSGi Support in JPA 2.g.0 [13] Table 1: Test results Eclipse Gemini 1.org/equinox/ [12] Apache Felix OSGi framework: http://felix.org/ [13] Knopflerfish OSGi framework: http://www.org. Conclusion Summing up everything above.knowhowlab.2.eclipse. JNDI etc.0</param> <param>mvn:org.2 [11] Felix 3.persistence/org.eclipse. Data Source Factories.0</param> <param>mvn:org. external transactions etc. In this tutorial five different JPA configurations were created and every configuration was tested with three OSGi frameworks. that there is a feasible and easy way to run the same JPA model and client bundles with various configurations.jpa/2.com | May 2011 36 . telematics.org and www.0</param> <param>mvn:org.jpa [2] JEE 6 tutorial: http://download. we can speak about plenty of things that can be added and tested with the provided configurations: JPA provider features (e.2.apache.0RC1 passed not supported not supported Apache Aries 0. One extra header has been added to the model bundle to make Persistence Units available for the following EclipseLink configuration: JPA-PersistenceUnits: jpa.eclipse.2. Blueprint.persistence.persistence/org.persistence.specs/geronimo-jpa_2.jpa/model/1.ly/lfykXs Apache Aries 0.3 with EclipseLink 2.0-SNAPSHOT</param> <param>mvn:org.1</param> <param>mvn:org.1.osgi. cache.eclipse.apache. JEE.enterprise/4.knowhowlab.0 Persistence Providers: http://bit.org/gemini/ [9] Universal OSGi shell adapters: http://code.2.1.tips. Germany.osgi. train industry.2. smart-house.6.persistence/org.0 passed passed ClassLoader issues www.knopflerfish.geronimo.eclipse.0 passed passed passed Apache Aries 0. Dmytro currently resides in Frankfurt am Main.eclipse. References and useful links [1] Tutorial Sources: https://github.0</param> <param>mvn:org.core/2.0</param> <param>mvn:org.g.google. OSGi.eclipse.2.1</param> <param>mvn:org. He took a part in many OSGi projects for different markets: automotive.aqute.ly/8Yf4Vd [15] JPA persistence in OSGi with openJPA: http://bit.JAXenter.osgi/org.2.0 [12] Knopflerfish 3.osgi/2.osgi/org.biz/Code/ BndHibernate [11] Eclipse Equinox OSGi framework: http://eclipse.apache.derby/derby/10.2.0_spec/1.3 with OpenJPA 2.org/ [4] EclipseLink JPA provider: http://www.persistence.students The test results are depicted in Table 1.2.1.ly/kCnbps [16] OpenJPA and OSGi: http://bit.org/Download/ Release4V42 [7] Apache Aries project: http://aries.org/ [8] Eclipse Gemini project: http://www.persistence. ops4j.asm/2.3 with Hibernate 3. OSGi Enterprise features (e.Persistence feel like adding any extra libraries to support JPA. He is a member of open-source projects related to OSGi technologies: www.antlr/2.

New green The Nature of Complexity We live in a complex world. Long term volatility driven by mergers and acquisitions. 66% of all IT projects either fail outright or take much longer to install than expected because of their complexity. out-sourcing and in-sourcing initiatives? • Despite numerous initiatives.5 billion annually. Supporting similar conclusions of this earlier NIST study. waves of offshoring. If left unchecked. The conclusions are inescapable.S. are operational maintenance costs continuing to increase? As will be shown. secure and low cost business systems? • Is your environment able to efficiently scale to meet unpredictable volumes caused by increasingly volatile markets? • Are you able to quickly adapt business systems to meet new market opportunities? • Is on-going fragmentation of your business value chain a challenge for your legacy stove-piped business processes? • Is the operational environment volatile? Short term volatility caused by infrastructure failures. each node within each network itself a complex system of interrelated parts. on-shoring. According to the Standish Group [1].JAXenter. Via encapsulation we partition reality into distinct entities. a typical programmer writes between 8 and 20 lines of new code a day. The NIST study concludes that software errors cost the U. The Cost of Complexity – The Harsh Realities Large organizations have IT systems that comprise of thousands of applications: these highly complex environments comprising of a large number of tightly coupled network components running 10’s or even 100’s of millions of lines of code. a world comprised of diverse ecological. 98% fall short of meeting their business objectives. developer productivity has plummeted. instead referring to these entities by simple descriptions. economy an estimated $59. Meanwhile it is not unusual for several thousand application changes a week to be driven by a continuous flow of new business requirements. Such environments are heterogeneous and volatile. estimates that ongoing maintenance accounts for 92% of the total lifetime cost of each application: see slides 9 & 10 – SOA Symposium: Berlin.Modularity OSGi and the Enterprise? The Cure for Complexity OSGiTM is the dynamic module system for JavaTM.com | May 2011 37 . Applications become obsolete and need to be replaced (obsolete technology. software faults and operational errors. commercial and social networks. October 2010. frequent strategy changes. but what is its relevance to the modern enterprise? By Richard Nicholson To answers this question. Meanwhile. As a result. a 2002 study by the National Institute of Standards and Technology (NIST [3]) reports that developers spend nearly 80% of their time fixing bugs. If your business systems are Java based. agile.e. reflect for a moment upon the challenges most likely faced by your own organization: • Do your customers demand highly reliable. endof-life applications). For IT projects costing over $10m apiece. Figure 1: On average amount of software doubles every 7 years – see [2] www. we modularize reality. application modularity is the key stone required to successfully addresses these issues. recent work by Anne Thomas Manes (a Senior Gartner Research Analyst). i. an organizations’ business systems will continue to deteriorate. if left unchecked environmental complexity and operational costs will continue to spiral. then OSGi technology will be central to this strategy. Accounting for this debugging overhead. We make sense of this complexity through the processes of encapsulation and abstraction.we mask the internal complexities of these entities. political. field applications run side-by-side with applications that have been in operational use for 30-40 years. Via abstraction. The economic cost of such IT complexity is hard to quantify but probably exorbitant.

OSGi adoption spans the embedded device market. Large monolithic applications may be broken into a number of local or remote interconnect OSGi Services. To directly address environmental complexity one must also embrace application modularity. The OSGi Alliance Accidental Complexity? The term ‘Accidental Complexity’ is frequently used but rarely adequately defined. Since 1999 the OSGi Alliance [5] has successfully created and shepherded a portfolio of OSGi standards. as these modules perform a few. which directly leads to increased maintainability.JAXenter. specific functions. This realization has. so allowing a more modular runtime environments. The modern archetype for modularity and assembly is the automotive industry. • Service Oriented Architecture (SOA) – The move from business systems rigidly coupled with proprietary protocols to “services” accessed via common protocols. Whatever the product. sometimes unknowingly. modularity and assembly results in the mass production of affordable automobiles.com | May 2011 38 . underpinned a number of recent technology trends including: • Business Process Management – The codification and modularization of business workflow. • The deliverables from each development team can be independently versioned. the impact of change is localized to each module and prevented from leaking into the wider system. modularity directly facilitates efficiency increases in the development process. Modularity localizes the impact of change. Meanwhile each Service may be comprised of one or more OSGi bundles. they are much easier to exhaustively unit test: the working modules then simple assemble into a full application for integration testing. or a single function. as long as the service interfaces are maintained. the Eclipse IDE framework used by millions of Java developers and mission critical ISV middleware products used by some of the largest of enterprise environments. As with traditional coarse-grained Service Oriented Architectures. reduce cost and increase output. • In a composite system. without worrying about their internal details. Modularity and Assembly Modularity is the cure for complexity. Accidental Complexity can be simply defined as the difference between a given structure and the simplest possible alternative that interacts with the external world in exactly the same fashion. OSGi enables application modularity. • Finally. individual services may be rapidly evolved An old Idea The concept of assembling a product from a set of well-defined re-usable components is not new. As complexity is an issue at all structural levels. each a rotting code-base that drives environmental complexity. • By allowing parallel engineering teams to concurrently work on different modules within the same system. where extensive use of standardization. the driver for modularity and subsequent assembly is to. • As long as the module boundaries are invariant. in two distinct ways: • ‘SOA inside’ – OSGi Services interact with each other via local or distributed OSGi service registries in a dynamic manner. increase and maintain quality. in 2011. along with its relationship to other modules within the system. Now. Yet in each of the above transformations the underlying application portfolio remains untouched. These other modules may be treated as “black boxes” that perform OSGi™ the dynamic module system for Java™ For JavaTM based applications. providing reference implementations and guidance to the industry. www. OSGiTM is the industry standard for modularity and dynamic assembly. Indeed its roots can be traced back to at least 250BC with emperor Qin Shi Huang and his commissioning of the Terracotta Army [7]. accidental complexity (unnecessary structure) accretes over time.Modularity Figure 2: OSGi technology enables modularity and re-use via two complementary mechanisms. • Cloud Computing – The decoupling of applications from the underlying compute resources upon which they run. expanding the scope of OSGi specifications. so modularity must be applied at all structural levels [4]. knowledge is only required for the particular module being worked upon. Left unchecked.

test. well-contained projects have a higher success rate than larger and more poorly constrained projects. Resource Utilization Traditional monolithic applications lack information concerning required software libraries. For an organization with several hundred developers the cost savings are considerable: the potential to reduce memory footprint in production potentially resulting in even more substantial savings. with corresponding reduction in required machine memory. By enabling industry standards based modularity. each individual can independently work on small well-defined and decoupled modules. prior versions of an application may be rapidly reconstituted. developers typically load every possible library into their IDE: driving development. each of which may be independently maintained. OSGi bundles tend to be small.JAXenter. Hence OSGi is a natural technology partner to the agile development techniques adopted in recent years by many organizations. With the appropriate organizational incentives in place to encourage re-use over code creation. Finally. In contrast. enhanced and used outside its initial context. It is therefore a simple task to answer questions like: • Which software licenses are used? • Which production applications are at risk from a third party library with an identified security vulnerability? The structure of a composite application may be rapidly mapped by any OSGi literate engineer. which operational metrics indicate that the strategy is succeeding? 1. cohesive and de-coupled significantly reducing development and debug time. or out of date configurations. further significant efficiencies are realized by cross team re-use of OSGi bundles and services. an organization naturally moves away from high-risk water-fall product release processes towards lower-risk incremental feature releases. rather it is explicitly defined by OSGi metadata.e. and so systematically driving accidental complexity out of each application and so over time. with an increased likelihood that some issues are not found and will leak into production. Product Delivery By embracing modularity. 5. Each OSGi Service may be comprised of one or more OSGi bundles modules.com | May 2011 39 . this offering great value to those organizations that are required to validate the past behavior of a business system to a regulatory authority. one silo at a time: so increasing op- OSGi – The Business Benefits Having embarked upon an OSGi based application transformation strategy. Operations respond to this challenge by maintaining a number of isolated horizontal production silos. and maintenance. Enhanced IT Governance Structural information is no longer locked away within key members of staff. 7. Hence monolithic applications may be broken into a number of Services. the environment as a whole. the local or remote services with which they interoperate. Developer Efficiency . once dependencies are understood and mechanisms are in place so that only required libraries are automatically loaded. developers are forced to rely upon unit and integration tests that run during the nightly build cycle. i. This coupled with the long developer diagnostic/fix cycles. In this manner. as compile times may be many hours. This directly translates to increased project delivery success rates. UAT and Production memory requirements much higher than actually required. common infrastructure or processing logic code may be encapsulated within a set of commonly used OSGi bundles and re-used across many OSGi Services. • Java Modularity – OSGi also provides the software industries modularity standard for Java.parallelism and agility Developing a monolithic application requires multiple developers to concurrently work and test against the complete application code-base. As a result. results in production outages and instabilities that may spans several working days or even weeks. In response. upgrades are complex and high risk. run. 6. attempting to ensure service availability by releasing new software. In contrast. 3. this significantly reducing the amount of forensic work needed to decipher and understand an application’s code-base: so decreasing operation risk associated with loss of key development personal. Reducing Operational Risk Increasing Business Agility As the internal structure of monolithic applications is poorly understood. Courtesy of this metadata. increasing code re-use. It’s not necessary to understand the whole system inside-out. 4. This in-turn causes bug detection and rectification cycles to take days.Accelerated compile. However. a module at a time. 2. the number of artifacts may be reduced by an order of magnitude. reversing design rot. by breaking large monolithic applications into composite applications comprised of a number of independent modules. the structure of each composite application is known. a modular system lends itself well to many hands being involved in its development www.Modularity and re-factored without affecting their environment. as small. OSGi technology provides the foundations for any business IT transformation program whose primary aim is to reduce environmental complexity and so medium term application total cost of ownership. Maintenance From an ongoing maintenance perspective it is now possible to re-factor a composite application. For large monolithic applications it may not be possible to test changes in the developer’s local IDE. Developer Efficiency .

Richard headed the European System Engineering function for Salomon Smith Barney/Citigroup. current industry trends are collectively shifting away from rigidly coupled. static. loosely coupled systems which are dynamically assembled from well-defined software components that run across a fluid set of compute resources. www.kirkk. the easier it is to change from one well-defined state to the next.html [4] http://techdistrict.org/wiki/Assembly_line The Portal for Java. Subsequent enhancements may be applied and removed just as rapidly: so significantly increasing business agility. applications and so towards OSGi. Prior to founding Paremus.gov/index.ly/16S0uK [7] http://en.standishgroup. decreasing operational risk and operational expense. A business system and any associated runtime middleware services may be dynamically deployed in seconds. dynamic assembled.nist. He is specifically interested in the application of such concepts to next generation distributed system designs and is an active contributor to the OSGi Alliance RFP 133 on Cloud Computing. The more agile the business service.kirkk. each application is self-describing.osgi. meaning the dependencies between versioned modules and dependencies on runtime infrastructure are known.de .jaxenter. With an advanced OSGi based runtime. Modular Systems are Maintainable Systems As identified by James Governor in his article “The Rise of the Stackless Stack” [6].com/2010/02/26/osgi-devcon-slides/ [3] http://www.org [6] http://bit.wikipedia.com/ [2] http://techdistrict.Modularity erational management. Yet stability and agility are closely related concerns. towards adaptive. no longer bearable). Sooner (for those that seek significant competitive advantage) or later (for those that find that operational issues are References [1] http://www. applying a patch. compute hardware and data-center real-estate costs. or rolling back to a previously well known functioning state. Excessive application maintenance costs will ensure that this trend continues into the foreseeable future.com/2009/11/03/turtles-and-architecture/ [5] http://www. ‘necessity’ – the mother of all invention – will drive organizations towards modular. Richard maintains a keen interest in a number of research areas including Recovery Oriented techniques and Self-Organizing and Complex Adaptive System design. the industry standard for Java modularity. Richard graduated from Manchester University with Honors in Physics and went on to gain an Astrophysics doctorate from the Royal Greenwich Observatory. Richard is CEO and Founder of Paremus Ltd and is President of the OSGi Alliance. opaque environments. whether this be to introduce new business functionality. Enterprise Architecture and SOA.

Let’s look at consumption first.Using OSGi in the Enterpise Using OSGi in the Enterprise The Enterprise OSGi Specification The OSGi Service Platform Enterprise Specification. in which case a default will be used. Some of the areas are described in this article and are referred to as Enterprise OSGi. It is possible that updated() is called without this information specified. Some additional notes. there is usually some configuration involved. Release 4. The services of the specification have been designed to guarantee integration with OSGi and cooperation among each other. // configure the system with the data supplied } } Listing 2 public void start(BundleContext context) throws Exception { ManagedService ms = new MyManagedService(). create an implementation of the ManagedService interface and register it in the OSGi Service Registry under a Service PID. // my default if (properties != null) { Object url = properties. Version 4. The PID acts as a key to direct configuration information to this ManagedService.getName(). To consume configuration.url").2 is produced by the Enterprise Expert Group of the OSGi Alliance. The specification combines previously published as well as new OSGi services that address the common use cases of enterprise applications and application server developers.service. } www. By Tim Diekmann and David Bosschaert The Enterprise Specification includes the recommended specifications for a number of areas. Popular tools for setting ConfigAdmin configuration include the Felix file-install bundle (which takes configuration from a . reg = context.toString(). Version 4. Configuration Admin Service Nearly every application needs configuration.service. You can find an example in Listing 1.service. It is pos- Listing 1 import java.class.util.JAXenter. e. It will get called as soon as there is configuration information available for the registered PID. props). The ManagedService implementation is registered in the OSGi Service Registry with a service.registerService(ManagedService.Dictionary object (similar to a Map).SERVICE_PID. The configuration itself is passed in as a java. Whether it’s a server process or a Rich Client Application. which is very flexible. This means that you can write a bundle that consumes Configuration Admin information completely independent of the entity that provides it. Consumption of CAS configuration is completely decoupled from the provisioning of it. } applyMyConfig(serverURL).pid"). "my.osgi.get("server. public class MyManagedService implements ManagedService { public void updated(Dictionary properties) throws ConfigurationException { String serverURL = "http://localhost:7070/server".put(Constants. ms.ManagedService.util. The OSGi specifications provide a standard way to provide and consume configuration information through the OSGi Configuration Admin Service (CAS). Setting the configuration can be done through a variety of means. import org. The ConfigurationAdmin API can also be used to integrate with another configuration data system. Note that ConfigAdmin supports dynamic re-configuration so the ManagedService should support reconfiguration of the component at runtime.cfg file) and the Felix Web Console.osgi. props. Dictionary props = new Hashtable().Dictionary. if (url != null) serverURL = url. It serves as a first reference point for enterprise software vendors when considering the use of OSGi in their environment to fulfill their own needs or to better serve the needs of their customers. The ManagedService has one callback method: updated().cm.ConfigurationException.2.com | May 2011 41 . ConfigAdmin uses maps to pass configuration data around. Release 4. It is based on the OSGi Service Platform Core Specification. import org.cm.url. from a BundleActivator (Listing 2). In this example the configuration property being used is server.g.pid key which is used to address it.

Let’s see how this is implemented in DS and Blueprint. Listing 3 public class SimpleDateFormatterComponent implements PrintDate { public String formatDate(Date date) { if (date != null) { return new SimpleDateFormat(). For example. the factory registers a management object which implements a common management interface as an OSGi service. therefore. The factory knows how to create the cloud image for its specific cloud from the data provided. Declarative Services Declarative Services (DS) is a simple and yet powerful component model. for the most part. They provide an OSGi bundle programming model with minimal implementation dependencies and virtually no accidental complexity in the Java code. the provider and the clients of a service are implemented by different components. Following OSGi best practices. Furthermore. Managing the component lifecycle by instantiating services on demand and on-the-fly ensures optimal use of resources. When created and passed to ConfigurationAdmin. it is still considered infrastructure that can bleed into the application code of a bundle. and the service references are documented in a XML file that accompanies the project. Each instance of configuration data contains the specifics for creating an image in a particular type of cloud. Creating cloud images may be highly specific to the cloud vendor. Enterprise OSGi. Rackspace and Microsoft Azure. take a cloud toolkit that supports managing cloud instances using a common API. The schema of the XML file www.JAXenter. once created. provides two interoperable Dependency Injection (DI) based component frameworks. The lookup of services. } return null. However. These component frameworks ensure decoupling of the application code from the OSGi APIs.format(date). Declarative Services and the Blueprint Container. the client application that manages the cloud instances (checks their status. both frameworks elegantly address the issue of long start-up times when many services are instantiated and made available without being needed as well as the resulting increased memory footprint. The component implementation. } Figure 1: Using CAS ManagedServiceFactories to contol multiple cloud images. It operates on the OSGi Services through the common management interface using CAS ManagedServiceFactories to contol multiple cloud images (Figure 1). The bundle containing the shared service interface.Using OSGi in the Enterpise This can be supported very well through a ManagedServiceFactory. } } as well as an implementation (Listing 3) and a consumer that has a member and a setter for the component framework to inject the reference(Listing 4). public void setProvider(PrintDate provider) { this. Component Models While the OSGi framework API is relatively simple to use. Both the provider and the client components will be wired to it by the DI framework. } } Listing 4 public class PrintDateClient { private PrintDate provider. its provided services.com | May 2011 42 . the tracking of their lifecycle and availability quickly become an overwhelming task to be managed correctly and efficiently. It’s also possible to use CAS to configure multiple instances of entities of similar type. it will call a specific ManagedServiceFactory with the config information. Finally. It might support managing cloud instances in EC2. sible to restrict the data to a schema by using the Metatype specification. In the following example we have a simple interface: public interface PrintDate { public String formatDate(Date date). is implemented and contributed as a simple bundle with no lifecycle of its own. Once the image has been created. starts and stops them etc) has no need to know anything about cloud specifics. This CAS concept allows the creation of multiple entity instances based on similar configuration data.provider = provider. the management operations can be abstracted across cloud providers through a common API.

The description of the component and its implementation has to be understood as templates for individual instances.api.client.ds. There are now multiple open and closed source implementations available. To configure the instances on demand or at startup time. The definition of components as beans will look very familiar to those with experience in Spring.1. } Listing 5 <?xml version='1.client. DS ties the life span of the component to the availability of the reference.PrintDate" bind="setProvider"/> <service> <provide interface="org. Components are typically configured with static property defaults in the component XML file..0. By convention the DS component XML files are stored in the OSGI-INF folder of the bundle. DS uses the name of the component as a PID to obtain a configuration from CAS.0" name="org.PrintDateClient"/> Components can provide services..example. <implementation class="org.1 0. public void activate() { System.1 1. Setting the value to require makes it mandatory for a PID to be available from CAS and optional will use the configuration from CAS when it is available. the configuration is not obtained from CAS...ds.PrintDateClient. Each component description includes the name of the component and the implementing class.n 1. the component is deactivated and its services unregistered. Blueprint Container The Blueprint Container specification is based on the popular Spring framework and the work that was done by the Spring Dynamic Modules project to integrate it with OSGi. In order to support more dynamic configurations. This allows for client bundles to start their processing once all dependencies are satisfied.n"/> Each component is defined in its own XML file listed in the header and it is possible to use the ‘*’ wildcard to automatically match all XML files in a given folder.’ in the name and are only visible to the component implementation. namely Eclipse Gemini. Using attributes on the reference element for services it is possible to declare the client interest in multiple services of the same type and whether those references are mandatory for the lifecycle of the component or optional.ds. Service-Component: OSGI-INF/org.ComponentFactory service on behalf of the component that allows clients to create new instances with a given configuration.example. Table 1: Cardinality Table www. The component implementation can participate in the activation process by implementing the activate() method. or both at the same time.ds. These activation policies are declared as attributes of the component.Using OSGi in the Enterpise is defined by the OSGi Alliance and the latest version is 1. In DS all component properties are automatically registered as service properties of the registered service unless they are marked as private. The user code is freed of all references to OSGi API and can thereby be tested easily in JUnit and other Java test frameworks (Listing 5).example..out.JAXenter.example. see Configuration Admin Service. Apache Aries..formatDate(new Date())).example.example.println(this. Only if no replacement can be found.PrintDate" cardinality="1.osgi. component.client.xml <reference name="provider" interface="org.api. and Virgo from SpringSource (VMWare).api.provider. DS then registers a org. In this example the cardinality of 1. DS integrates very tightly with the Configuration Admin Service (CAS).n one or no reference (optional dependency) one reference (mandatory dependency) zero or many references (all available dependencies) one or many references (at least one reference is required) A similar callback for the deactivation is available by implementing the deactivate() method.PrintDate" bind="setProvider"/> </scr:component> Listing 6 <reference name="provider" interface="org.PrintDateClient"/> <reference name="provider" interface="org. By default.1.api. consume services.example. If set to ignore. The configuration-policy attribute of the component element controls the configuration policy used by DS.example.client. The service and reference elements describe the service interface to be used in the registration of the service or in a filter when resolving service dependencies (Listing 6). In order to be processed by DS a bundle has to identify itself as a DS contributor by defining the Service-Component header in the bundle manifest. If set to dynamic DS tries to find an alternate suitable candidate to remove the reference that has failed. DS handles dependency management on behalf of the component.PrintDateClient"> <implementation class="org.0' encoding='utf-8'?> <scr:component xmlns:scr="http://www.osgi. DS initiates the lifecycle of components automatically by calling the default constructor.service.n indicates that the client is interested in all services matching the filter criteria and it requires at least one to become functional.PrintDate"/> <service> 0. By setting the policy attribute in the reference element to static. Private properties start with a ‘.org/xmlns/scr/v1.com | May 2011 43 . It is possible to provide configuration properties for the instance as well as delaying the instantiation of a component until its registered service is requested by a client. DS supports the factory pattern for components by setting the factory attribute on the component declaration.

In DS. which was not possible in DS where all public properties are part of the registration automatically. This may lead to component thrashing in larger configurations. Blueprint beans can implement and export services to the OSGi service registry.example.api. the proxy will throw a org.framework. In DS fragments can contribute component definitions but they have to be complete as they cannot span multiple files.osgi.Using OSGi in the Enterpise DS and the Blueprint framework are very similar.PrintDate together with a public setter for Blueprint to call with the referenced object. example. Bundle fragments may also contribute bean definitions and can be reused among multiple components. Blueprint differentiates between mandatory and optional dependencies. Like DS. In its simplest form a bean definition contains an id and an implementation class. In DS the same was declared using the cardinality attribute on the reference element.example.osgi.PrintDateClient"/> <bean id="client" class="org.api.example. The proxies are able to cope with the temporary unavailability of services by blocking the calling thread for a configurable amount of time until a replacement is found. This allows for clearer separation of concerns and modularity in the definition itself.client. This includes. neither the proxy nor the bean will need to be destroyed unnecessarily.api. In Blueprint references and services are defined separately from the bean implementation declaration. www.PrintDate"/> This simple example assumes the presence of a public default constructor. Blueprint can introspect the implementation and select the service interfaces automatically from the implementation. This allows for service references to be declared once and reused multiple times by one or multiple beans. Blueprint is more focused on enterprise applications demanding a high degree of flexibility and extensibility.com | May 2011 44 .JAXenter. Of course. <service id="providersvc" interface="org. Blueprint has many configuration options to customize the initialization and dependency management. Instead of listing interfaces individually.org/xmlns/blueprint/v1.example.bp.example. among others.0" encoding="UTF-8"?> <blueprint xmlns="http://www. The bundle has to indicate its support for Blueprint by providing the Bundle-Blueprint header in the manifest file.ServiceUnavailableException for the client to handle.xml expects the bean to take a List<org. Bundle-Blueprint: OSGI-INF/org.client.0"> <bean id="myid" class="org.api. In general. The properties of the service registration can be individually configured. Blueprint. Listing 7 <?xml version="1. However. however. Among the significant differences between Blueprint and Declarative Services is the overall availabilty and lifecycle of components that have declared their dependencies to be managed by a component framework.example. As soon as mandatory dependencies are no longer satisfied the services of a bean becomes unavailable. DS is very efficient and meant for lightweight components with focus on startup times and memory footprint. beans are defined in one or more XML files inside of a bundle.client.bp.example. uses dynamic proxies that are injected into beans. The Blueprint declaration <reference-list id="providers" interface="org. The definition of a single component in Blueprint may span across multiple definition files. After the timeout has expired. support the passing of static properties as well as references to other beans and other non standard constructors.PrintDate> as the argument for the setter.api. Services provided by beans become available to others once a bean has been initialized. the ability to immediately instantiate beans on startup or delay their creation as well as customizing the callbacks for lifecycle and dependency injection handling. The most obvious similarity is the use of XML files to describe the components.bp. their lifecycle.api. Components in Blueprint are referred to as beans. You’ll find an Example Blueprint definition file in Listing 7. and their interactions among each other and with the OSGi framework.PrintDate" ref="myid"/> </blueprint> The registered service can be augmented with properties that can then be used in filters specified in the reference element.MyClass" /> <service id="srvc" interface="org.Printdate" ref="provider"/> The value of the header may point to individual definition files or to directories inside the bundle.example.PrintDate"/> A client declares a private member provider of the type org.example.PrintDateClient"/> <property name="provider" ref="provider"/> </bean> DS and Blueprint both provide the ability to have multiple instances of a declared reference injected. on the other hand. Similar to DS. It may also use the ‘*’ wildcard character to match multiple files in a single location. Blueprint does.bp. <reference id="provider" interface="org. Blueprint beans are instantiated when all mandatory references are satisfied and they are referenced by other beans or their service is requested.0. <bean id="client" class="org. The list is automatically updated with available references. where objects are created and destroyed in high frequency. which has an impact on the lifecycle of the bean and its availability to others. components become available and unavailable as soon as their dependencies are satisfied or unsatisfied.

1. Java Server Pages are a very popular technology and can be registered using a proxy servlet like the one provided by the The OSGi Web container implementation is implemented as an extender that automatically discovers and registers web applications found in WABs. Some of the most critical ones are mentioned here.HTTPService. The installation turns the war file into a OSGi Web Application Bundle (WAB). The last argument for both calls is a org. A WAB may contain an optional web. the Enterprise Expert has focused its attention in the first version of the specification on the use cases that integrate JEE technology with OSGi. if (ref != null) { HttpService svc = (HttpService) ctx. JEE Technology Integration HTTP Service and Web Applications Recognizing the significant investment of enterprise into the JEE technology.Dictionary with configuration parameters for the servlet.html file located at the root of the bundle. webbundle:file:///wars/myapp. Registering a servlet is very similar: svc.registerServlet(“/path”.osgi. they have to pass the same HttpContext object in the registerServlet call. the applications can leverage the OSGi module and service layers. Current Java enterprise architectures almost always require support for web technologies to provide content.class. Web Applications Specification Most features that are missing in the HTTP Service Specification are provided by the Web Application Specification. simply call svc.getServiceReference(HttpService. which in its current release supports the Java Servlet Specification 2.http. HTTP Service Specification Contributing and surfacing Java servlets programmatically in OSGi is as simple as installing an implementation of the org. This reduces memory footprint and opens up extensibility concepts that are otherwise not possible with static content.com | May 2011 45 . The user can implement the HttpContext in order to support authentication and more advanced resource mapping. To ease the adoption and integration with OSGi the Web Applications Specification defines a standard way of taking an existing war file and converting it into an OSGi bundle to be used in the framework on-the-fly. A WAB is differentiated from other bundles by the presence of the Web-ContextPath header. “/”..JAXenter. It is also possible to point to a folder in the file system here. The current version has support for the Java Servlet Specification in version 2.util.example The first argument registers the content under the /files context path and the second argument points to the location of the resource. and using the very simple interface to register static resource content as well as servlets (Listing 8). null). To register a static resource like a welcome.registerResources(“/files”. The Web Application Specification defines how to turn an existing Java EE web application war file into an OSGi bundle. if (svc != null) { // register resources and servlets } } www. Jasper project to compile . osgi. The simplicity of the programming model makes the HTTP Service very appealing for simple projects already implemented in OSGi. simply install a bundle from a URL that starts with webbundle:. initparams. The HTTPService provides the createDefaultHttpContext method to obtain the default implementation.Using OSGi in the Enterpise The use of dynamic proxies implies that a service has to implement an interface and cannot be a simple class. This is different from DS.HttpContext object.xml.getService(ref). However. passing null has the service pick the default.jsp files into Java servlets on demand. myServlet. In order for two servlets to share the same ServletContext. obtaining a reference to the service. Web-ContextPath: /path/to/my/app Here the servlet is mapped to the /path context path. where services can be provided by classes without implementing an interface. The Http Service Specification provides a simple way in OSGi to register servlets programmatically. The most common form is the use of Java servlets and web applications. The web. Therefore. like Bundle-SymbolicName and Bundle-Version and these may not always be available in the war file. the service interface lacks support for common features like servlet and context listeners.5 and Java Server Pages Specification 2. Every bundle requires a set of mandatory headers.getName()). The web container implementation registers a URL Handler that understands the protocol and performs the conversion into a bundle during the installation. null). it is possible to pass the header values in the URL used for installation.xml file located at WEB-INF/web. It is fair to say that the vast majority of Java based enterprise applications are written as Java EE web applications and packaged as war files. In addition to surfacing the same capabilities as a Java EE web container.http. The initparams argument is a java. The headers are passed in the URL query part separated by ‘&’. Like other bundles WABs have import-package and exportpackage headers that wire the implementation to other bun- Listing 8 ServiceReference ref = ctx. in this case the root of the bundle. Provided you have deployed a compliant web container implementation in your framework. Enterprise OSGi addresses both of them.xml file is interpreted the same way as is defined by Java EE.war?Bundle-SymbolicName=com.1.

TransactionSynchronizationRegistry are expected to be registered by an OSGi compliant Transaction Manager implementation.persistence. By referencing packages from other bundles. the main one being “service.DataSource as well as javax. The lookup mechanism of JNDI is also very rigid and not as dynamic as the OSGi service layer.getObjectInstance() mechanism is replaced by a call to a org.TransactionManager.jsp extension mappings or using the jsp-group element. Support for JPA is available by registering a org.naming.xml. Remote Services OSGi Services provide a Service Oriented Architecture within the OSGi framework. mind.JAXenter. Getting JDBC and JPA to work in an OSGi environment has been notoriously difficult in the past. Unfortunately. javax.osgi.jndi.interfaces”.InitialContext to obtain a context for their application and use it for lookup of resources.exported. the JTA interfaces javax. The Web Application Specification provides servlets access to the bundle context by setting the osgi-bundlecontext property in the ServletContext.ConnectionPoolDataSource objects. This is especially true for Java EE Naming clients that use the JRE provided javax.transaction.DataSourceFactory from which clients can obtain javax. The three remaining specifications to be mentioned here are Database Access via JDBC.osgi. OSGi Services are dynamic. lifecycle. and service layers of OSGi.transaction. the full potential for web applications is only achieved when the application is implemented as a WAB from the ground up and makes use of the module.xml file is set true. Besides. BundleContext ctxt = (BundleContext) servletContext. and the Naming specification JNDI.jdbc.transaction. web applications can significantly reduce their memory footprint.NamingManager. When this property is set to “*” all the interfaces registered for the Service are made available remotely.3 and 2.naming.0. While the installation of an existing war file is the easiest way. service. Similarly. To support existing non-OSGi aware clients compliant implementations provide a compatibility layer that sets the JDNIInitialContextFactoryBuilder and the ObjectFactoryBuilder singletons in the JRE such that it uses the BundleContext of the client bundle to obtain a reference to the JNDIContextManager service to obtain the appropriate JNDI context.service. naming.Context object from a org.Using OSGi in the Enterpise dles. For example. in some cases blanket messages need to be set on all displays in a certain area. void setText(String text).InitialContext class. the OSGi Remote Services specification takes the OSGi Service concept across machine boundaries. } Database Access. The example Service has the following API: public interface DisplayService { String getText().util. The Enterprise Specification describes how OSGi aware clients can obtain a javax. and service layers of OSGi.jndi. Using the service registry it becomes very easy to contribute content to the web application from other bundles. The static javax. but by no means all of the 25 different Java EE specifications. If annotations are used.xml. It may also include further resources available in the WAB. and Naming Currently. A controller might address displays by road number and direction or zip code. For example. the WAB has to import the appropriate packages.JNDIContextManager service instead of using the static javax.osgi. They can come and go at any time. Service registrations can hold arbitrary properties which make it possible to select Services from a larger set based on servicespecific metadata. but merely states patterns of integration into the module. The Bundle-Classpath header has to contain the entries for WEB-INF/classes and all jars in WEB-INF/lib. Multiple implementations of context and Object factories can be dynamically installed and updated.EntityManagerFactoryBuilder service.xml as defined by . It makes OSGi Services available through the network by adding some extra properties.ServiceLoader). This builder creates javax.osgi. These specifications solve the issues in a clean and simple way. Transactions. Enterprise OSGi addresses several. the abstraction of specific database drivers is provided by a org. Unlike many other service frameworks (such as Spring or java. It may optionally support Servlet annotations defined by JSR 250 Common Annotations for the Java Platform. The current version supports JPA 1. For the most part. The OSGi specification does not go and repeat the respective specifications in detail.UserTransaction. lifecycle. EntityManagerFactory objects that are described in the JPA specification. While ‘ordinary’ OSGi Services operate within the JVM.com | May 2011 46 .jpa. and javax. In that case it will scan the implementation classes for support of annotations unless the metadata-complete attribute on the web-app element in the web. take a Display Service. Each road sign registers a Remote Service to access its display.service.getAttribute ("osgi-bundlecontext").JNDIProviderAdmin service. implementations register services in the OSGi service registry that provide access to the well known APIs.service. In all three cases the integration with OSGi is similar. This Service represents electronic traffic warning displays. like a weather warning. Web container implementations support JSP pages in the web. for instance with a given post code. OSGi Remote Services is an excellent technology to realize this functionality. This makes it possible to invoke remote entities through the Service programming model. The mechanism by which implementations of the JNDI context are provided is not very suitable for modular environments with different class loaders per bundle.naming. neither all client nor all provider code is written with a dynamic modularity framework like OSGi in A controller doesn’t always need to know the exact displays to set. transactions defined by the JTA specification. When a Remote Services-compliant discovery system is used the Service is registered with this discovery system which allows Remote Service consumers to find www.

The Remote Services specification doesn't describe the network protocol and data binding to be used for the remote communication. However if a standard is used for the networking layer. Figure 5: Controlling road-side displays using OSGi remote services www. So a road-side display controller application could use an org. and reliable systems are based on asynchronous event-based computing models. based on pub-sub concepts. To set a message for an area. the controller selects the displays by zip code and sets the message accordingly across all relevant displays. Depending on the configured discovery system these will automatically appear on demand in the local Service Registry. Since the integration of Remote Services is done through the OSGi Service Registry they work with any framework that works with the OSGi Service Registry. Event Admin Service The OSGi Event Admin Service spec defines an inter-bundle event delivering mechanism. Many scalable. ServiceTracker or a Service Injection framework such as Declarative Services or Blueprint to look up the required Services using an LDAP filter like this one: (&(objectClass= DisplayService) (zipcode=95054)) and set the value “Warning: widespread fog” on all Services found. it opens up the possibility to access the Remote Service from non-OSGi consumers. A wide variety of options is available such as REST. performant.tracker. The Service consumer doesn’t need to pass any special properties to select Remote Services.util.JAXenter. Here’s how three displays could register themselves as Remote Services (Figure 2. plain sockets or RMI.osgi. This is entirely up to the implementation.Using OSGi in the Enterpise Figure 2 Figure 3 Figure 4 the Service without having to know where they are located beforehand. 3 and 4). The OSGi Event Admin Service provides this model inside the OSGi Framework. SOAP/HTTP.com | May 2011 47 .

I register this handler with the OSGi Service Registry (Listing 11). the JMX specification provides access to functionality from StartLevel and PackageAdmin.registerService(EventHandler.getTopic(). Additionally. In the OSGi Alliance. He spends most of his time on Open Source OSGi projects such as the JBoss OSGi Framework and Apache Aries and is also one of the OSGi Enterprise Expert Group co-chairs. Listing 11 EventHandler handler = new MyEventHandler().bosschaert@gmail. For example registering a handler under stock/us/nasdaq/* instructs Event Admin to send all Nasdaq stock events to the handler.com/digital. event. A screenshot can be found in figure 6 of OSGi JMX support in the JBoss AS7 OSGi Framework via Jconsole.getProperty("PRICE")). props).put("AMOUNT". Germany. EventAdmin eventAdmin = . props.getName(). Events are published on topics.Using OSGi in the Enterpise Figure 6: Accessing the OSGi Framework using JMX The essence of the Event Admin service is very simple.com | May 2011 48 . Framework operations such as installing. // obtain Event Admin Service. Tim holds a MS in Computer Science from University of Kaiserslautern. "stock/us/nasdaq/foobar" }).put("PRICE". Listing 9 Map<String.EVENT_TOPIC. as a Sr. for instance to limit events received to ones that relate to large trades only. where he was also in charge of the OSGi based runtime platform. trade. An event can hold a map of arbitrary properties as data. starting..customsigngenerator.osgi.org/ wiki/OSGi_Specification_Implementations [2] Find the latest OSGi specifications here: http://www. } } David Bosschaert works for JBoss at Red Hat. trade.put(EventConstants. Dictionary props = new Hashtable(). A small number of compendium services are also supported through JMX. I can also use a wildcard at the end of the topic path in the handler registration. new String [] { "stock/us/nasdaq/acme". My event handler may look like in Listing 10. To receive events. Architect. updating and uninstalling a bundle are supported as well as query operations for Bundles and Services. Listing 10 public class MyEventHandler implements EventHandler { public void handleEvent(Event event) { // process the event updateChart(event.com Tim is working at TIBCO Software Inc. Previously. Event event = new Event("stock/us/nasdaq/acme". you could use the following code in Listing 9. He has been developing software since 1983 and coding Java since 1997. 1742). such as CAS. References [1] Where can I get an implementation of an OSGi spec? A list of all OSGi technologies and where to get them can be found here: http://en. He is responsible for theOSGi based runtime platform of the ActiveMatrix product suite. bundleContext. essentially ‘/’-separated paths. handler.org/Specifications [3] Acknowledgements: clip art: openclipart. 1000). "USD").org [4] Traffic sign generator: http://www. trade).. Event consumers are registered with the Event Admin service under the topic paths they wish to receive events for.. Object>().put("CURRENCY".class. he was working for Siemens Communications as Principal Engineer.asp www. It's also possible to filter out events on additional event properties..JAXenter. eventAdmin. In this example my handler receives callbacks for the ‘acme’and ‘foobar’ stocks. For example to create a trade event for an imaginary trade system.wikipedia. Object> trade = new HashMap<String.postEvent(event). A bundle can generate events and other bundles can register themselves to consume these events. trade. Tim serves as the co-chair of the Enterprise Expert Group since its inception in November 2006. JMX Support The JMX specification enables control of the framework through JMX. stopping. You can reach him at david.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->