Berichten met label Apache Felix

Kennissessie Services op 24 oktober: de videos

Op 24 oktober 2011 vond een kennissessie plaats over services in gedistribueerde en/of embedded omgevingen. Deze sessie was georganiseerd door Luminis in samenwerking met Thales en leden van de Apache community, en ging in op de vraag hoe het toepassen van services kan helpen bij het verbeteren van de flexibiliteit van bestaande systemen.

De video presentaties van deze sessie zijn nu beschikbaar.

Innovatie, Services en Open Source
Rene van Hees, Technical Authority Software bij Thales

OSGi en Dynamische Services
Marcel Offermans, lid van de Apache Software Foundation

Apache Celix en Apache Foundation
Alexander Broekhuis, Software Engineer Luminis, committer Apache Celix

, , , , , ,

Nog geen reacties

Online video: Beyond OSGi software architecture

Op 11 november 2009 gaf Marcel Offermans samen met Jeroen van Grondelle (Be Informed) een duo presentatie over “Beyond OSGi software architecture”. De video van deze presentatie is inmiddels online beschikbaar. De gehele presentatie van 50 minuten kan je hier downloaden. Maar de eerste tien minuten zijn hieronder gelijk online te bekijken.

OSGi is niet meer weg te denken uit het Enterprise Java domein. Dit lightweight framework krijgt al een aantal jaren flinke aandacht en is met name bekend om z’n modulaire applicaties op basis van bundles. Minder bekend is het services model, waarbij applicaties worden ontwikkeld op basis van service interfaces en van elkaar ontkoppelde implementaties (POJO’s) van die interfaces. Krachtige eigenschappen van dit model zijn:

  • complexiteitsreductie door stricte scheiding van services;
  • declaratieve services en dependency management (IoC);
  • aspect oriëntatie op basis van stub services;
  • security model.

Lean software is een nieuwe manier om enterprise applicaties te bouwen op basis van OSGi, die ook goed aansluit bij Agile methoden, waarbij non-functional requirements ingevuld kunnen worden in een compact gebleven framework. In die context kijken we naar:

  • applicaties deployen op allerlei platformen en omgevingen;
  • applicaties automatisch installeren en updaten;
  • applicaties voorzien van management interfaces;
  • product software uitbreidbaar maken middels een SDK;
  • product software verkopen als combinatie van standaard onderdelen en optionele uitbreidingen;
  • modulaire User Interfaces.

De slides van de presentatie zijn te vinden op de NLJUG website.

, , , , , ,

1 reactie

ApacheCon US 2009 – Celebrating a decade of open source leadership

The Apache Software Foundation celebrated its 10th anniversary last week at the ApacheCon US in Oakland, California. The event, which lasted from November 2nd to 6th, consisted of many different types of events, ranging from full-day trainings to lightning talks, from a hackathon to technical and marketing sessions. On friday, the event featured a full-day track about OSGi, where all OSGi related Apache projects like Felix, ACE, Sling and Tuscany where present. The big announcement of the conference was the fact that Subversion wanted to join Apache. In fact, during the event, just like with any other project, there was a vote to accept Subversion into the incubator. As with many projects, this triggered some discussion, debating the merits of doing a release during incubation, even though this is a project with many seasoned Apache committers on board.

A conference like no other

Apache probably is the strongest brand in the open source space, but the conference itself focusses strongly on content. Here you will see no sponsored talks by commercial vendors, no sales people trying to sell you anything, it’s all about the code, the community and collaborating with each other. In that sense it’s quite different from most other conferences and if you like meeting and discussing fellow developers, this is a great place to visit. Many events facilitate discussion, and power and internet connectivity are available everywhere.

What open source is all about

Brian Behlendorf summarized the three main cultural elements of Apache quite well:

  • write good code and debate it to the bone
  • be humble
  • collaborate

In essence, Apache is a meritocracy, of which only individuals can become a member. It’s sometimes also described as a do-ocracy as projects are driven by contributions: if you want something done, just do it. Another important aspect is that everything that is done on the Apache projects is discussed and archived on the mailing list. All discussions, code diffs and decisions must be recorded there.

Presenting Apache ACE

Tuesday evenings “birds of a feather” session featured a discussion about Apache ACE, where questions mostly centered around the use cases for ACE and possible integrations with other OSGi components. One of the conclusions is that there are probably three different phases of deployment:

  1. Using Apache Felix File Installer, which allows you to drop components in a local folder to have them installed.
  2. Using Apache Felix Karaf’s provisioning components, which allow you to define features which basically group components and allow you to define dependencies on other features.
  3. Using Apache ACE, which allows you to group components and automatically deploy them to many remote systems.

Friday’s OSGi track started with an introduction to OSGi and moved into more advanced topics during the day. The Apache ACE talk was received well, with several people expressing an interest in wanting to use it and contribute to it.

Final thoughts

Summarizing the week, Floris and I had a great time talking to many interesting people and learning about various projects. ApacheCon is a great conference, and I’m already looking forward to the next one.

, , , , , , , , , ,

Nog geen reacties

Using GWT to create an OSGi-aware web application

Update 2010-02-20 Both Pax Runner 1.3.0 and GWT 2.0 have caused quite some changes to this post. I have tried to stay up to date as well as I could (the zipped project now uses GWT 2.0), but you might find some inconsistencies when following the tutorial.

Google Web Toolkit is cool, and so is OSGi. However, when building a web UI for Apache ACE, I found out that creating a web application that can use OSGi services is not that easy. By the end of this tutorial, you will have created a GWT project that delivers a usable jar. If you’re impatient, skip to the end for the downloadable Eclipse project.

Step 1: Create a GWT project

Create a regular GWT project using the regular webAppCreator; this will give you a project that includes an Ant buildfile, we will need that later on.

angelos:workspace angelos$ ./gwt-mac-1.6.4/webAppCreator -out GwtDemo net.luminis.gwt.gwtdemo
Created directory GwtDemo/src
Created directory GwtDemo/war
Created directory GwtDemo/war/WEB-INF
Created directory GwtDemo/war/WEB-INF/lib
Created directory GwtDemo/src/net/luminis/gwt
Created directory GwtDemo/src/net/luminis/gwt/client
Created directory GwtDemo/src/net/luminis/gwt/server
Created file GwtDemo/src/net/luminis/gwt/gwtdemo.gwt.xml
Created file GwtDemo/war/gwtdemo.html
Created file GwtDemo/war/gwtdemo.css
Created file GwtDemo/war/WEB-INF/web.xml
Created file GwtDemo/src/net/luminis/gwt/client/gwtdemo.java
Created file GwtDemo/src/net/luminis/gwt/client/GreetingService.java
Created file GwtDemo/src/net/luminis/gwt/client/GreetingServiceAsync.java
Created file GwtDemo/src/net/luminis/gwt/server/GreetingServiceImpl.java
Created file GwtDemo/build.xml
Created file GwtDemo/README.txt
Created file GwtDemo/.project
Created file GwtDemo/.classpath
Created file GwtDemo/gwtdemo.launch
Created file GwtDemo/war/WEB-INF/lib/gwt-servlet.jar

If you want to, you can import this project directly into your Eclipse. If you check the mark “use Google Web Toolkit” in the project properties, you can use all the same goodies that creating the project in Eclipse would have given you. Remember to replace the buildpath entries for gwt-user.jar and gwt-dev-*.jar by a Library import for GWT.

Step 2: Include the necessary OSGi references

Create an ‘ext’ directory, and add org.osgi.core.jar to that. In Eclipse, add this jar to your build path.

Step 3: Use OSGi services from your web applicaiton

We will first add a simple Activator on the server side.

package net.luminis.gwt.server;
 
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
 
public class Activator implements BundleActivator {
    private static BundleContext m_context;
 
    public static BundleContext getContext() {
        return m_context;
    }
 
    public void start(BundleContext context) throws Exception {
        m_context = context;
    }
 
    public void stop(BundleContext context) throws Exception {
    }
}

Then, we up the GreetingServiceImpl to actually use this BundleContext (note that we use it directly here, but you could use it to get other services, create a ServiceTracker, etc.)

public String greetServer(String input) {
  String serverInfo = getServletContext().getServerInfo();
  String userAgent = getThreadLocalRequest().getHeader("User-Agent");
  return "Hello, " + input + "!
 
I am running " + serverInfo
    + ".
 
It looks like you are using:" + userAgent +
    "The framework we run from has " + Activator.getContext().getBundles().length + " bundles in it.";
}

Step 4: Add OSGi dependencies for the compiler

Add our OSGi dependencies to the classpath, so the compiler can find all of it.

    <!-- Add any additional non-server libs (such as JUnit) -->

Right, let’s give it a try!

angelos:GwtDemo angelos$ ant war
Buildfile: build.xml
 
...some output removed...
 
war:
[zip] Building zip: /Users/angelos/workspace/workspace/GwtDemo/gwtdemo.war
 
BUILD SUCCESSFUL
Total time: 36 seconds

You will find a war in your project directory now. There still is one ingredient we need. We need to make this into a proper bundle. We can use bnd to help us with that.

Step 5: use bnd to create a proper war

Download bnd, and put into a lib directory, and add it to your buildfile.

We create a new target that transforms our war into a jar.

<target name="jar">
    <copy file="gwtdemo.war" tofile="gwtdemo.jar"/>
    <echo file="gwtdemo.bnd">Import-Package: junit.framework;resolution:=optional, com.google.gwt.*;resolution:=optional, org.w3c.*;resolution:=optional, sun.misc;resolution:=optional, javax.imageio;resolution:=optional, javax.servlet.*;resolution:=optional, *
Bundle-Name: GWT Demo
Bundle-ClassPath: WEB-INF/classes, WEB-INF/lib/gwt-servlet.jar
Bundle-SymbolicName: net.luminis.gwt.gwtdemo
Webapp-Context: gwtdemo
Bundle-Activator: net.luminis.gwt.server.Activator
    </echo>
    <bndwrap jars="gwtdemo.jar" output="gwtdemo.jar"/>
    <jar file="gwtdemo.jar" update="true">
    <manifest>
        <attribute name="Bundle-ClassPath" value="WEB-INF/classes, WEB-INF/lib/gwt-servlet.jar, ."/>
     </manifest>
    </jar>
    <delete file="gwtdemo.bnd"/>
</target>

What’s happening here?

  • we copy our war to the same file, but with a jar extension,
  • we create a file for bnd to use, stating that we
    • want optional imports for junit and the gwt benchmarks, and non-optional imports for everything else (that what the * is for),
    • have some classes that we want bnd to scan for finding dependencies,
    • want to use a given Webapp-Context (this is a Pax war extender specific entry),
  • let bnd do its magic,
  • update our manifest: we put the . back on the classpath. This is important for the web application to find all resources, but if we would tell bnd to do it like this, it would treat . as the root of the classpath.
  • Finally, we delete that temporary bnd file.

What does that give us?

angelos:GwtDemo angelos$ ant jar
Buildfile: build.xml
 
...some output removed...
 
jar:
[copy] Copying 1 file to /Users/angelos/workspace/workspace/GwtDemo
[bndwrap] gwtdemo 41 910305
[bndwrap] Warnings
[bndwrap] Superfluous export-package instructions: [WEB-INF.classes.net, gwtdemo.gwt.standard.images, WEB-INF, gwtdemo, WEB-INF.classes.net.luminis.gwt, gwtdemo.gwt.standard, WEB-INF.classes.net.luminis, WEB-INF.lib, WEB-INF.classes, gwtdemo.gwt.standard.images.ie6, WEB-INF.classes.net.luminis.gwt.client, WEB-INF.classes.net.luminis.gwt.server, gwtdemo.gwt]
[jar] Updating jar: /Users/angelos/workspace/workspace/GwtDemo/gwtdemo.jar
[delete] Deleting: /Users/angelos/workspace/workspace/GwtDemo/gwtdemo.bnd
 
BUILD SUCCESSFUL
Total time: 23 seconds

That’s it! You can now deploy this jar into a framework that uses the pax web tools. Right, let’s give that a try.

Download pax-runner, and unzip that somewhere. Copy in your new jar, an try the following command

angelos:pax-runner angelos$ sh bin/pax-run.sh --profiles=war,compendium gwtdemo.jar

Now visit http://localhost:8080/gwtdemo:

gwtdemo

Summary

So, what did we need?

  • A fairly regular GWT project, create with an Ant file,
  • some code that tries to use OSGi services,
  • some bnd magic to make the war into a jar,
  • Pax tools to get it all running quickly.

If you don’t want to use pax runner, you can need to deploy pax-web-extender-war(jar, snapshot 23 June) and an http server, preferably pax-web-service(jar), into your framework.

You can download the gwtdemo Eclipse project to play around with it. I have not provided the GWT runtime in this download; you should edit line 4 of the build.xml to point to your installation of GWT.

, , , , , , , , , , ,

16 reacties

EZdroid launched


The EZdroid initiative is launched: www.ezdroid.com

We are pleased to announce the launch of EZdroid, the world’s first open-source, collaborative platform for the safe deployment of component-based software applications and content across Android, and other Linux-based mobile devices.
EZdroid was founded by two of Europe’s leading companies in the field of OSS technology; the platform consists of Android, Apache Felix and a number of their own enhancements (e.g. software license-, device- and integrated software-management). EZdroid supports the secure deployment of software applications and content (known as Provisioning) to Android phones and in the future, other Linux-based operating systems. It is available to any organization or individual wishing to make software and content available to Android users world-wide. Further information and a demonstration of the platform is now available and downloadable to Android phones at: http://www.ezdroid.com.

EZdroid’s founders: Luminis BV (www.luminis.nl/en) of The Netherlands and Akquinet GmbH (www.akquinet.com/en) of Germany are now inviting partners and collaborators to become part of the EZdroid community – whether these are developers, wishing to show-case their applications, business partners interested in co-development or an OEM relationship, or organizations which are interested in owning and controlling their own application repository/App Store.

The launch of EZdroid is very significant; it is the world’s first platform, built from open source components, which will allow the mass deployment of applications without proprietary licensing issues. The founders intend to supplement the platform with a validation and quality assurance system – to ensure that applications are safe and do not interfere with Android’s normal operations.

, , , , , , ,

Nog geen reacties

Enterprise Javabeans 3 in OSGI

Previous blogs (look here and here) have shown that it’s fairly easy to use (open)JPA within OSGi. Moving on on this path of attempting persistence solutions for OSGi led to an encounter with Easybeans (EZB from now on), an Enterprise Javabeans 3 (EJB3) container for OSGi.

This blog assumes that the felix 1.4.0 environment is used. All source code used and all relevant bundles can be found in this zip.

Some of the reasons EJB3 can be of interest when moving beyond what JPA has to offer:

  • container managed transactions;
  • dependency injection.

For more detailed information on the advantages of EJB3, refer to this article on javaworld


Using EZB within an OSGi context may be of interest to you if you’re working with an:

  • EJB3 environment and you’re thinking about migrating towards OSGi;
  • OSGi environment, but you don’t have a satisfactory solution for handling persistency issues.

In this blog we will use a simple example that uses some basic EJB3 functionality; we’ll use a command line client that connects to a stateless session bean. The session bean is able to interact with an entity bean called Wombat and is able to create, update and delete (Wombat) entities. We’ll walk through the specifics of each step below.

In order to execute a command, the client first has to connect to (i.e. obtain a reference to) the stateless session bean (EzbCommand.java):

    private static final String STATELESS_REMOTE = "net.luminis.ezb.example1.stateless.StatelessRemote";

    public void execute(String commandLine, PrintStream out, PrintStream err) {
        ServiceReference ref = m_bundleContext.getServiceReference(STATELESS_REMOTE);
        m_stateless = (StatelessRemote)m_bundleContext.getService(ref);

EZB registers each stateless session bean as an OSGi service when the bundle that contains the service (and using the org.ow2.easybeans.osgi.ejbjar.Activator) is started. Because of this, it is possible to use the service without EJB3/EZB specific code in the client or the service interface, even though you can still use JNDI to lookup the service. When trying this, be warned that there’s a class loader issue. When dealing with stateful beans, this mechanism does not work and a JNDI lookup must always be used.

Following that, the session bean receives a command from the client, e.g. a ‘create’ command. StatelessImpl.java then picks up the command and creates a new Wombat object with the supplied values. Once that is done, it uses the EntityManager injected into the implementation by EZB (because of the @PersistenceContext annotation – default EJB3 behaviour) to persist the newly created Wombat entity:

    @PersistenceContext
    private EntityManager m_entityManager = null;

    public void createWombat(int id, String name) {
        Wombat entity = new Wombat();
        entity.setId(id);
        entity.setName(name);
        m_entityManager.persist(entity);
        System.out.println("Created entity bean: " + findWombat(id));

The entity bean used (defined in Wombat.java) contains three EJB3 annotations, denoting it as an entity bean (’@Entity’), indicating which table to create/use for the entity (’@Table’) and indicating which of the bean’s attributes can be used as its primary key (’@Id’):

@Entity

@Table(name = "WOMBATS")
public class Wombat implements Serializable {

    // [cut some code]

    @Id
    public int getId() {
        return m_id;
    }

Update the Felix configuration

Once again, please note that a felix 1.4.x environment should be used. For more information on previous releases, refer to the README in the zip file. In order to start the EZB bundles, a few changes need to be made in the configuration.

A pre-configured conf/config.properties file can be downloaded from here.
Of course, you can also apply the required changes yourself; an overview of the changes that need to be applied to the conf/config.properties file will follow.

Note that you’ll need the file config.properties of a previous release to copy two specific configuration entries: ‘org.osgi.framework.system.packages’ and ‘jre-1.x’ (depending on the JRE used, this is a list of packages that are exported by default).
Now, edit the config.properties of your newly installed Felix configuration and:

  • Uncomment the ‘org.osgi.framework.system.packages’ entry and set the value to the one copied from a previous release.
  • Add the complete ‘jre-1.x’ entry to (the bottom of) the file.

The ‘org.osgi.framework.system.packages’ entry should now look something like:

org.osgi.framework.system.packages=org.osgi.framework; version=1.4.0, \
 org.osgi.service.packageadmin; version=1.2.0, \
 org.osgi.service.startlevel; version=1.1.0, \
 org.osgi.service.url; version=1.0.0, \
 org.osgi.util.tracker; version=1.3.3 \
 ${jre-${java.specification.version}}

Note that the last line (with the ${jre-${java.specification.version}} construct) includes all items that are set in the copied ‘jre-1.x’ configuration and that this means that you must have at least 1 section in your config file that starts like:

jre-1.5=, \
 javax.accessibility; \

Also, add the sun.rmi packages to the config.properties file, which can now be done more cleanly through:

org.osgi.framework.system.packages.extra= \
 sun.rmi.server; \
 sun.rmi.transport; \
 sun.rmi.registry;

Finally, make sure Felix only logs a warning if it encounters unsupported fragment behavior through uncommenting the line with the felix.fragment.validation option:

felix.fragment.validation=warning

Download the EZB bundles

The required easybean jars can be downloaded from here. This blog is based on usage of the ‘1.1.0-M1′ release, select that release (or possibly a newer release) and then download the package available under “OSGi bundles of EasyBeans”. Unzip the file and note the location of the ‘bundles’ folder.

Install the EZB bundles

Note that this this step should be performed using a felix-1.0.x configuration or a felix-1.4.x configuration only!
In order to install the bundles, start Felix (make sure you’re using the updated configuration!) and execute the following commands in Felix:

-> cd file:/<absolute_path_to_bundle_folder>/
-> start org.apache.felix.configadmin-1.0.4.jar
-> start org.apache.felix.dependencymanager-1.1.0-2008.07.10.jar
-> start org.apache.felix.log-0.9.0-incubator-2007.12.14.jar
-> start org.apache.felix.scr-1.0.6.jar
-> start ow2-bundles-externals-commons-logging-1.0.8.jar
-> start ow2-bundles-externals-commons-modeler-1.0.8.jar
-> start ow2-util-event-api-1.0.8.jar
-> install ow2-util-event-impl-1.0.8.jar
-> start ow2-util-jmx-api-1.0.8.jar
-> install ow2-util-jmx-impl-1.0.8.jar
-> start slf4j-api-1.5.2.jar
-> start slf4j-jcl-1.5.2.jar
-> install easybeans-core-1.1.0-M1.jar
-> install easybeans-component-carol-1.1.0-M1.jar
-> install easybeans-component-jdbcpool-1.1.0-M1.jar
-> install easybeans-component-joram-1.1.0-M1.jar
-> install easybeans-component-jotm-1.1.0-M1.jar
-> install easybeans-component-quartz-1.1.0-M1.jar
-> install easybeans-component-hsqldb-1.1.0-M1.jar
-> install easybeans-agent-1.1.0-M1.jar

Once all these bundles are Active or Installed, start the easybeans-agent bundle. Once that bundle is Active, all bundles should be. Now you can start the ezb-command.jar and the statelessbean.jar bundles (same command structure as above). If you want to build the bundles yourself, copy the file easybeans-core-1.1.0-M1.jar from the ezb bundles dir and use ant to create the bundles:

cd <example1-location>
cp <ezb-bundledir-location>/easybeans-core-1.1.0-M1.jar lib
ant clean bundle.all

Once that is done, you can use the jars that can be found in the output dir.

An interesting point to note for this section is the use of the ‘easybeans-agent’ bundle. This bundle is used to stop and start the ‘ow2-util-event-impl’, the ‘ow2-util-jmx-impl’, the ‘easybeans-core’ and all ‘easybeans-component’ bundles in the right order (also refer to ‘issues encountered’ section below).

Issues encountered

  • When a bundle defines an entity bean in an exported package, it must import the package ‘javassist.util.proxy’ with ‘optional’ resolution;
  • The fact that EZB uses the easybeans-agent instead of using dependencies was often a source of confusion, if not errors: it felt like the startup order could not always be reproduced and only by stopping the agent, shutting down the framework and restarting both, could problems be resolved;
  • Running a client from the outside (not deployed in osgi / running in another JVM) that attempts to lookup (JNDI) a session bean was a real bother (and is therefore not included in this blog);
  • Injecting a session bean service that is not defined in the same bundle is not (yet) possible;
  • When using entity beans defined in a separate bundle, it is required to include the entity class name to be used both in the entity bundle itself and the bundle using it;

Maybe a follow-up of this blog will elaborate on the last two issues when moving on from using a single bundle to using multiple bundles.

Conclusion

All in all, the ability to use EJB3 related features from within OSGi is definitely a good thing, even though there’s a couple of usability issues to take into account still. Keeping in mind that the product is still in development and that the support is very good (when posting a question in the ow2 mailing, a response will usually follow within a day, if not within the hour), the EZB container is definitely one to keep an eye on!

, , , , ,

1 reactie

The OSGi Community Event in Berlin 2008

Day 1, a beautiful sunny day, was reserved for business presentations. A lot of these presentations actually mentioned the same benefits, which makes a nice, consistent case for OSGi. Some of the bigger projects were funded research projects, and I was proud to see Martijn and Hans do a presentation and succesful demo of GX’s WebManager 9, an application that is commercially available and nicely shows the benefits of using OSGi in an enterprise content management environment.

Near the end of the day, we showed a demo of the L-iQ Provisioning Server. The interest was pretty overwhelming and we got to show it in action many times, doing demos for three hours straight. Our main demo showed Apache Felix and a simple paint program which visualizes the dynamics nicely.

We ended the evening with a couple of beers on the roof of our hotel with some people from ICW who were staying at the same hotel.

Day 2, still sunny but cooler, started with a keynote by Peter Kriens who took a long trip down memory lane, going back to the days at Ericsson where he first started on what later became OSGi. He ended with a small peek into the future and ended by stating the mission of the OSGi alliance now, which is to become THE component framework.

Later in the day we had presentations on several topics. There were two parallel tracks so I could not even attend everything. A talk on JOnAS 5 gave an overview on the architecture of the first open source, OSGi based application server and how they can dynamically load and unload services. They already use iPOJO, OBR and have a componentized EJB 3 implementation called EasyBeans. Michael Keith from Oracle explained how JPA was adapted to work on OSGi and wondered why there was not yet a standardized persistence solution for OSGi. Jan and Markus gave an interesting talk on the Eclipse Communication Framework and R-OSGi, explaining how they can do all types of distributed services. The Enterprise Expert Group will also address this soon, and we briefly talked to Eric Newcomer about that. Richard did a nice overview of iPOJO, going through over 100 slides in 45 minutes while still making a lot of sense. iPOJO is definitely the dependency and component management solution for the future, as soon as it gets an API so we can use it instead of our dependency manager.

, , , ,

Nog geen reacties

Persistence in OSGi with OpenJPA — part 2

In the previous blog entry on openJPA in OSGi, we showed that it is fairly easy to use
openJPA within an OSGi context. This was demonstrated by creating a bundle that
provided a persistence service, that was able to persist and list sample domain
objects. As the goal was to get it working, we didn’t bother about separating stuff
over several bundles and put all in one bundle. In this blog, we’ll show how to make it
work with separate bundles, and how this simplifies using JPA within an OSGi context.

There are two disadvantages with respect to the single bundle approach (apart from
that it’s just ugly). Suppose you would develop deploy several bundles that provide
persistence services, and that these would all contain the OpenJPA jar (2.8 M) and all
of its supporting libraries (another megabyte). Having copies of these jars in each
bundle whould be a waste of space (disk space and memory!) and if you would
like to update one library, you’d have to update all bundles. Of course, it would be
much better if each “component” (whatever that me be) is in its own bundle.

Another issue is that the domain objects (in the code sample the Person
class) are bundled together with the persistence service. This is not ideal, as you can
image that domain objects can be used without persistence. Bundling them together would
require each application that uses domain objects, to have the persistence service
bundle to be installed as well. Having the domain objects in a separate,
independant bundle, results in a more modular configuration.

A domain bundle

We’ll start with the last issue, as this is the simplest one to fix. Starting point is
the sample code we developed last time (download the zip for all sample code).
The test client, a bundle that extends the
Felix command shell with a simple command to call our persistence service, is exactly
the same as last time. However, if you compare the first build file
(build1.xml) of the jpa-sample bundle with the ones from the previous blog
entry, you’ll notice differences with respect to imports of the sample bundle. This is
the result of upgrading to OpenJPA 1.1.0. With this new OpenJPA version, a number of
(obscure) dependencies (oracle, apache.avalon, weblogic) seem to be vanished, and also
commons-logging doesn’t seem to be required anymore, so we could clean up the
<bundle&gt task a bit.

Separating the domain classes is easy: create a bundle that only contains the
net.luminis.sample.jpainosgi.domain package. At the same time, we’ll
remove this package from the existing jpasample bundle (that is now
renamed to jpa-sample-service). This is not
required (OSGi can handle several bundles providing the same package), but we want to
ensure that our new setup works when the domain classes are in the domain bundle only.
However, as the domain classes use the javax.persistence package, this is
not enough: someone must export this package in order to make the domain bundle
resolvable. As this package is in the jpa-sample-service bundle, we’ll add an extra
export there (build2.xml).

If you’d deploy these two bundles in Felix and test it, you’d notice this works. But
it’s not yet perfect: due to the javax.persistence package that is
provided by the jpa-sample-service bundle, our newly created domain bundle still needs
the service bundle. That’s not we wanted, the domain bundle should be completely
independent from the service bundle! Hence, we must move out the
javax.persistence from the service bundle and make it a separate bundle.

Supporting libraries

The OpenJPA distribution comes with an implementation of the
javax.persistence package
(geronimo-jta_1.1_spec-1.1.jar). Turning this library into an OSGi bundle
is not difficult, and can be easily achieved with the Bnd tool (*).
But creating these bundles by hand is not necessary anymore, because the
javax.persistence and javax.transaction libraries that are
shipped with Apache Geronimo since version 2.1, are already OSGi bundles.
If you download the 2.1.2 Geronimo release, you’ll find the libraries in the
geronimo-jetty6-javaee5-2.1.2/repository/org/apache/geronimo/specs
subdirectory.

There are more common libraries that are used by OpenJPA and that can be easily
stripped from the bundle: the most used Apache Commons libraries are nowadays released as OSGi
bundles too. Unfortunately, the ones shipped with OpenJPA are not OSGi ready, but the
newest releases of Commons Collections, Commons Lang and Commons Pool are (see
overview). So you can simply
download these new versions and install them right away in your OSGi framework.

The Postgres JDBC driver is not yet available as OSGi bundle, so i fixed this by hand
(with a little help from Bnd). You can download this bundle, as well as the Bnd
configuration file used to create this bundle, from the
luminis open source server.
This results in a much smaller jpa-sample-service
bundle (build4.xml).

OpenJPA OSGi bundle

The final step, removing the openjar itself from our bundle, is a little bit more
tricky. We start by creating a bundle from the OpenJPA jar file. This time the Bnd
configuration file is less trivial; not only we must provide the (do-not)import
specifications that were previously in the build file (!org.apache.tools.ant;
!org.apache.tools.ant.types;
, etc), but also we need to explicitely export the
packages that will be needed by other bundles. This leads to an OSGi enabled version of
the OpenJPA jar (download it here).
Next we remove the openjpa stuff from our jpa-sample-service bundle. Trying to run this
version results in an “Creating EntityManagerFactory failed!” error. What’s going on here?

To understand what’s going on, we must understand how the generic
javax.persistence.Persistence class, finds a specific
EntityManagerFactory (since that class is part of the JPA implementation
you use, in constract to the Persistence class that bootstraps it). The find out which
JPA implementation you’d like the use, the Persistence class searches the classpath for
a provider configuration file in the META-INF/services resource
directory, see href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">Jar
file specification (actually, it asks the thread-context-classloader to list all
these files). In our old scenario, with the openjpa jar inside the bundle, this worked
well because the openjpa.jar was on the bundle-classpath (and hence, could be loaded by
the bundle classloader, that was set as context-classloader). But now, these service
definitions are in another bundle and it is not possible to load these resources from
outside (it is possible to load resources from another bundle, but not in this way).

We can solve this problem by explicitly telling the Persistence class which persistence
provider we want. This is possible by passing a property:

props.put("javax.persistence.provider", "org.apache.openjpa.persistence.PersistenceProviderImpl");

Hard-coding this is of course bad style, as we would tie our persistence service to one
specific JPA implementation. In production ready software, one would make this configurable.

Now, the Persistence class knows which persistence provider (class) to create. We must
only ensure that this class is visible for the jpa-sample-service bundle: it must
import org.apache.openjpa.persistence and org.apache.openjpa.jdbc.kernel. With this
setup (build5.xml) the bundle can start and create an EntityManagerFactory.

Unfortunately, this does not mean that calling the persistence service succeeds. When
you try, you’ll get a ClassNotFoundException for the Person class. This is caused by
the fact that OpenJPA tries to load the Person class from the same classloader that has loaded
the OpenJPA classes. In this case, that is the bundle classloader of the openjpa.jar
bundle, which of course, cannot find the Person class (it does not import it). In the
previous setup, both the openjpa.jar and the Person class were in the same bundle and
thus loaded via the same (bundle) classloader.

We can solve this by setting the thread context classloader, as OpenJPA tries that
classloader too. The disadvantage of this approach is that we have to add
setContextClassLoader() calls to each and every method in our service
implementation that uses JPA, e.g.

public void list() {
    ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        List resultList = entityManager.createQuery("select p from Person p").getResultList();
        System.out.println("List of all persons in db: ");
        for (Object p: resultList)
            System.out.println(p);
    }
    finally {
        transaction.commit();
        entityManager.close();
    }
    Thread.currentThread().setContextClassLoader(oldCL);
}

Of course, this is not what we want. We want to be able to use a “normal” piece of
(JPA) persistence code, without change, in a service implementation. The classloader
fiddling is an infrastructure aspect, that should be separated from our business
code. A simple solution is to use a proxy object that takes care of the context
classloader, see the sample source code for details.

Setting the context classloader solves the class not found issue, but reveals another
one: OpenJPA now complains that the Person class is not enhanced. This is strange,
because OpenJPA enhance persistent classes on the fly – after all, that is how it
worked in all the previous samples. I tried to track down this issue; it has to do with
a difference between the classloader that is used to enhance the classes and the one
that is used for accessing these classes. I’m not sure yet whether this is an OpenJPA
or an OSGi (or Felix) issue. Anyway, it’s easy to solve by enhancing the classes
beforehand. If you run the enhance task in build6.xml before the
bundle task, it creates a domain bundle with pre-enhanced domain
classes. Deploy this bundle in Felix, and see how it all works fine now!

We finally arrived at the situation with two very small sample bundles, that contain no
infrastructural libraries anymore. All libraries used are now bundles on their own, and
deploying these in an OSGi framework is all what it takes to make it work.

Conclusion

We showed that using OpenJPA in an OSGi context is very easy. An OSGi service
implementation that uses OpenJPA, can be implemented in the same way you would do when
used outside OSGi. Although there is one small difference, the need for setting the thread context
classloader upon each service invocation, this can be easily hidden by using a
proxy. If you want to maximize ease of development, and have no worries about the
overhead caused by using dynamic proxies, you could use a dynamic proxy that
automatically delegates all methods in the interface.

The bottom line is that using OpenJPA within an OSGi context is painless. That makes
OpenJPA a perfect solution for introducing persistency in an OSGi based application.

, ,

Nog geen reacties

ApacheCon EU 2008

After a successful conference last year, Amsterdam was again hosting the european ApacheCon. Karl and I hooked up with Richard Hall and we travelled together to this year’s edition. The sessions started on wednesday and lasted until friday. As always, it was interesting to hook up with committers and users of various projects and exchange ideas.

From the various sessions we visited, there were some that were particularly interesting and worth mentioning here.

For everybody who has ever built protocols, Apache Mina is a great framework. It abstracts away most of the complication of the NIO API and contains many building blocks for creating scalable servers and clients that use a custom protocol.

If you need to do enterprise integration, and you’re familiar with the Enterprise Integration Patterns book, then Apache Camel will help you write these integrations. Camel itself is packaged as a set of Spring components that can be integrated into any application easily. Configurations are either done using XML or with a fluent Java API. The latter looks really great and allows you to express complicated rules in a very easy way. Another interesting thing you can do with Camel is implement Business Activity Monitors (BAM). These are rules that trigger exceptions if some condition is not met. For example, you can specify that whenever a message A comes in, you would expect a response message B within 3 seconds. You can furthermore say what should be done if that is not the case, for example post an alert message C.

One of the Apache projects that has really adopted OSGi and Apache Felix is the ServiceMix project. They managed to implement JBI on top of OSGi and are working with the spec leads to make JBI fit more naturally with OSGi (which currently is not really the case). This is really one of the projects that will help move OSGi into the enterprise.

The Apache Sling project had an interesting BOF. They are close to doing their first release and are trying to grow their community. One of the nice aspects of Sling is that it packages Apache JackRabbit in OSGi bundles. Of course this should really happen within JackRabbit but it’s a great initiative. Sling itself is a web application development platform that uses REST principles to build content repositories.

Apart from the sessions, we also had several talks with people about Apache Felix. During the BOF about Apache Sling we discovered they had a very nice web based management console for OSGi. Since this was not in any way Sling specific, we agreed to donate it to Felix, as it would be a nice addition to our text and Swing based shells. You can follow that process on either the Sling or the Felix mailing list.

Furthermore, we discussed the possibility of a simple, pluggable installer that combines efforts from Peter Kriens, ServiceMix and Sling to create an easy to use, convenient installer that will speed up development.

A third interesting topic was the issue of testing OSGi bundles on multiple frameworks and rebranding. Even though we at Felix ensure we only use standard OSGi features that are part of the spec, some people think that bundles that are part of the Felix project only work on Felix. That’s of course not true, but we don’t explicitly test and guarantee the working of these bundles on other frameworks either. So, like with many hardware components that often get rebranded, we discussed the value of doing this for OSGi bundles. That way, companies like JayWay and luminis could provide branded bundles to their customers and make sure they comply with their quality and testing standards.

As a general trend, a lot of projects are now moving towards Java 5 as their minimum version, mostly stating generics and the concurrency API’s as their prime reasons. This poses an interesting question for OSGi development, since not all embedded JVM’s are Java 5 compliant yet. Should some kind of new Foundation profile be defined that includes the most important features of Java 5?

Finally, we showed some people our software component provisioning server and got positive reactions and some good feedback. In general we had a great time and learned some new things. Next year, we will try to organize more events around OSGi and Apache Felix in a further attempt to grow our community.

, ,

Nog geen reacties

JPA persistence in OSGi with openJPA

Applying a persistence framework in an OSGi container is not always a nuisance. Some persistence frameworks claim to be OSGi ready, but nevertheless, deploying them in a real OSGi application can be quite hard. In this blog, we’ll try to get openJPA to work in Apache Felix. All source code used for this experiment can be found in this zip.

For our experiments, we take a simple JPA example, consisting of one entity class Person and a Persister class that will either list all the person items in the database, or add a new one. For example, its create method looks like this:

public void create(Person person) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        entityManager.persist(person);
        transaction.commit();
    }
    finally {
        if (transaction.isActive())
            transaction.rollback();
        entityManager.close();
    }
}

Both operations (create & list) are contained in an interface that is published as an OSGi service, which enables code external to our jpa bundle to use this functions.

The first step in our little experiment is of course to create a bundle for these classes. We’ll use the Bnd tool for this, wrapped in the ant task that is available on http://opensource.luminis.net. We’ll start with the naive approach: we create a bundle that only contains our sample classes, add an activator and see what happens. The activator calls the Persister.initJPA() method in its start method, that tries to create the EntityManagerFactory:

private void initJPA() {
    Properties props = new Properties();
    entityManagerFactory = Persistence.createEntityManagerFactory("openjpa", props);
    if (entityManagerFactory == null)
        throw new RuntimeException("Creating EntityManagerFactory failed");
    else
        System.out.println("Init JPA ok.");
}

Of course JPA can not function without its persistence.xml file, which we add in the META-INF directory of our bundle (see build-attempt1.xml).

Installing this bundle in Felix results in one unresolved package: javax.persistence. This is easy to understand: our Person class uses JPA annotations (@Entity, @Id). We'll take the geronimo-jpa_3.0_spec-1.0.jar that comes with openJPA and add this to our bundle (eventually, we would like to make this separate bundles, but let's focus on getting it to work first). To do so, we adapt the build file to include the jar as a resource and set it on the bundle classpath explicitely (see build-attempt2.xml).

Loading this next version of the bundle in Felix, results in an exception: because the EntityManagerFactory is null. Note that there is no openJPA exception that gives us a clue about what is going wrong, but it's likely that is has something to do with the fact that we did not yet deploy any openJPA jars. So we add the openjpa-1.0.2.jar to the bundle and try again. If we try to load this bundle in Felix, it complains about an unresolved org.apache.tools.ant.types package. If we study the Import-Packages header generated by Bnd, we see a long list of missing dependencies, containing the usual suspects like org.apache.commons.lang, but also containing items like

  • com.ibm.websphere.jtaextensions
  • oracle.sql
  • org.apache.tools.ant.taskdefs
  • sun.misc
  • weblogic.transaction

which will a bit harder to track down. We take the pragmatic approach of adding the packages that (we think) openJPA really needs and ignore the others. In the end, we won't get away with this approach, but for now, it suffices. See the build file build-attempt5.xml for the exact list of ignored packages and the openJPA libaries that are added on the bundle classpath.

Note that the geronimo-jta_1.1_spec-1.1.jar that provides javax.transaction is needed, even though this package is delivered with the JDK and Felix makes it available on the system classpath. The funny thing is, is that the JDK version of this packages includes only a few classes of this package (and its javax.transaction.xa subpackage). This leads to the strange behaviour that the bundle does not load with a ClassNotFoundException, even though the package javax.transaction can be resolved!

Unfortunately, adding all these jars did not resolve the issue of having no EntityManagerFactory. This turns out to be a classloader issue: the openJPA classes are on the bundle classpath, but the JPA bootstrap code (the Persistence class) doesn't know about the bundle classloader. This can be solved by passing the bundle classloader as context classloader:

private void initJPA() {

    ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
    Properties props = new Properties();
    entityManagerFactory = Persistence.createEntityManagerFactory("openjpa", props);
    ...
    Thread.currentThread().setContextClassLoader(oldCL);
}

Note the last line of this method: its considered good practice to switch back to the original context classloader before returning.

Now the initJPA method seems to succeed, it's time for a real test. If you downloaded the source code of this samples, you'll find a seperate bundle (perscmd.jar) that adds an interactive command to the Felix shell, that will talk to our PersonPersistence service. This command bundle works only with Felix (i.e. with the Felix command shell), but you can easily create a similar bundle for other frameworks, e.g. Equinox or Knopflerfish.
Running this command shows that we're not done yet: the jdbc driver class can't be loaded. Adding the jdbc driver jar to the bundle classpath (postgres in our case) solves this last classloader problem and after creating a database and a "person" table, we can finally create persistent Person classes, as the following trace of the Felix interactive shell shows:

-> persistence list
List of all persons in db:
-> persistence create 1 john
-> persistence create 2 mike
-> persistence list
List of all persons in db:
john (1); registered on Mon Mar 24 21:19:53 CET 2008
mike (2); registered on Mon Mar 24 21:20:00 CET 2008
->

The conclusion is that it is fairly simple to use openJPA in an OSGi bundle. Actually, i was quite surprised how easy it turned out to be, given my previous experience with other persistency frameworks. I guess the fact that a library is so easily deployed in a context it was not designed for, tells us something about the quality of the library. And by the way, i got the same impression about quality when browsing through the code, trying to pinpoint the few problems i had to solve.

Conclusion

There are a few things to improve. First, bundling everything in the same jar is a bit of a brute force approach; ideally, we should create one or more separate bundles for the openJPA stuff. I did some work on this already, maybe i'll come back to that later.
Second, we created a sort of a work around for the unresolved imports, which should be solved differently.
However, i think both issues are doable in reasonable time, so for me openJPA is considered a good candidate for adding persistence to OSGi applications.

, ,

1 reactie