<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Luminis Software Development &#187; Apache OpenJPA</title>
	<atom:link href="http://lsd.luminis.eu/en/tag/apache-openjpa/feed/" rel="self" type="application/rss+xml" />
	<link>http://lsd.luminis.eu</link>
	<description></description>
	<lastBuildDate>Wed, 28 Dec 2011 20:44:50 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Persistence in OSGi with OpenJPA &#8212; part 2</title>
		<link>http://lsd.luminis.eu/en/persistence-in-osgi-with-openjpa-part-2/</link>
		<comments>http://lsd.luminis.eu/en/persistence-in-osgi-with-openjpa-part-2/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 11:18:23 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apache Felix]]></category>
		<category><![CDATA[Apache OpenJPA]]></category>
		<category><![CDATA[OSGi]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=138</guid>
		<description><![CDATA[Follow up of the previous blog entry on using Apache OpenJPA in an OSGi framework. This installment focuses on creating separate, independent bundles, which makes it even easier to apply OpenJPA in OSGi. ]]></description>
			<content:encoded><![CDATA[<p>
In the <a href="http://blog.luminis.nl/roller/luminis/entry/jpa_persistence_in_osgi_with">previous</a> blog entry on openJPA in OSGi, we showed that it is fairly easy to use<br />
openJPA within an OSGi context. This was demonstrated by creating a bundle that<br />
provided a persistence service, that was able to persist and list sample domain<br />
objects. As the goal was to get it working, we didn&#8217;t bother about separating stuff<br />
over several bundles and put all in one bundle. In this blog, we&#8217;ll show how to make it<br />
work with separate bundles, and how this simplifies using JPA within an OSGi context.
</p>
<p>
There are two disadvantages with respect to the single bundle approach (apart from<br />
that it&#8217;s just ugly). Suppose you would develop deploy several bundles that provide<br />
persistence services, and that these would all contain the OpenJPA jar (2.8 M) and all<br />
of its supporting libraries (another megabyte). Having copies of these jars in each<br />
bundle whould be a waste of space (disk space <em>and</em> memory!) and if you would<br />
like to update one library, you&#8217;d have to update all bundles. Of course, it would be<br />
much better if each &#8220;component&#8221; (whatever that me be) is in its own bundle.
</p>
<p>
Another issue is that the domain objects (in the code sample the <code>Person</code><br />
class) are bundled together with the persistence service. This is not ideal, as you can<br />
image that domain objects can be used without persistence. Bundling them together would<br />
require each application that uses domain objects, to have the persistence service<br />
<em>bundle</em> to be installed as well. Having the domain objects in a separate,<br />
independant bundle, results in a more modular configuration.
</p>
<h3>A domain bundle</h3>
<p>
We&#8217;ll start with the last issue, as this is the simplest one to fix. Starting point is<br />
the sample code we developed last time (download the <a href="http://blog.luminis.nl/roller/luminis/resource/peter/jpa_in_osgi2.zip" onClick="javascript: pageTracker._trackPageview('/downloads/jpa_in_osgi2.zip'); ">zip</a> for all sample code).<br />
The test client, a bundle that extends the<br />
Felix command shell with a simple command to call our persistence service, is exactly<br />
the same as last time. However, if you compare the first build file<br />
(<code>build1.xml</code>) of the jpa-sample bundle with the ones from the previous blog<br />
entry, you&#8217;ll notice differences with respect to imports of the sample bundle. This is<br />
the result of upgrading to OpenJPA 1.1.0. With this new OpenJPA version, a number of<br />
(obscure) dependencies (oracle, apache.avalon, weblogic) seem to be vanished, and also<br />
commons-logging doesn&#8217;t seem to be required anymore, so we could clean up the<br />
<code>&lt;bundle&#038;gt</code> task a bit.
</p>
<p>
Separating the domain classes is easy: create a bundle that only contains the<br />
<code>net.luminis.sample.jpainosgi.domain</code> package. At the same time, we&#8217;ll<br />
remove this package from the existing <code>jpasample</code> bundle (that is now<br />
renamed to jpa-sample-service). This is not<br />
required (OSGi can handle several bundles providing the same package), but we want to<br />
ensure that our new setup works when the domain classes are in the domain bundle only.<br />
However, as the domain classes use the <code>javax.persistence</code> package, this is<br />
not enough: someone must export this package in order to make the domain bundle<br />
resolvable. As this package is in the jpa-sample-service bundle, we&#8217;ll add an extra<br />
export there (<code>build2.xml</code>).
</p>
<p>
If you&#8217;d deploy these two bundles in Felix and test it, you&#8217;d notice this works. But<br />
it&#8217;s not yet perfect: due to the <code>javax.persistence</code> package that is<br />
provided by the jpa-sample-service bundle, our newly created domain bundle still needs<br />
the service bundle. That&#8217;s not we wanted, the domain bundle should be completely<br />
independent from the service bundle! Hence, we must move out the<br />
<code>javax.persistence</code> from the service bundle and make it a separate bundle.
</p>
<h3>Supporting libraries</h3>
<p>
The OpenJPA distribution comes with an implementation of the<br />
<code>javax.persistence</code> package<br />
(<code>geronimo-jta_1.1_spec-1.1.jar</code>). Turning this library into an OSGi bundle<br />
is not difficult, and can be easily achieved with the Bnd tool (*).<br />
But creating these bundles by hand is not necessary anymore, because the<br />
<code>javax.persistence</code> and <code>javax.transaction</code> libraries that are<br />
shipped with Apache Geronimo since version 2.1, are already OSGi bundles.<br />
If you download the 2.1.2 Geronimo release,  you&#8217;ll find the libraries in the<br />
<code>geronimo-jetty6-javaee5-2.1.2/repository/org/apache/geronimo/specs</code><br />
subdirectory.
</p>
<p>
There are more common libraries that are used by OpenJPA and that can be easily<br />
stripped from the bundle: the most used Apache Commons libraries are nowadays released as OSGi<br />
bundles too. Unfortunately, the ones shipped with OpenJPA are not OSGi ready, but the<br />
newest releases of Commons Collections, Commons Lang and Commons Pool are (see<br />
<a href="http://wiki.apache.org/commons/CommonsOsgi">overview</a>). So you can simply<br />
download these new versions and install them right away in your OSGi framework.
</p>
<p>
The Postgres JDBC driver is not yet available as OSGi bundle, so i fixed this by hand<br />
(with a little help from Bnd). You can download this bundle, as well as the Bnd<br />
configuration file used to create this bundle, from the<br />
<a href="https://opensource.luminis.net/confluence/display/SITE/openJpa+on+OSGi">luminis open source server</a>.<br />
This results in a much smaller jpa-sample-service<br />
bundle (<code>build4.xml</code>).
</p>
<h3>OpenJPA OSGi bundle</h3>
<p>
The final step, removing the openjar itself from our bundle, is a little bit more<br />
tricky. We start by creating a bundle from the OpenJPA jar file. This time the Bnd<br />
configuration file is less trivial; not only we must provide the (do-not)import<br />
specifications that were previously in the build file (<code>!org.apache.tools.ant;<br />
!org.apache.tools.ant.types;</code>, etc), but also we need to explicitely export the<br />
packages that will be needed by other bundles. This leads to an OSGi enabled version of<br />
the OpenJPA jar (download it <a href="https://opensource.luminis.net/confluence/display/SITE/openJpa+on+OSGi">here</a>).<br />
Next we remove the openjpa stuff from our jpa-sample-service bundle. Trying to run this<br />
version results in an &#8220;Creating EntityManagerFactory failed!&#8221; error. What&#8217;s going on here?
</p>
<p>
To understand what&#8217;s going on, we must understand how the generic<br />
<code>javax.persistence.Persistence</code> class, finds a specific<br />
<code>EntityManagerFactory</code> (since that class is part of the JPA implementation<br />
you use, in constract to the Persistence class that bootstraps it). The find out which<br />
JPA implementation you&#8217;d like the use, the Persistence class searches the classpath for<br />
a provider configuration file in the <code>META-INF/services</code> resource<br />
directory, see <a<br />
href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">Jar<br />
file specification</a> (actually, it asks the thread-context-classloader to list all<br />
these files). In our old scenario, with the openjpa jar inside the bundle, this worked<br />
well because the openjpa.jar was on the bundle-classpath (and hence, could be loaded by<br />
the bundle classloader, that was set as context-classloader). But now, these service<br />
definitions are in another bundle and it is not possible to load these resources from<br />
outside (it is possible to load resources from another bundle, but not in this way).
</p>
<p>
We can solve this problem by explicitly telling the Persistence class which persistence<br />
provider we want. This is possible by passing a property:</p>
<pre>
props.put("javax.persistence.provider", "org.apache.openjpa.persistence.PersistenceProviderImpl");
</pre>
<p>Hard-coding this is of course bad style, as we would tie our persistence service to one<br />
specific JPA implementation. In production ready software, one would make this configurable.
</p>
<p>
Now, the Persistence class knows which persistence provider (class) to create. We must<br />
only ensure that this class is visible for the jpa-sample-service bundle: it must<br />
import <code>org.apache.openjpa.persistence</code> and <code>org.apache.openjpa.jdbc.kernel</code>. With this<br />
setup (<code>build5.xml</code>) the bundle can start and create an EntityManagerFactory.
</p>
<p>
Unfortunately, this does not mean that calling the persistence service succeeds. When<br />
you try, you&#8217;ll get a <code>ClassNotFoundException</code> for the <code>Person</code> class. This is caused by<br />
the fact that OpenJPA tries to load the <code>Person</code> class from the same classloader that has loaded<br />
the OpenJPA classes. In this case, that is the bundle classloader of the <code>openjpa.jar</code><br />
bundle, which of course, cannot find the <code>Person</code> class (it does not import it). In the<br />
previous setup, both the openjpa.jar and the <code>Person</code> class were in the same bundle and<br />
thus loaded via the same (bundle) classloader.
</p>
<p>
We can solve this by setting the thread context classloader, as OpenJPA tries that<br />
classloader too. The disadvantage of this approach is that we have to add<br />
<code>setContextClassLoader()</code> calls to each and every method in our service<br />
implementation that uses JPA, e.g.</p>
<pre>
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);
}
</pre>
<p>Of course, this is not what we want. We want to be able to use a &#8220;normal&#8221; piece of<br />
(JPA) persistence code, without change, in a service implementation. The classloader<br />
fiddling is an infrastructure aspect, that should be separated from our business<br />
code. A simple solution is to use a proxy object that takes care of the context<br />
classloader, see the sample source code for details.
</p>
<p>
Setting the context classloader solves the class not found issue, but reveals another<br />
one: OpenJPA now complains that the <code>Person</code> class is not enhanced. This is strange,<br />
because OpenJPA enhance persistent classes on the fly &#8211; after all, that is how it<br />
worked in all the previous samples. I tried to track down this issue; it has to do with<br />
a difference between the classloader that is used to enhance the classes and the one<br />
that is used for accessing these classes. I&#8217;m not sure yet whether this is an OpenJPA<br />
or an OSGi (or Felix) issue. Anyway, it&#8217;s easy to solve by enhancing the classes<br />
beforehand. If you run the <code>enhance</code> task in build6.xml before the<br />
<code>bundle</code> task, it creates a domain bundle with pre-enhanced domain<br />
classes. Deploy this bundle in Felix, and see how it all works fine now!
</p>
<p>
We finally arrived at the situation with two very small sample bundles, that contain no<br />
infrastructural libraries anymore. All libraries used are now bundles on their own, and<br />
deploying these in an OSGi framework is all what it takes to make it work.
</p>
<h3>Conclusion</h3>
<p>
We showed that using OpenJPA in an OSGi context is very easy. An OSGi service<br />
implementation that uses OpenJPA, can be implemented in the same way you would do when<br />
used outside OSGi. Although there is one small difference, the need for setting the thread context<br />
classloader upon each service invocation, this can be easily hidden by using a<br />
proxy. If you want to maximize ease of development, and have no worries about the<br />
overhead caused by using dynamic proxies, you could use a dynamic proxy that<br />
automatically delegates all methods in the interface.
</p>
<p>
The bottom line is that using OpenJPA within an OSGi context is painless. That makes<br />
OpenJPA a perfect solution for introducing persistency in an OSGi based application.</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.eu/en/persistence-in-osgi-with-openjpa-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JPA persistence in OSGi with openJPA</title>
		<link>http://lsd.luminis.eu/en/jpa-persistence-in-osgi-with-openjpa/</link>
		<comments>http://lsd.luminis.eu/en/jpa-persistence-in-osgi-with-openjpa/#comments</comments>
		<pubDate>Mon, 24 Mar 2008 20:46:16 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apache Felix]]></category>
		<category><![CDATA[Apache OpenJPA]]></category>
		<category><![CDATA[OSGi]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=140</guid>
		<description><![CDATA[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 take a look at using openJPA in a Apache Felix OSGi container.]]></description>
			<content:encoded><![CDATA[<p>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&#8217;ll try to get openJPA to work in Apache Felix. All source code used for this experiment can be found in <a href="http://blog.luminis.nl/luminis/resource/peter/jpa_in_osgi.zip" onClick="javascript:pageTracker._trackPageview('/downloads/jpa_in_osgi1.zip'); ">this zip</a>.
</p>
<p>
For our experiments, we take a simple JPA example, consisting of one entity class <code>Person</code> and a <code>Persister</code> class that will either list all the person items in the database, or add a new one. For example, its <code>create</code> method looks like this:
</p>
<pre>
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();
    }
}
</pre>
<p>
Both operations (create &amp; 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.
</p>
<p>
The first step in our little experiment is of course to create a bundle for these classes. We&#8217;ll use the Bnd tool for this, wrapped in the ant task that is available on http://opensource.luminis.net. We&#8217;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 <code>Persister.initJPA()</code> method in its <code>start</code> method, that tries to create the <code>EntityManagerFactory</code>:</p>
<pre>
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.");
}
</pre>
<p>
Of course JPA can not function without its <code>persistence.xml</code> file, which we add in the META-INF directory of our bundle (see <code>build-attempt1.xml</code>).
</p>
<p>
Installing this bundle in Felix results in one unresolved package: <code>javax.persistence</code>. This is easy to understand: our </code>Person</code> class uses JPA annotations (<code>@Entity, @Id</code>). We'll take the <code>geronimo-jpa_3.0_spec-1.0.jar</code> 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 <code>build-attempt2.xml</code>).
</p>
<p>
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 <code>openjpa-1.0.2.jar</code> to the bundle and try again. If we try to load this bundle in Felix, it complains about an unresolved <code>org.apache.tools.ant.types</code> package. If we study the Import-Packages header generated by Bnd, we see a long list of missing dependencies, containing the usual suspects like <code>org.apache.commons.lang</code>, but also containing items like</p>
<ul>
<li>com.ibm.websphere.jtaextensions
<li>oracle.sql
<li>org.apache.tools.ant.taskdefs
<li>sun.misc
<li>weblogic.transaction
</ul>
<p>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 <code>build-attempt5.xml</code> for the exact list of ignored packages and the openJPA libaries that are added on the bundle classpath.
</p>
<p>
Note that the <code>geronimo-jta_1.1_spec-1.1.jar</code> that provides <code>javax.transaction</code> <em>is</em> 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 <code>javax.transaction.xa</code> subpackage). This leads to the strange behaviour that the bundle does not load with a <code>ClassNotFoundException</code>, even though the package <code>javax.transaction</code> can be resolved!
</p>
<p>
Unfortunately, adding all these jars did not resolve the issue of having no <code>EntityManagerFactory</code>. This turns out to be a classloader issue: the openJPA classes are on the bundle classpath, but the JPA bootstrap code (the <code>Persistence</code> class) doesn't know about the bundle classloader. This can be solved by passing the bundle classloader as context classloader:</p>
<pre>
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);
}
</pre>
<p>
Note the last line of this method: its considered good practice to switch back to the original context classloader before returning.
</p>
<p>
Now the <code>initJPA</code> 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 (<code>perscmd.jar</code>) that adds an interactive command to the Felix shell, that will talk to our <code>PersonPersistence</code> 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. <br />
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 <code>Person</code> classes, as the following trace of the Felix interactive shell shows:
</p>
<pre>
-> 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
->
</pre>
<p>
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.
</p>
<h3>Conclusion</h3>
<p>
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.<br />
Second, we created a sort of a work around for the unresolved imports, which should be solved differently. <br />
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.</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.eu/en/jpa-persistence-in-osgi-with-openjpa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

