<?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; Peter Doornbosch</title>
	<atom:link href="http://lsd.luminis.nl/author/peterd/feed/" rel="self" type="application/rss+xml" />
	<link>http://lsd.luminis.nl</link>
	<description></description>
	<lastBuildDate>Mon, 19 Jul 2010 06:45:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>nl</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>J-Spring 2009</title>
		<link>http://lsd.luminis.nl/j-spring-2009/</link>
		<comments>http://lsd.luminis.nl/j-spring-2009/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 18:17:24 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[buglabs]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[jspring]]></category>
		<category><![CDATA[lwuit]]></category>
		<category><![CDATA[mda]]></category>
		<category><![CDATA[News Item]]></category>
		<category><![CDATA[nljug]]></category>
		<category><![CDATA[OSGi]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=189</guid>
		<description><![CDATA[Aan de druk bezochte J-Spring Java conferentie in een zomers warm Spant! in Bussum, heeft <b>luminis</b> weer een flinke bijdrage geleverd: gratis tompouce bij de stand, een boekverloting, 3 presentaties over uiteenlopende onderwerpen en sponsor van de slotborrel!]]></description>
			<content:encoded><![CDATA[<p>Aan de druk bezochte J-Spring Java conferentie in een zomers warm Spant! in Bussum, heeft <strong>luminis</strong> weer een flinke bijdrage geleverd. Bij de stand werd de bezoeker getrakteerd op een overheerlijke tompouce (van de <em>echte</em> 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 <strong>luminis</strong> gesponsorde borrel!</p>
<p><img src="http://blog.luminis.nl/luminis/resource/peter/meerviltjes.jpg" alt="" /></p>
<p>De presentatie van Jaap Vriend ging over <a href="lwuit_een_lichtgewicht_ui_toolkit">LWUIT</a>, 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.</p>
<p>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.</p>
<p>Onze OSGi guru, Marcel Offermans, had een leuke demo samengesteld op basis van <a href="unboxing_the_bug">de leukste bug</a>. 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 <strong>luminis</strong> stand?</p>
<p>De presentaties kun je als pdf downloaden:</p>
<ul>
<li><a href="http://blog.luminis.nl/luminis/resource/jspring/lwuit.pdf">LWUIT, proberen of negeren?</a></li>
<li><a href="http://www.luminis.nl/downloads/JSpring2009_MDA.pdf">MDA: Slimmer ontwikkelen van Java EE applicaties</a></li>
<li><a href="http://www.luminis.nl/downloads/JSpring2009_DeLeuksteBug.pdf">De leukste Bug!</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/j-spring-2009/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Enterprise Javabeans 3 in OSGI</title>
		<link>http://lsd.luminis.nl/enterprise-javabeans-3-in-osgi/</link>
		<comments>http://lsd.luminis.nl/enterprise-javabeans-3-in-osgi/#comments</comments>
		<pubDate>Fri, 19 Dec 2008 15:36:16 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apache Felix]]></category>
		<category><![CDATA[easybeans]]></category>
		<category><![CDATA[ejb3]]></category>
		<category><![CDATA[ezb]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[OSGi]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=166</guid>
		<description><![CDATA[<img class="thumbnail" src="http://blog.luminis.nl/luminis/roller/luminis/resource/jaapv/easybean.jpg">

This blog will outline the findings of an investigation into the Easybeans product including all issues encountered (and how to solve them) to get a simple example running properly.]]></description>
			<content:encoded><![CDATA[<p>
Previous blogs (look <a href="http://blog.luminis.nl/roller/luminis/entry/jpa_persistence_in_osgi_with">here</a> and <a href="http://blog.luminis.nl/roller/luminis/entry/persistence_in_osgi_with_openjpa">here</a>) have shown that it&#8217;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.</p>
<p>This blog assumes that the felix 1.4.0 environment is used. All source code used and all relevant bundles can be found in <a href="http://blog.luminis.nl/luminis/resource/jaapv/example1.zip" onClick="javascript:pageTracker._trackPageview('/downloads/example1.zip'); ">this zip</a>.</p>
<p>Some of the reasons EJB3 can be of interest when moving beyond what JPA has to offer:</p>
<ul>
<li>container managed transactions;
<li>dependency injection.
</ul>
<p>For more detailed information on the advantages of EJB3, refer to <a href="http://www.javaworld.com/javaworld/jw-10-2008/jw-10-ejb3.html">this article on javaworld</a><br />
<br/><br />
Using EZB within an OSGi context may be of interest to you if you&#8217;re working with an:</p>
<ul>
<li>EJB3 environment and you&#8217;re thinking about migrating towards OSGi;
<li>OSGi environment, but you don&#8217;t have a satisfactory solution for handling persistency issues.
</ul>
</p>
<p>
In this blog we will use a simple example that uses some basic EJB3 functionality; we&#8217;ll use a <a href="http://felix.apache.org/site/apache-felix-shell-service.html">command line client</a> that connects to a <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts3.html">stateless session bean</a>. The session bean is able to interact with an <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts4.html">entity bean</a> called Wombat and is able to create, update and delete (Wombat) entities. We&#8217;ll walk through the specifics of each step below.</p>
<p>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):</p>
<pre>
    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);
</pre>
<p>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&#8217;s a class loader issue. When dealing with stateful beans, this mechanism does not work and a JNDI lookup must always be used.</p>
<p>
Following that, the session bean receives a command from the client, e.g. a &#8216;create&#8217; 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 <i>EntityManager</i> injected into the implementation by EZB (because of the <a href="http://edocs.bea.com/wls/docs100/ejb30/annotations.html#wp1424642">@PersistenceContext</a> annotation &#8211; default EJB3 behaviour) to persist the newly created Wombat entity:</p>
<pre>
    @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));
</pre>
</p>
<p>
The entity bean used (defined in Wombat.java) contains three EJB3 annotations, denoting it as an entity bean (&#8217;@Entity&#8217;), indicating which table to create/use for the entity (&#8217;@Table&#8217;) and indicating which of the bean&#8217;s attributes can be used as its primary key (&#8217;@Id&#8217;):</p>
<pre>
@Entity

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

    // [cut some code]

    @Id
    public int getId() {
        return m_id;
    }
</pre>
</p>
<h3>Update the Felix configuration</h3>
<p>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 <a href="http://felix.apache.org/site/apache-felix-usage-documentation.html#ApacheFelixUsageDocumentation-configuringfelix">configuration</a>.</p>
<p>A pre-configured <i>conf/config.properties</i> file can be downloaded from <a href="http://blog.luminis.nl/luminis/resource/jaapv/config.properties.example1">here</a>.<br />
Of course, you can also apply the required changes yourself; an overview of the changes that need to be applied to the <i>conf/config.properties</i> file will follow.</p>
<p>Note that you&#8217;ll need the file <i>config.properties</i> of a previous release to copy two specific configuration entries: &#8216;org.osgi.framework.system.packages&#8217; and &#8216;jre-1.x&#8217; (depending on the JRE used, this is a list of packages that are exported by default).<br />
Now, edit the <i>config.properties</i> of your newly installed Felix configuration and:</p>
<ul>
<li>Uncomment the &#8216;org.osgi.framework.system.packages&#8217; entry and set the value to the one copied from a previous release.
<li>Add the complete &#8216;jre-1.x&#8217; entry to (the bottom of) the file.
</ul>
<p>The &#8216;org.osgi.framework.system.packages&#8217; entry should now look something like:</p>
<pre>
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}}
</pre>
<p>Note that the last line (with the ${jre-${java.specification.version}} construct) includes all items that are set in the copied &#8216;jre-1.x&#8217; configuration and that this means that you <b>must</b> have at least 1 section in your config file that starts like:</p>
<pre>
jre-1.5=, \
 javax.accessibility; \
</pre>
<p>Also, add the sun.rmi packages to the <i>config.properties</i> file, which can now be done more cleanly through:</p>
<pre>
org.osgi.framework.system.packages.extra= \
 sun.rmi.server; \
 sun.rmi.transport; \
 sun.rmi.registry;
</pre>
<p>Finally, make sure Felix only logs a warning if it encounters unsupported fragment behavior through uncommenting the line with the felix.fragment.validation option:</p>
<pre>
felix.fragment.validation=warning
</pre>
<h3>Download the EZB bundles</h3>
<p>The required easybean jars can be downloaded from <a href="http://www.easybeans.net/xwiki/bin/view/Main/Downloads">here</a>. This blog is based on usage of the &#8216;1.1.0-M1&#8242; release, select that release (or possibly a newer release) and then download the package available under &#8220;OSGi bundles of EasyBeans&#8221;. Unzip the file and note the location of the &#8216;bundles&#8217; folder.</p>
<h3>Install the EZB bundles</h3>
<p>Note that this this step should be performed using a felix-1.0.x configuration or a felix-1.4.x configuration only!<br />
In order to install the bundles, start Felix (make sure you&#8217;re using the updated configuration!) and execute the following commands in Felix:</p>
<pre>
-> cd file:/&lt;absolute_path_to_bundle_folder&gt;/
-> 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
</pre>
<p>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 <i>easybeans-core-1.1.0-M1.jar</i> from the ezb bundles dir and use ant to create the bundles:</p>
<pre>
cd &lt;example1-location&gt;
cp &lt;ezb-bundledir-location&gt;/easybeans-core-1.1.0-M1.jar lib
ant clean bundle.all
</pre>
<p>Once that is done, you can use the jars that can be found in the output dir.</p>
<p>An interesting point to note for this section is the use of the &#8216;easybeans-agent&#8217; bundle. This bundle is used to stop and start the &#8216;ow2-util-event-impl&#8217;, the &#8216;ow2-util-jmx-impl&#8217;, the &#8216;easybeans-core&#8217; and all &#8216;easybeans-component&#8217; bundles in the right order (also refer to &#8216;issues encountered&#8217; section below).</p>
<h3>Issues encountered</h3>
<ul>
<li>When a bundle defines an entity bean in an exported package, it must import the package &#8216;javassist.util.proxy&#8217; with &#8216;optional&#8217; resolution;
<li>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;
<li>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);
<li>Injecting a session bean service that is not defined in the same bundle <a href="http://jira.easybeans.org/browse/EZB-322">is not (yet) possible</a>;
<li>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;
</ul>
<p>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.</p>
<h3>Conclusion</h3>
<p>All in all, the ability to use EJB3 related features from within OSGi is definitely a good thing, even though there&#8217;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!</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/enterprise-javabeans-3-in-osgi/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Persistence in OSGi with OpenJPA &#8212; part 2</title>
		<link>http://lsd.luminis.nl/persistence-in-osgi-with-openjpa-part-2/</link>
		<comments>http://lsd.luminis.nl/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.nl/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.nl/jpa-persistence-in-osgi-with-openjpa/</link>
		<comments>http://lsd.luminis.nl/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.nl/jpa-persistence-in-osgi-with-openjpa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java 6 on OSX?!</title>
		<link>http://lsd.luminis.nl/java-6-on-osx/</link>
		<comments>http://lsd.luminis.nl/java-6-on-osx/#comments</comments>
		<pubDate>Sun, 11 Nov 2007 19:20:35 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[technical]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mac os x]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=127</guid>
		<description><![CDATA[<img class="thumbnail" src="http://blog.luminis.nl/luminis/resource/peter/java6uprise-2.jpg">
Java developers using Mac OSX need to make their voice heard.
]]></description>
			<content:encoded><![CDATA[<p>
I haven&#8217;t been using OSX for long, only since the beginning of this year, but i very much liked it from the first moment (well, to be honest not from <em>very</em> first moment; it took a day to get used to it). It seemed to be the ideal Java development platform, but slowly it became clear that we would have to wait a while for Java 6. So we waited patiently for Leopard, but Apple let us down again.
</p>
<p>
What&#8217;s most frustrating about the whole situation, is that Apple doesn&#8217;t communicate at all about its plans with Java. In an attempt to make Apple stop ignoring the Java developer community, <a href="http://blogs.sun.com/bblfish/entry/vote_for_java6_on_leopard">this blog</a> started an action to make our voice heard. Of course, we support the 13949712720901ForOSX effort too. All we ask is that Apple is more open about a timeline for Java 6 support, or a statement that this will not happen at all (which would probably fuel initiatives to create a port of Java 6 by some other means).</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/java-6-on-osx/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with Spring-OSGi &#8212; part 2</title>
		<link>http://lsd.luminis.nl/getting-started-with-spring-osgi-part-2/</link>
		<comments>http://lsd.luminis.nl/getting-started-with-spring-osgi-part-2/#comments</comments>
		<pubDate>Wed, 26 Sep 2007 20:42:20 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apache Felix]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=145</guid>
		<description><![CDATA[<img class="thumbnail" src="http://blog.luminis.nl/luminis/resource/thumbnails/lego_thumb.gif">
The second installment of the hands-on guide to Spring-OSGi, focuses on using external OSGi services in a Spring bean and how to handle service dynamics...]]></description>
			<content:encoded><![CDATA[<p>
In the<br />
<a href="http://blog.luminis.nl/luminis/entry/getting_started_with_spring_osgi">previous</a><br />
blog entry about Spring-OSGi, we demonstrated how to develop a simple<br />
Spring-OSGi bundle that exposes a Spring bean as an OSGi service. In this installment<br />
we&#8217;ll have a look at how you can use OSGi services in a Spring-OSGi bundle.<br />
The sample code used in this blog builds on the sample of the previous blog<br />
and can of course be<br />
<a href="http://blog.luminis.nl/luminis/resource/peter/getting-started-with-SpringOSGi-part2.zip" onClick="javascript:pageTracker._trackPageview('/downloads/SprintOSGi-part2.zip'); ">downloaded</a> from our site.
</p>
<p>
For demonstrating the use of an external OSGi services, we&#8217;ll use a very simple bundle<br />
exposing an <code>AuditService</code> service that looks like this:</p>
<pre>
public interface AuditService
{
    public void audit(String action);
}
</pre>
<p>The bundle provides an implementation of this interface that simply prints a message to<br />
system out. You can download this bundle <a href="http://blog.luminis.nl/luminis/resource/peter/auditservice.jar">here</a>; of course the<br />
complete bundle source is available in the source<br />
<a href="http://blog.luminis.nl/luminis/resource/peter/getting-started-with-SpringOSGi-part2.zip">zip</a>. It&#8217;s a plain (non-Spring) bundle<br />
that use a standard OSGi activator; don&#8217;t bother if you don&#8217;t grasp all the details of this bundle<br />
implementation: we&#8217;ll just use it as an external service. If you install and start this<br />
bundle in Felix, you&#8217;ll see the new service appear when issue the <code>services</code> command.
</p>
<h3>Binding service to Spring bean</h3>
<p>
The next thing to do, is of course to adapt our <code>reversestringbean</code> bundle,<br />
to use this service. We change the <code>reverse</code> method to audit-log all<br />
invocations of the reverse method:</p>
<pre>
private AuditService m_auditService;

public String reverse(String arg) {
    if (m_auditService != null) {
        m_auditService.audit("reverse(String) called with argument '" + arg + "'");
    }
    ...
}
</pre>
</p>
<p>
If you have Felix running with the previous version of<br />
the <code>reversestringbean</code> bundle and made the change outlined above, you can<br />
replace the old bundle with the new version (issue<br />
an <code>update</code> command with the id of the old bundle and the file url of the<br />
new version), and see that the <code>reverse</code> command is still working, even<br />
though it has switched to the new version.<br />
(If you get an error like &#8220;Unresolved package in bundle 19: package;<br />
(package=nl.luminis.demo.audit)&#8221;, you forgot to install the audit bundle; install it<br />
and try to start the reversestring bundle again.)
</p>
<p>
The new <code>reversestringbean</code> implementation is not using the audit service yet, because the service<br />
reference is not set. When can make Spring do this, by specifying the service in<br />
the <code>spring.xml</code> file:</p>
<pre>
&lt;osgi:reference id="externalAuditService"
                interface="nl.luminis.demo.audit.AuditService"/>
</pre>
<p>and use this reference as property value for the bean that was already defined in the<br />
same <code>spring.xml</code> file:</p>
<pre>
&lt;bean name="reverseBean" class="nl.luminis.demo.reversestring.ReverseStringBean">
    &lt;property name="auditService" ref="externalAuditService"/>
&lt;/bean>
</pre>
<p>When you build the bundle with the updated <code>spring.xml</code> file and reload it,<br />
Spring will notice that<br />
the <code>reversestringbean</code> bundle requires an <code>AuditService</code>, and<br />
pass the bean a reference to that service. When you issue the <code>reverse</code><br />
command again, you&#8217;ll see the audit message printed to the console:</p>
<pre>
-> reverse hello there!
AuditService: reverse(String) called with argument ' hello there!'
!ereht olleh
->
</pre>
</p>
<h3>Service not available</h3>
<p>
Now it&#8217;s time for a little experiment, to see how things behave when the audit service<br />
is not (yet) available. After all, we&#8217;re now working in a service oriented environment<br />
and service orientation is all about dynamics.<br />
<br />
We&#8217;ll restart the Felix framework, with a non-active audit service. To do so, issue the<br />
stop command on the audit service bundle and restart Felix. The framework will remember<br />
each bundle&#8217;s last state, so after the restart, the state of the audit service bundle<br />
will be &#8220;Resolved&#8221; (check this with the <code>ps</code> command). Note that we can&#8217;t<br />
uninstall the audit service bundle, as it is the only bundle providing<br />
the <code>AuditService</code> <em>interface</em>, and this interface (its class file)<br />
is needed by the <code>reversestringbean</code> bundle. A better alternative would be<br />
to split the audit service bundle and have the interface and implementation in two<br />
separate bundles: in that case you could now uninstall the implementation bundle and<br />
leave the interface bundle &#8211; this is left as an exercise for the reader <img src='http://lsd.luminis.nl/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> .
</p>
<p>
Issue a <code>reverse</code> again: you&#8217;ll get a message (from the command bundle)<br />
telling you that there<br />
is no string service. If you&#8217;d study the output of the <code>services</code> command,<br />
you&#8217;ll notice that although the <code>reversestringbean</code> bundle is started and<br />
active, it is not publishing any service: not even Spring&#8217;s<br />
<code>org.springframework.context.ApplicationContext</code> service we saw earlier.<br />
The explanation for this behaviour is that Spring will not activate the bundle before<br />
all its required dependencies are satisfied. You can verify this by starting the audit<br />
service and trying again: now it works as before.<br />
<br />
To continue our little experiment, stop the audit service again, study the output of<br />
the <code>services</code> command and issue the <code>reverse</code> command<br />
again. This time, the reverse string service is still there, even though the bundle&#8217;s<br />
required services are not satisfied anymore. So, Spring refuses to start our bean when<br />
the required service(s) (i.e. the audit service) are not there, but it doesn&#8217;t bother<br />
to stop the bean when the required service(s) disappear. Personally I dislike this<br />
non-symmetric behaviour and I think it shows that Spring was never designed for dynamic<br />
systems: somehow they can&#8217;t really stop an ApplicationContext (and<br />
restart it later) once it is created, I guess.
</p>
<h3>Optional service dependency</h3>
<p>To return to our sample bundle that won&#8217;t start when there is not audit service:<br />
 this is not what we want. The <code>reversestringbean</code> bundle<br />
should always perform the reverse operation; whether or not the audit service is there<br />
(in a banking example this might not be the case, but for this example, assume<br />
auditting is not crucial).<br />
The solution is in the word &#8220;required&#8221;: if<br />
we define the audit service to be optional, Spring will start the bundle, even when the<br />
audit service is not there yet.</p>
<p>Let&#8217;s try this: add cardinality &#8220;0 to 1&#8243; to the service reference definition:</p>
<pre>
&lt;osgi:reference id="externalAuditService"
                interface="nl.luminis.demo.audit.AuditService"
                cardinality="0..1" />
</pre>
<p>and additionally, add the <code>lazy-init="true"</code> to the bean definition. Now<br />
build and reload the bundle and issue another <code>reverse</code> command. To your<br />
surprise (I guess&#8230;, at least to mine!), it still won&#8217;t work; you&#8217;ll get<br />
a <code>ServiceUnavailableException</code> now.<br />
Check the output of the <code>services</code> command: the reverse string<br />
service <em>is</em> published. What&#8217;s going on here?
</p>
<p>
The point is that, in constrast to &#8216;plain&#8217; OSGi behaviour, Spring provides the bean<br />
with a proxy to the service, instead of a plain Java reference to the service<br />
implementation (as the OSGi framework itself does). Moreover, this proxy is set,<br />
irrespective of whether the service is available. The<br />
<code>ServiceUnavailableException</code> is intentional: you should always be prepared<br />
to get an exception when calling an external service.<br />
<br />
I can agree with this last rule: in a dynamic environment, you can never be sure<br />
whether a service is there; even when it was there a few minutes ago, it might be gone<br />
at the very moment you&#8217;re using the service. However, in a case like this, I wouldn&#8217;t<br />
expect the service proxy to be passed to the bean in the first place, until the service it<br />
represents actually exists. We&#8217;ll come back to this in a minute.
</p>
<p>
Let&#8217;s add a try-catch block to the code around calling the service and try again.<br />
This time it works as expected, although it might take a little longer than you expect:<br />
that&#8217;s because Spring has a default wait time when it tries to find a service. You can<br />
skip this by adding a attribute <code>timeout="0"</code> to<br />
the <code>&lt;osgi:reference></code> element in the <code>spring.xml</code> file.<br />
Now, the service behaves as expected: it does its job whether or not the audit service<br />
is available, and it does it without any additional delay.
</p>
<h3>Dynamic services</h3>
<p>
There is an alternative to the setter injection, that better suits dynamic<br />
behaviour: callback methods on the bean. As you&#8217;d expect from the Spring framework,<br />
your bean doesn&#8217;t have to implement an interface in order to be listener; just add two<br />
methods and specify their names in the <code>spring.xml</code>:</p>
<pre>
&lt;osgi:reference id="externalAuditService"
                interface="nl.luminis.demo.audit.AuditService"
                cardinality="0..1">
  &lt;osgi:listener ref="reverseBean"
                 bind-method="serviceAdded"
                 unbind-method="serviceRemoved"/>
&lt;/osgi:reference>
</pre>
</p>
<p>Note that the signature of the methods is fixed to this (at least in Spring-OSGi<br />
1.0-m2; it was different in earlier versions, so it might as well differ in newer<br />
versions):</p>
<pre>
public void serviceAdded(AuditService service, Dictionary d) {
    m_auditService = service;
}

public void serviceRemoved(AuditService service, Dictionary d) {
    m_auditService = null;
}
</pre>
<p>Don&#8217;t forget to remove the (setter injection) property from the bean definition. If you<br />
add <code>println's</code> to these listener methods, you&#8217;ll see that these are indeed<br />
called exactly at the moment the service appears or disappears.
</p>
<p>
You might wonder what happens when the cardinality is set to something else, e.g. 1 to<br />
many 0 to many. In both cases, the setter that receives the service(s) is supposed to<br />
receive a collection instead of a single service reference. The collection is managed<br />
by Spring behind the scenes: each time you iterate over this collection, it&#8217;s contents<br />
may be different, as it reflects the current state of the OSGi framework. Handling of<br />
the case that there is no service is easy, as an iterator over the collection will<br />
return nothing. However, one has still to cover for the<br />
dreadfull <code>ServiceUnavailableException</code>, as a service may disappear between<br />
the moment you get its reference from the collection and call a method on it.
</p>
<h3>Conclusion</h3>
<p>
We&#8217;ve seen how a normal Spring bean can interact with external OSGi services, and that<br />
by using setter injection, the implementation of the bean doesn&#8217;t have to different<br />
from a bean that is used within Spring exclusively. On the other hand, we&#8217;ve also seen<br />
that a <code>ServiceUnavailableException</code> is always to be expected and that the<br />
setter injection solution doesn&#8217;t combine very well with the dynamic behaviour of a<br />
service oriented framework.<br />
<br />
If you want to get it right, you can&#8217;t get away with a normal Spring bean<br />
implementation that does not handle <code>ServiceUnavailableException's</code> and is<br />
not prepared to handle missing dependencies. It&#8217;s an illusion that you can take an<br />
existing Spring bean implementation and use it unmodified in an OSGi context. It&#8217;s<br />
similar to having to deal with remote calls: you can&#8217;t hide remoteness from your<br />
application, as remote calls might fail, and your code has to be aware of it &#8211; provided<br />
you aim at robust code, of course. The same holds for a dynamic service oriented<br />
environment: you have to deal with disappearing services, you can&#8217;t simply ignore<br />
that. That is what makes OSGi different from old fashioned Spring usage that always<br />
assumes that all beans are there, once the system is started.<br />
<br />
The good news though, is that with Spring-OSGi, handling dynamic service is possible<br />
and that it can&#8217;t be done without implementing specific interfaces. In that sense,<br />
Spring-OSGi is non-intrusive, just like plain Spring is. You can&#8217;t ignore the fact that<br />
you&#8217;ve to deal with disappearing services, but you can do it in a way that does not<br />
limit reuse of your beans in other (non-OSGi) environments.
</p>
<p>
Finally a tip for those who want to experiment with the Spring-OSGi framework: enable<br />
Spring (log4j) logging. It&#8217;s hard to get it all right the first time, especially with<br />
all the xml-configuration stuff, and sometimes errors are swallowed by the framework,<br />
leaving you in total dispair. Logging can enabled by passing a system property on the<br />
java command line: </p>
<pre>
-Dlog4j.configuration=file:///your/path/to/spring-log4j.properties
</pre>
<p>You&#8217;ll find a sample log4j.properties file in the source zip. Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/getting-started-with-spring-osgi-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with Spring-OSGi</title>
		<link>http://lsd.luminis.nl/getting-started-with-spring-osgi/</link>
		<comments>http://lsd.luminis.nl/getting-started-with-spring-osgi/#comments</comments>
		<pubDate>Sun, 26 Aug 2007 19:32:42 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Apache Felix]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=147</guid>
		<description><![CDATA[<img class="thumbnail" src="http://blog.luminis.nl/luminis/resource/thumbnails/lego_thumb.gif"> With the introduction of Spring OSGi, it becomes relatively easy to develop a Spring application 
as a number of separate OSGi bundles. This blog post gets you up and running with this new way of deploying Spring applications...  ]]></description>
			<content:encoded><![CDATA[<h2>Getting started with Spring-OSGi</h2>
<p>
With the introduction of <a href="http://www.springframework.org/osgi">Spring OSGi</a>,<br />
it becomes relatively easy to split up a Spring application in separate OSGi bundles,<br />
and have a much more modular application architecture, without all the classloading<br />
hassle you may encounter when deploying components in J2EE application servers.
</p>
<p>
The purpose of this series of blog posts is to get you started with Spring-OSGi. We&#8217;ll<br />
develop some simple examples that will get you up and running.<br />
Theoretically, it is possible to use Eclipse for developing OSGi bundles using Spring,<br />
but, at least in my experience, this is a bumpy road with lots of obstacles, and in the<br />
end it does not lead to better understanding of the concepts. Therefore, the samples<br />
presented here will be provided with simple ant build files and do not require special<br />
tools to build or deploy. The complete source code of the samples can be found in this<br />
<a href="http://blog.luminis.nl/luminis/resource/peter/getting-started-with-SpringOSGi.zip" onClick="javascript:pageTracker._trackPageview('/downloads/SpringOSGi-part1.zip'); ">zip file</a>.
</p>
<p>
OSGi is (a standard defining) a service oriented framework as well as a number of<br />
standard services that can be deployed on these frameworks. Key concepts are &#8220;bundles&#8221;<br />
and &#8220;services&#8221;. A bundle is essentially a normal Java jar file and is the unit of<br />
deployment, i.e. you can install, update and de-install them in a running<br />
framework. Each bundle can publish one or more services, that can be used by other<br />
bundles. Bundles can locate services by querying the OSGi service registry. One of the<br />
most important aspects of OSGi, is that even bundles that use each others services,<br />
have nothing more in common than the service interface. <br />
A complete introduction on OSGi is beyond the scope of this blog post, but there is<br />
enough information online, see for example<br />
<a href="http://www.osgi.nl">OSGi.nl</a>,<br />
<a href="http://www.aqute.biz/OSGi/Tutorial">www.aqute.biz/OSGi/Tutorial</a>,<br />
<a href="http://www.osgi.org">www.osgi.org</a>,<br />
<a href="http://felix.apache.org">felix.apache.org</a>.
</p>
<h3>Hello&#8230;, OSGi</h3>
<p>
We&#8217;ll start with a simple &#8220;hello world&#8221; like sample, that exposes a trivial Spring bean<br />
as an OSGi service. The next step will be to create a bundle that actually uses this<br />
service, so we can run the demo in an OSGi framework and experiment with this. Also,<br />
these samples will help us to setup the compile time and run time environment<br />
correctly.
</p>
<p>
As said, we start with a simple, not to say trivial (Spring) bean. Here is its source:
</p>
<pre>
package nl.luminis.demo.reversestring;

public class ReverseStringBean
{
    public String reverse(String arg) {
        String result = "";
        for (int i = arg.length() - 1; i >= 0; i--)
            result += arg.charAt(i);
        return result;
    }
}
</pre>
<p>
To make it Spring bean, we have to add a configuration file that defines the bean. In<br />
plain Spring this would be something like:
</p>
<pre>
&lt;beans xmlns="http://www.springframework.org/schema/beans"&gt;
  &lt;bean name="reverseBean"
        class="nl.luminis.demo.reversestring.impl.ReverseStringImpl"/&gt;
&lt;/beans>
</pre>
<p>
(omitting xml namespace stuff for brevity, see the zip for complete source).
</p>
<p>
Exposing beans as OSGi services is fairly simple in Spring-OSGi. Basically, the only<br />
thing you&#8217;ll have to do is to add an <code>&lt;osgi:service></code> element to the<br />
spring xml configuration file like this:
</p>
<pre>
&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;beans> &lt;!-- (again, namespace declarations omitted) -->

  &lt;bean name="reverseBean"
        class="nl.luminis.demo.reversestring.ReverseStringImpl"/>
  &lt;osgi:service ref="reverseBean"
                interface="nl.luminis.demo.string.ReverseString"/>

&lt;/beans>
</pre>
<p>
Of course, we need an interface that defines the service we&#8217;re exposing, so we define<br />
the <code>ReverseString</code><br />
interface and add the <code>reverseString()</code> method to it.
</p>
<p>
To make it a bundle, the last thing to do is add a manifest file with the (OSGi)<br />
required entries:
</p>
<pre>
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: ReverseStringBean
Bundle-SymbolicName: ReverseStringBean
Bundle-Version: 1.0.0
</pre>
<p>
Strictly speaking, not all of these entries are required, but it is common practice to<br />
have at least these entries in the manifest file.
</p>
<p>
This completes our first bundle. If you&#8217;re familair with OSGi you might wonder if our<br />
bundle doesnt&#8217; need a <code>BundleActivator</code>, that provides <code>start()</code><br />
and <code>stop()</code> lifecyle methods that the OSGi framework can call to start or<br />
stop our bundle. The answer is that it doesn&#8217;t need it, because Spring-OSGi works<br />
similar to the OSGi declarative service specification: the framework will inspect the<br />
service declaration and instantiate the service on our bundle&#8217;s behalf; instead of<br />
publishing the service ourselves (from within the BundleActivators start method), the<br />
framework &#8220;pulls&#8221; the service out of our bundle, so to speak.
</p>
<p><h3>Setting up the runtime environment</h3>
<p>Now it&#8217;s time to set up our run time environment. For the demo we will<br />
use <a href="http://felix.apache.org">Apache Felix</a> 1.0, but you can deploy the<br />
bundle in any OSGi framework, e.g. (Eclipse) Equinox, or Knopflerfish. Download felix<br />
and start it by executing the jar file in its bin directory and enter a profile<br />
name. If you enter <code>ps</code> on the prompt you&#8217;ll see that there are only three<br />
bundles active: the system bundle (i.e. the framework ifself) and two bundles that<br />
constitute the shell service that executes the commands your typing at the<br />
prompt. Install our demo bundle by using the <code>install</code> command, passing it a<br />
file url that points to the bundle:
</p>
<pre>
-> install file:///Users/peter/.../reverestringbean.jar
</pre>
<p>
You can <code>start</code> the bundle now, but it won&#8217;t register any services yet, as no<br />
one is paying attention to our service declaration in the <code>spring.xml</code><br />
file. Execute the <code>services</code> command to confirm this.
</p>
<p>
As the final step in setting up the run time environment, we&#8217;ll install the Spring-OSGi<br />
framework. For this demo, we used the <a href="http://sourceforge.net/project/showfiles.php?group_id=73357&#038;package_id=227224&#038;release_id=507778">milestone 2 release of Spring-OSGi 1.0</a>; newer versions should work also, but of course, small (presumably subtle) differences may occur.<br />
Make sure you download the &#8220;-with-dependencies&#8221; zip file.
</p>
<p>
Install these Spring-OSGi bundles from the <code>dist</code> directory:</p>
<ul>
<li>spring-osgi-core-1.0-m2.jar
<li>spring-osgi-extender-1.0-m2.jar
<li>spring-osgi-io-1.0-m2.jar
</ul>
<p>These bundles depend on (but do not include) the plain Spring code, so you have to install<br />
a number of bundles (all of which can be found in the <code>lib</code><br />
directory) that contain the plain spring framework modules:</p>
<ul>
<li>spring-core-2.0.5-osgi-m2.jar (from spring-core/2.0.5-osgi-m2/)
<li>spring-aop-2.0.5-osgi-m2.jar (from spring-aop/2.0.5-osgi-m2/)
<li>spring-beans-2.0.5-osgi-m2.jar (from spring-beans/2.0.5-osgi-m2/)
<li>spring-context-2.0.5-osgi-m2.jar (from spring-context/2.0.5-osgi-m2/)
<li>aopalliance.osgi-1.0-SNAPSHOT.jar (from aopalliance.osgi/1.0-SNAPSHOT/)
<li>backport-util-concurrent-3.0-SNAPSHOT.jar (from backport-util-concurrent/3.0-SNAPSHOT/)
</ul>
<p>Additionally, some <a href="http://www.slf4j.org/download.html">SLF4J</a> libraries<br />
have to be installed. SLF4J is a logging facade for several logging implementations,<br />
similar to Apache Commons Logging. An important difference with Apache Commons Logging<br />
is that in order to determine what implementation to use, it does not rely on<br />
classloading tricks that can cause a lot of <a href="http://www.qos.ch/logging/classloader.jsp">trouble</a>, especially when<br />
used in dynamic environments like an OSGi framework.
</p>
<p>
From SLF4J you need the following libraries:</p>
<ul>
<li>slf4j-api-1.4.3.jar (contains only the SLF4J API)
<li>slf4j-log4j12-1.4.3.jar (implementation of SFL4J, hard-wired to log4j)
<li>jcl104-over-slf4j-1.4.3.jar (100% compatible drop-in replacement for Commons Logging)
</ul>
<p>Just install them as normal bundles, these libraries are OSGi ready. The<br />
jcl104-over-slf4j library contains modified versions<br />
of <code>org.apache.commons.logging.Log.java</code> etc, that redirect to SLF4J. This<br />
will take care of libraries using the Commons Logging API.
</p>
<p>
As we&#8217;ll be using log4j as the logging implementation that does the real work, we&#8217;ll<br />
have to install that too. An OSGi compatible version of log4j can be found in the<br />
Spring OSGi package</p>
<ul>
<li>log4j.osgi-1.2.13-SNAPSHOT.jar (from src/spring-modules/spring-required-libraries/log4j/target)
</ul>
<p>but, you&#8217;ll have to build it first (with maven). Alternatively, you can download the<br />
file <a href="http://blog.luminis.nl/luminis/resource/peter/log4j.osgi-1.2.13-SNAPSHOT.jar">here</a>.
</p>
<p>
After you&#8217;ve installed these bundles, you can start them all. Note that if you try to<br />
start some bundles before you installed them all, you&#8217;re likely to get errors about<br />
unresolved packages; to avoid that you would have to install them in the right order.<br />
You&#8217;ll probably see some warnings about resources files and namespace handlers that<br />
can&#8217;t be found, which you can just ignore.
</p>
<p>
Now the Spring-OSGi extender is running, it should have discovered and published our<br />
service. Due to a bug in the M2 release (fixed in later releases), it doesn&#8217;t yet work this way and you have to<br />
restart our bundle. If you do so, you&#8217;ll get some warnings about BeanInfo classes not<br />
being found; ignore these too.
</p>
<p><h3>Using the service</h3>
<p>If you issue the <code>services</code> command once again, you&#8217;ll notice that our simple demo<br />
bundle provides to services: <code>nl.luminis.demo.string.ReverseString</code><br />
and <code>org.springframework.context.ApplicationContext</code>. The latter is the<br />
well known Spring application context, that is merely provided as OSGi service for<br />
debugging purposes (you shouldn&#8217;t use it to access a bean from outside its bundle).
</p>
<p>
Essentially, we&#8217;re ready now, as our first spring enabled bundle is up and running and<br />
publishes its service. However, we can&#8217;t be satisfied until we&#8217;ve actually seen it do<br />
something &#8220;usefull&#8221;. To make that happen, we&#8217;ll write an extension for the felix<br />
command interpreter, that will call our service. This extension will be a bundle on its<br />
own. As it hooks in into the Felix command shell, this of course is a Felix specific<br />
solution, but similar constructs exist for Equinox and Klopflerfish.
</p>
<p>
The heart of this command bundle is the <code>execute()</code> method, that tries to<br />
locate the service and calls it:</p>
<pre>
public void execute(String line, PrintStream out, PrintStream err)
{
    // (...)
    ServiceReference ref = m_context.getServiceReference("nl.luminis.demo.string.ReverseString");
    Object service = (ref != null)? m_context.getService(ref): null;
    if (service != null)
        try {
            out.println(((ReverseString) service).reverse(arg));
        }
        catch (Exception e) {
            err.println("calling reverse string service failed: " + e);
        }
    else {
        err.println("no reverse string service, ref=" + ref);
    }
}
</pre>
<p>See the source.zip for the complete source code.
</p>
<p>
After installing and starting the command bundle, you&#8217;ll notice the new &#8220;reverse&#8221; command in the<br />
help text:</p>
<pre>
-> help
...
install &lt;URL> [&lt;URL> ...]           - install bundle(s).
ps [-l | -s | -u]                   - list installed bundles.
resolve [&lt;id> ...]                  - attempt to resolve the specified bundles.
reverse &lt;arg>                       - reverses a string, using a ReverseString service
services [-u] [-a] [&lt;id> ...]       - list registered or used services.
...
</pre>
<p>and issuing this command will finally show that our service works correctly:</p>
<pre>
-> reverse  OSGi is cool!
!looc si iGSO
->
</pre>
</p>
<p>
This concludes our first working Spring-OSGi sample. It&#8217;s not yet a full-blown J2EE<br />
application, but it clearly shows what is needed to make a basic Spring-OSGi bundle<br />
work and have it publish a bean as an OSGi service. In future installments, we&#8217;ll have a<br />
look at using external OSGi services in our beans, and experiment with some less<br />
trivial bundles, including a simple web application and database access.</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/getting-started-with-spring-osgi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;top threads&#8221; plugin for JConsole</title>
		<link>http://lsd.luminis.nl/top-threads-plugin-for-jconsole/</link>
		<comments>http://lsd.luminis.nl/top-threads-plugin-for-jconsole/#comments</comments>
		<pubDate>Thu, 24 May 2007 19:46:34 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[jconsole]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=153</guid>
		<description><![CDATA[<img class="thumbnail" src="http://blog.luminis.nl/luminis/resource/thumbnails/topthreads_thumbnail.png" />

When troubleshooting large multi threaded java applications, an overview of the most active threads might help. The JConsole &#34;top threads&#34; plugin provides such an overview, based on the standard platform monitoring MBeans.]]></description>
			<content:encoded><![CDATA[<p>
When working with large (server side) java application, sometimes it<br />
would be nice if you could look inside, to see what thread is taking<br />
up so much cpu time, and why. Something similar to the Unix top<br />
command, but then showing all threads in one (java) application,<br />
instead of all processes in the system.
</p>
<p>
When I was looking for such a monitoring application, I came accross the 2.0 version of MC4J that<br />
provides a &quot;Thread Info&quot; panel that<br />
displays threads together with CPU usage; exactly what I<br />
needed. Unfortunately, there is only an alpha release of this MC4J<br />
version, that is not yet perfectly stable. Moreover, the thread info<br />
panel doesn&#8217;t handle applications with large amounts of threads very<br />
well. As the source code of this version of MC4J is not (yet)<br />
publically available, this option turned out to be a dead end.</p>
<p>
To my surprise, other applications with such functionality are hard to<br />
find. There are probably enough profiling applications that can do the<br />
job, but I wanted something simple, something JMX-based, that can used<br />
also to monitor applications running in production.</p>
<p>
There is however something called JTop, which is a plugin for<br />
JConsole. It&#8217;s actually a demo for the new (since Java 6) JConsole<br />
plugin API, that does show CPU usage per thread. It&#8217;s fairly basic and<br />
only shows total CPU usage, which is not very usefull. You would<br />
expect that (after a year), somebody would have extended the demo to<br />
something more useful, but as I couldn&#8217;t find anything like that, I<br />
thought I should give it a try myself.</p>
<p>
The result is a JConsole plugin that displays the top threads, sorted<br />
by cpu usage in the last sampling period. It also displays cpu usage<br />
history, and an average over the last 10 sampling periods.<br />
<img src="http://blog.luminis.nl/luminis/resource/peter/topthreads-plugin.png" />
</p>
<p>
To avoid ending up with an unresponsive user interface when monitoring<br />
applications with large number of threads, I took a few<br />
precautions. First of all, the plugin has it&#8217;s own refresh rate. It&#8217;s<br />
independent from the JConsole poll interval, which is 4 seconds by<br />
default. For applications with large amounts of threads, this is way<br />
too short: only retrieving all thread information can already take 4<br />
or 5 seconds! Although you can change the JConsole poll interval with<br />
a command line option, I thought it would be more convenient to be<br />
able to change it from the monitoring panel. It&#8217;s default set to 10<br />
seconds, which I think is reasonable in most cases. If you notice that<br />
cpu usage measurement takes too much of the application under test,<br />
just increase the sample period and see the RMI Connection thread that<br />
processes these request, sink in the list.
</p>
<p>
Another precaution was not to list all threads in the<br />
table. Displaying thousands of rows in a table is quite useless in any<br />
case, and I was afraid it would seriously harm<br />
performance. Eventually, diplaying that many rows turned out to be not<br />
much of a problem; I guess I still suffer from an prejudice with<br />
respect to Swing performance&#8230;</p>
<p>
Using MX4J also showed me that in a continuously refreshing table,<br />
it&#8217;s hard to select a thread in order to see it&#8217;s<br />
stacktrace. Therefore, in this plugin, tracing a thread is &quot;sticky&quot;:<br />
when you click a row in the table, the stacktrace of that thread is<br />
shown immediately and is refreshed with each new sample, until you<br />
deselect it or select another thread.
</p>
<p>
Even though having threads sorted by cpu usage is the logical thing to<br />
do, it&#8217;s not always convenient when you&#8217;re studying the results, as<br />
rows keeping moving with each refresh. To lock the rows to there<br />
current position, click the &quot;fix order&quot; button. The topmost rows<br />
(actually all rows with a non-zero cpu usage), will stay where they<br />
are. Rows that had a cpu usage of zero, but have a non-zero value<br />
in the next sampling periods, will appear just below these rows, to<br />
avoid that you oversee any thread that suddenly takes a large amount<br />
of cpu time.
</p>
<p>
You can run the plugin by downloading the <a href="http://blog.luminis.nl/luminis/resource/peter/topthreads.jar" onClick="javascript:pageTracker._trackPageview('/downloads/topthreads-1.0.4.jar'); ">jar file</a> and passing it to JConsole with the plugin option:<br />
jconsole -pluginpath topthreads.jar. When JConsole connects, it should have a seventh tab named &quot;top threads&quot;.</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/top-threads-plugin-for-jconsole/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Verrassende effecten bij een toString</title>
		<link>http://lsd.luminis.nl/verrassende-effecten-bij-een-tostring/</link>
		<comments>http://lsd.luminis.nl/verrassende-effecten-bij-een-tostring/#comments</comments>
		<pubDate>Fri, 30 Mar 2007 14:35:16 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=112</guid>
		<description><![CDATA[Dat de javadoc van <tt>Object.toString()</tt> slechts in vrij vage termen (&#34;string that textually represents this&#34;) spreekt over wat het resultaat van de aanroep zou moeten zijn, is doorgaans geen enkel probleem, maar in sommige gevallen kan een ietwat slordige implementatie leiden tot verrassende effecten, zelfs tot een aanzienlijk verlies van performance.]]></description>
			<content:encoded><![CDATA[<p>
Bij Java cursussen waarschuw ik de cursisten altijd om voorzichtig te zijn met de<br />
toString() methode en ook bij code reviews komt het wel eens aan de orde. Sommige mensen<br />
zijn geneigd &quot;iets&quot; te doen met het resultaat van een toString() aanroep (anders dan<br />
afdrukken of loggen) en het kost me nog wel eens moeite om mensen te overtuigen dat dat nogal<br />
riskant is.
</p>
<p>
Wat mij betreft is de redenering heel helder: weliswaar definieert de javadoc van<br />
Object dat het resultaat een &quot;concise but informative representation&quot; van het object<br />
moet zijn (en voor mensen goed leesbaar), maar dat laat nogal wat ruimte voor<br />
variatie. Als programmeur kun je er dus niet op vertrouwen dat hetgeen je terugkrijgt<br />
van toString bruikbaar is om er iets mee te doen of enige beslissing hierop te baseren.
</p>
<p>
Dit wordt nog wel eens afgedaan als een theoretische redenering. Immers, als je zelf de<br />
toString implementeert weet je precies wat hij teruggeeft, en waarom zou je die kennis<br />
niet kunnen gebruiken? Als je het heel netjes doet specificeer je in de javadoc heel<br />
precies wat de return waarde is, en niemand kan je wat maken.
</p>
<p>
Waar dit aan voorbij gaat, is dat &quot;derden&quot; die specifieke semantiek niet verwachten. Er komt een dag dat<br />
iemand anders de code aanpast of met een afgeleide class uitbreidt, en die gaat niet de<br />
javadoc van toString() bestuderen &#8211; die kent hij al. Zonder zich er van bewust te zijn<br />
breekt hij het (gewijzigde!) contract en is Leiden in last. En laten we wel wezen: op<br />
de keper beschouwd was het preciezer definieren van het toString resultaat al een<br />
wijziging in het contract. Hiermee wordt een belangrijk principe van &quot;good coding<br />
style&quot; overtreden: goede code bevat geen verrassingen.
</p>
<p></p>
<p>
<b>Aanroeper onbekend</b><br />
Een andere reden om op te passen met de implementatie van de toString method, is dat<br />
het onderdeel is van het Object contract en je nooit weet wie of wat je wanneer<br />
aanroept. Hoe vreselijk dit uit de hand kan lopen, merkte ik een tijdje geleden toen ik<br />
probeerde een performance probleem op te lossen.
</p>
<p>
Het ging om een applicatie die draaide op JBoss. De testers hadden het gevoel dat de<br />
applicatie onder zware belasting steeds langzamer werd &#8211; meer dan ze op grond van de<br />
belasting zouden verwachten. Met een profiler had ik van alles onderzocht, en ook wat<br />
kleinere issues opgelost, maar de klacht bleef.
</p>
<p>
Nadat ik op een gegeven moment wat had zitten monitoren met JConsole en eigenlijk<br />
gedachtenloos wat zat te klikken in de thread view, viel mijn oog op een stacktrace<br />
waarin een toString method werd aangeroepen van een van andere Queue class. Dat was<br />
verdacht, vooral omdat in die applicatie bij zware belasting nogal lange queues konden<br />
ontstaan. Het zou toch niet zo zijn dat&#8230;
</p>
<p>
Het was wel zo. De queue bevatte enkele duizenden of tienduizenden elementen en de<br />
toString leverde een string op van enkele megabytes groot (niet echt &quot;concise&quot;). De aanroep kwam uit een<br />
toString van een worker-thread class; waarschijnlijk had iemand daarin ooit de toString van<br />
de queue toegevoegd om beter te kunnen debuggen. En de verrassing was dat deze methode<br />
niet vanuit applicatie code werd aangeroepen, maar vanuit JBoss.
</p>
<p>
Ergens diep in de transactie en lock management van JBoss, wordt van een thread die in<br />
een wachtrij geplaatst wordt, de toString() aangeroepen; ook hier weer voor<br />
debugging en/of monitoring. Hoe drukker de applicatie, hoe meer locks, hoe vaker de<br />
toString werd aangeroepen en hoe drukker JBoss was met het uitrekenen van Strings die<br />
eigenlijk nooit gebruikt werden, in plaats van met het uitvoeren van applicatie code.
</p>
<p>
Het was zo&#8217;n vondst waarop je altijd hoopt als je performance problemen onderzoekt. De<br />
aanpassing was letterlijk in twee tellen gebeurd en de performance verbetering was echt<br />
aanzienlijk.
</p>
<p>
De moraal van het verhaal is duidelijk: geen gekke dingen doen in de toString, want je<br />
weet nooit wie het aanroept. En dat geldt niet alleen voor (afgeleide classes van)<br />
infrastructurele elementen zoals Thread, maar juist omdat toString onderdeel uitmaakt<br />
van het Object contract, voor alle classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/verrassende-effecten-bij-een-tostring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ScheduledThreadPoolExecutor horribly broken</title>
		<link>http://lsd.luminis.nl/scheduledthreadpoolexecutor-horribly-broken/</link>
		<comments>http://lsd.luminis.nl/scheduledthreadpoolexecutor-horribly-broken/#comments</comments>
		<pubDate>Thu, 29 Mar 2007 16:03:17 +0000</pubDate>
		<dc:creator>Peter Doornbosch</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[mobility]]></category>
		<category><![CDATA[social]]></category>
		<category><![CDATA[technical]]></category>
		<category><![CDATA[concurrency]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=100</guid>
		<description><![CDATA[The Java concurrent package defines a powerful task-execution/thread-pooling architecture with a few interesting threadpool implementations. Unfortunately, the implementation of one of these is a bit sloppy, which leads to nasty surprises when you're actually trying to use it.]]></description>
			<content:encoded><![CDATA[<p>
A while ago, I considered using the Java 5 ThreadPoolExecutor class for executing<br />
remote calls asynchronuously. The application I was working on needs to perform remote<br />
calls on large numbers of devices, and as remote calls can take quite a while, you<br />
don&#8217;t want these remote calls to wait on each other. Moreover, as remote calls might fail,<br />
e.g. due to network problems, a retry mechanism was also needed. The<br />
ScheduledThreadPoolExecutor, a subclass of the ThreadPoolExecutor, additionally allows you to<br />
schedule a task at a certain delay, which offers a simple and elegant solution for the<br />
retry mechanism: when a remote call fails, I only had to re-schedule it with a<br />
proper (increasing) delay and the scheduler would take care of it.
</p>
<p>
Thanks to the fact the ThreadPoolExecutors provides an abstract method afterExecute()<br />
that is called after execution of the task, I didn&#8217;t have to pollute my task<br />
implementation with retry logic, but could clearly separate these concerns. In the<br />
afterExecute() method of the (subclassed) ScheduledThreadPoolExecutor, I could ask the<br />
task whether it had succeeded, and if not I could simply reschedule it. And all this<br />
just in a few lines of code:</p>
<pre>
void afterExecute(Runnable task, Throwable exception) {
     if ((RemoteCallerTask) task).failed()) {
         super.schedule(task, 10, TimeUnit.SECONDS);
     }
}
</pre>
<p>When I first tested it, I got a ClassCastExeception. My first guess was that it might<br />
have something to do with different class loaders, but when I ran it in a debugger it<br />
turned out to be something that realy surprised me: the Runnable task that was passed<br />
to this method was not my do-a-remote-call task that I had passed to the executor, but<br />
something of a completely different type<br />
(ScheduledThreadPoolExecutor$ScheduledFutureTask<V>).</p>
<p>
Maybe I misinterpreted the documentation? I went back to the ThreadPoolExecutor<br />
javadoc. It talked about &#8220;methods that are called before and after execution of each<br />
task&#8221;, and the parameter description claimed the Runnable parameter to be &#8220;the runnable<br />
that has completed&#8221;. This seemed to match my expectations: you execute a Runnable task<br />
and that is what is passed to afterExecute. That would be the only sensible definition<br />
of a after-execution hook, wouldn&#8217;t it? As the source code is the best documentation, I<br />
checked the ThreadPoolExecutor source, which confirmed what I was expecting: the task<br />
that is run is passed to the beforeExecute() and afterExecute() hooks.</p>
<p>
A little bit of studying on the ScheduledThreadPoolExecutor source revealed why I got a<br />
ClassCastExeception: it wraps the (user supplied) task in a ScheduledFutureTask object<br />
before passing it to the base class (that puts it in the task queue). One of the<br />
reasons why this wrapper is needed, is because the ScheduledThreadPoolExecutor uses a<br />
DelayQueue to store the tasks and elements of this queue must implemented Delayed<br />
(i.e. have a method that returns the delay). This type of queue sorts tasks based on<br />
the delay: shorter delay comes first. When taking an element from the queue, it blocks<br />
until the delay of the first task has passed. Using this type of queue makes the<br />
implementation of the ScheduledThreadPoolExecutor quite simple: it wraps the task in a<br />
wrapper that implements getDelay() and puts these wrappers in the queue.</p>
<p>
Although I can appreciate the beauty of using a DelayQueue in combination with a normal<br />
ThreadPoolExecutor, I don&#8217;t think it is the right solution. The point is that it breaks<br />
one of the fundamental principles of OO programming and that is that derived classes<br />
should respect the contract defined by the base class(es) (and or interfaces). The contract<br />
that the base class ThreadPoolExecutor defines, is that it will call the hook methods<br />
with your task as a parameter. ScheduledThreadPoolExecutor breaks this contract, as it<br />
does not adhere to what its base class has promised.</p>
<p>
This break of contract shouldn&#8217;t be taken lightly. It makes code that uses these<br />
executors fragile: if for some reason someone decides to use the other class as<br />
implementation of the general executor service, existing code might break. Put<br />
differently: in order to make your code robust, you would to have to take into account<br />
which executor implementation was chosen, at different points in your code. This<br />
violates principles of encapsulation and abstraction: code should never depend on<br />
implementation types, only on interfaces.</p>
<p>
I was pretty disappointed that even in the concurrency API, such fundamental<br />
mistakes can be found. Moreover, it appeared this is not the only break of contract, and that fixing this properly doesn&#8217;t seem to have any priority, but more on that later.</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.nl/scheduledthreadpoolexecutor-horribly-broken/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
