Berichten met label OSGi
J-Spring 2009
Geplaatst door Peter Doornbosch in Uncategorized op 16 april 2009
Aan de druk bezochte J-Spring Java conferentie in een zomers warm Spant! in Bussum, heeft luminis weer een flinke bijdrage geleverd. Bij de stand werd de bezoeker getrakteerd op een overheerlijke tompouce (van de echte bakker!) en werden lootjes uitgedeeld voor een boekverloting. Op inhoudelijk vlak bestond de bijdrage uit 3 presentaties over uiteenlopende onderwerpen. En voor de bezoekers die het uithoudingsvermogen hadden om tot het eind te blijven, was er dan nog de door luminis gesponsorde borrel!

De presentatie van Jaap Vriend ging over LWUIT, een UI library voor J2ME. Deze library biedt een op Swing lijkend programmeermodel en maakt het veel makkelijker om een J2ME applicatie er op alle telefoons hetzelfde uit te laten zien.
Richard van der Laan presenteerde samen met Tony Sloos van ArchitecIT een pragmatische benadering van MDA. Aan de hand van een concreet voorbeeld lieten ze zien hoe je bottom-up MDA kunt invoeren, waarbij je er vanaf het begin voordeel van hebt.
Onze OSGi guru, Marcel Offermans, had een leuke demo samengesteld op basis van de leukste bug. Nu is een live demo natuurlijk altijd riskant, maar Marcel is typisch iemand die dat wel aan kan. Helaas voor hem (en voor het publiek) waren de goden hem dit keer niet zo goed gezind en lukte het niet de demo dat te laten doen wat hij had moeten doen. Dus die houden we van hem tegoed! Bij de J-Fall op de luminis stand?
De presentaties kun je als pdf downloaden:
Enterprise Javabeans 3 in OSGi — part 2
Geplaatst door admin in Uncategorized op 29 januari 2009
This blog picks up on some unfinished items mentioned in the first blog. More specifically, this blog will focus on:
- auto-injecting session beans;
- entity-only bundles;
- transaction rollback.
Note that if the reader wants to run the example source, he or she is referred to the aformentioned previous blog in which more information on setting up the environment and getting the sources to compile/run can be found. To get the samples running, you always need to start ezb-command.jar and entitybeans.jar. Besides those 2 bundles, you either need to start combinedbean.jar (includes 2 stateless beans) or statelessbean1.jar and statelessbean2.jar (both bundles contain 1 stateless bean).
Auto-injecting session beans
In EJB3 (and therefore also in EZB) it is possible to inject a reference to a session bean through using the ‘@EJB’ annotation. When using this annotation, you can supply the product-specific name of the EJB to which it should be mapped (could be any kind of name – even though it is often a JNDI one). As it turns out, EZB almost completely supports this feature; both when the EJB to be injected is defined within the same bundle (use combinedbean.jar) and when it is defined in a different bundle (use statelessbean1.jar and statelessbean2.jar) the reference is injected properly and no lookup takes place:
@EJB(mappedName="SL2")
private Stateless2Remote m_stateless2 = null;
@EJB
private Stateless2Remote m_stateless2NotAutoInjected = null;
// ... and some code using it:
if (m_stateless2 == null) {
// '@EJB' injection did not take place, performing lookup
try {
m_stateless2 = (Stateless2Remote)new InitialContext().lookup(
String.format("%s_%s@Remote", "net.luminis.ezb.stateless2.impl.Stateless2Impl", Stateless2Remote.class.getName()));
} catch (NamingException e) {
e.printStackTrace(); // lookup failed.
}
}
Note though, that the mappedName must be set both here and in the implementation of the session bean to be injected. If this is not done, EZB cannot find/inject it. I.e. in the code above, at the point where m_stateless2 has been set, the member variable m_stateless2NotAutoInjected is still null.
Entity-only bundles
When deploying ones bundles you’re likely to combine related functionality. It’s possible to simply put everything in a single bundle, but not desirable; the more fine-grained your design, the easier it is to re-use a specific bit of functionality. When you decide to define an entity-only bundle, EZB requires that you include the line
net.luminis.ezb.entitybeans.Kangaroo
both in persistence.xml of the entity-bundle, but also in all bundles using the entity-bundle. This inconvenience may be corrected, but for now, it’s not a very flexible way of working; when you add an entity bean to your entity-bundle, you not only have to update the persistence.xml in that bundle, but also in all bundles using it!
Rollback
Finally, the source code attached to this blog also includes an example of how EZB handles a transaction rollback. It is possible to trigger such a rollback by using:
m_sessionContext.setRollbackOnly();
to signal the session to perform a rollback of every action associated with the current transaction. In this example the functionality is illustrated through using the command
ezb use_injected_max
which not only uses an injected session bean to create a Kangaroo entity, but also triggers a rollback if 4 Kangaroos have already been created. (Check the methods addKangaroo() and addKangarooWithMaximumCheck() in Stateless2Impl to find out more.
Unboxing the Bug
Geplaatst door Marcel Offermans in Uncategorized op 5 januari 2009
First of all, happy new year! I’m sure 2009 will be a great year for everybody.
Today, the long anticipated Bug arrived in the mail. I met Ken almost a year ago now, at EclipseCon, where he did a very nice demo of a new device. Call it LEGO for adults. The box contains hotpluggable hardware modules, such as motion sensors, a touch screen, a GPS locator, a generic I/O board for custom extensions which makes the hardware as dynamic as the software inside. That software, of course, is OSGi based, so there is full modularity there too. Add a well designed SDK for developing and deploying bundles for the system and you have a system that is very appealing to developers and can be used for all kinds of technology demos. Today’s blog ends with a nice picture of the opened box, showing some of the goodies inside. Expect more in depth articles in the near future!

Enterprise Javabeans 3 in OSGI
Geplaatst door Peter Doornbosch in Uncategorized op 19 december 2008
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!
The OSGi Community Event in Berlin 2008
Geplaatst door Marcel Offermans in Uncategorized op 6 november 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.
Persistence in OSGi with OpenJPA — part 2
Geplaatst door Peter Doornbosch in Uncategorized op 29 augustus 2008
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> 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;, etc), but also we need to explicitely export the
!org.apache.tools.ant.types;
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.
ApacheCon EU 2008
Geplaatst door Marcel Offermans in Uncategorized op 11 april 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.
JPA persistence in OSGi with openJPA
Geplaatst door Peter Doornbosch in Uncategorized op 24 maart 2008
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.
OSGi DevCon EclipseCon and OSGi Security
Geplaatst door Marcel Offermans in Uncategorized op 10 maart 2008
I hope you registered already for this years OSGi DevCon at EclipseCon? It’s less then two weeks away and it would be great to see you there.
In case you did I’d like to urge you to consider our talk about OSGi security.
The program looks very interesting and OSGi is well represented throughout the conference.
Marcel Offermans and Karl Pauls will give a tutorial on the first day about Building Secure OSGi Applications.
This Tutorial focuses on embedding various OSGi framework implementations namely, Eclipse Equinox and Apache Felix, into applications as a means of plugin mechanism while taking advantage of the often overlooked benefits of this solution: security. The OSGi specifications have an extensive and very powerful security model that eases the difficult task of building secure, dynamically extensible, applications so don’t miss out on this opportunity.
People in and around the Netherlands, however, have another possibility to get to see this as we will give a boiled down version of the tutorial at the NLJUG jspring 2008 as well.
Thats all for today and we look forward to seeing you in Santa Clara!
regards,
OSGi on Google Android using Apache Felix
Geplaatst door Marcel Offermans in Uncategorized op 25 november 2007
UPDATE: A lot has changed in the world of Android & OSGi since writing this post. For the latest developments around this topic, go to: EZdroid community
Since Android 1.5 it is now possible to run Apache Felix without any changes on the phone!
So I was playing around with the Android Google is building … As somebody involved with OSGi for quite some years and a regular contributor to Apache Felix (the OSGi implementation of the Apache Software Foundation) the objective is clear: this platform needs an OSGi framework and Apache Felix is what it is going to be!
The task at hand can be split in two parts namely, figure out how to run the framework itself and extend it to be able to dynamically load bundles.
The former shouldn’t be a big problem because Apache Felix is easily portable and I personally made it run on a quite a number of JVMs. The later qualifies as tricky because for not yet publicly announced reasons Google chooses to not really provide a real JVM but something similar called dalvik.
One of the biggest differences (apart from added API) is that dalvik doesn’t execute Java bytecode directly but needs its own format. Tools are provided to convert from existing Java bytecode to dalvik alas, the conversion is not done at runtime.
Apache Felix on Google Android
The first step is to find the actual runtime on the emulator to save me going through the hassle of rebuilding and redeploying all the time:
> emulator &
> adb shell
# /system/bin/dalvikvm -Xbootclasspath:/system/framework/core.jar -version
DalvikVM version 0.2.0
Copyright (C) 2007 Google, Inc.
Blah blah blah LICENSE blah blah.
Notice the funny last line – I’m not making this up
.
So for a straight forward scenario all we need is the felix.jar with the added dalvik bytecode:
> dx --dex --output=classes.dex bin/felix.jar > aapt add bin/felix.jar classes.dex > adb push bin/felix.jar /root/felix/bin/felix.jar > adb shell # cd root/felix # /system/bin/dalvikvm -Xbootclasspath:/system/framework/core.jar \ -classpath bin/felix.jar org.apache.felix.main.Main
Voila (well, in reality I needed to patch a little to get to this point because there was a bug or two – I’ll commit the fix to trunk).
Dynamically Loading Bundles on Google Android
The next part is the most critical one because we will need to do something that is officially not supported. We need to be able to load bundles i.e., dynamically load code. There is a way to do something in this direction in the official api but nothing close to the power of what we need (and want) for OSGi — hence, I spend sometime finding a loop-hole. It turns out that the normal ClassLoader approach will throw an exception saying that it is not possible to load java byte code. Fortunately, there is a class available that allows to load classes from dex files.
private static final Constructor m_dexFileClassConstructor;
private static final Method m_dexFileClassLoadClass;
static
{
Constructor dexFileClassConstructor = null;
Method dexFileClassLoadClass = null;
try
{
Class dexFileClass = Class.forName("android.dalvik.DexFile");
dexFileClassConstructor = dexFileClass.getConstructor(
new Class[] { java.io.File.class });
dexFileClassLoadClass = dexFileClass.getMethod("loadClass",
new Class[] { String.class, ClassLoader.class });
}
catch (Exception ex)
{
dexFileClassConstructor = null;
dexFileClassLoadClass = null;
}
m_dexFileClassConstructor = dexFileClassConstructor;
m_dexFileClassLoadClass = dexFileClassLoadClass;
}
private Object m_dexFile = null;
public synchronized Class getDexFileClass(String name, ClassLoader loader)
throws Exception
{
if (m_dexFile == null)
{
if ((m_dexFileClassConstructor != null) &&
(m_dexFileClassLoadClass != null))
{
m_dexFile = m_dexFileClassConstructor.newInstance(
new Object[] { m_file });
}
else
{
return null;
}
}
return (Class) m_dexFileClassLoadClass.invoke(m_dexFile,
new Object[] { name.replace('.','/'), loader });
}
This is the equivalent to using com.sun.* classes because the class is not inside the official package namespace but at any rate:
> dx --dex --output=classes.dex \ bundle/org.apache.felix.shell-1.1.0-SNAPSHOT.jar > aapt add bundle/org.apache.felix.shell-1.1.0-SNAPSHOT.jar classes.dex > adb push bundle/org.apache.felix.shell-1.1.0-SNAPSHOT.jar \ /root/felix/bundle/org.apache.felix.shell-1.1.0-SNAPSHOT.jar > dx --dex --output=classes.dex \ bundle/org.apache.felix.shell.tui-1.1.0-SNAPSHOT.jar > aapt add bundle/org.apache.felix.shell.tui-1.1.0-SNAPSHOT.jar \ classes.dex > adb push bundle/org.apache.felix.shell.tui-1.1.0-SNAPSHOT.jar \ /root/felix/bundle/org.apache.felix.shell-1.1.0-SNAPSHOT.jar
We also need a configuration that will make use of the bundles:
> adb push conf/config.properties /root/felix/conf/config.properties > adb shell # cd root/felix # /system/bin/dalvikvm -Xbootclasspath:/system/framework/core.jar \ -classpath bin/felix.jar org.apache.felix.main.Main Welcome to Felix. ================= -> ps START LEVEL 1 ID State Level Name [ 0] [Active ] [ 0] System Bundle (0.0.0) [ 1] [Active ] [ 1] Apache Felix Shell Service (1.1.0.SNAPSHOT) [ 2] [Active ] [ 1] Apache Felix Shell TUI (1.1.0.SNAPSHOT) -> shutdown
Now, for the added fun and as a prove of concept we are going to use the telnet bundle available form the OBR side. It is a little bit more involved because of an inner jar that needs to be processed as well.
> mkdir unpack && cd unpack > jar -xf ../bundle/telnetd.jar > dx --dex --output=classes.dex \ com/softsell/open/osgi/telnetd/dtw.TelnetD.jar > aapt add com/softsell/open/osgi/telnetd/dtw.TelnetD.jar \ classes.dex > rm classes.dex > jar -cmf META-INF/MANIFEST.MF ../bundle/telnetd.jar * > cd .. && rm -rf unpack > dx --dex --output=classes.dex bundle/telnetd.jar > aapt add bundle/telnetd.jar classes.dex > adb push bundle/telnetd.jar /root/felix/bundle/telnetd.jar > adb shell # cd root/felix # /system/bin/dalvikvm -Xbootclasspath:/system/framework/core.jar \ -classpath bin/felix.jar org.apache.felix.main.Main Welcome to Felix. ================= -> ps START LEVEL 1 ID State Level Name [ 0] [Active ] [ 0] System Bundle (0.0.0) [ 1] [Active ] [ 1] Apache Felix Shell Service (1.1.0.SNAPSHOT) [ 2] [Active ] [ 1] Apache Felix Shell TUI (1.1.0.SNAPSHOT) -> install file:bundle/telnetd.jar Bundle ID: 3 -> start 3 [Listening to Port 6623 with a connectivity queue size of 5]
With a little bit of work we are now able to telnet into our framework (we first have to add an redirect of the port):
> telnet localhost 5554 Trying ::1... Connected to localhost. Escape character is '^]'. Android Console: type 'help' for a list of commands redir add tcp:4711:6623 OK quit
Now the framework should be reachable on localhost under port 4711:
> telnet localhost 4711 Welcome to the SoftSell OSGI Telnet Server Available Services: Felix Enter Choice> Felix Welcome to the OSGI command shell ================================= -> ps ID State Level Name [ 0] [Active ] [ 0] System Bundle (0.0.0) [ 1] [Active ] [ 1] Apache Felix Shell Service (1.1.0.SNAPSHOT) [ 2] [Active ] [ 1] Apache Felix Shell TUI (1.1.0.SNAPSHOT) [ 3] [Active ] [ 1] telnetd (1.0.0) -> shutdown connection closed by foreign host.
Success! With a small patch that enables to load classes from a dex file dynamically we have an OSGi framework working on Google’s Android. I will commit the patch for the bugs soon and the binary as well as the real patch are available from our opensource server.
That’s all for today; happy bundle hacking


