<?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>biotext.org.uk &#187; java</title>
	<atom:link href="http://biotext.org.uk/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://biotext.org.uk</link>
	<description>Not a typewriter</description>
	<lastBuildDate>Wed, 08 Sep 2010 17:47:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Best new feature in Eclipse 3.6 Helios</title>
		<link>http://biotext.org.uk/best-new-feature-in-eclipse-3-6-helios/</link>
		<comments>http://biotext.org.uk/best-new-feature-in-eclipse-3-6-helios/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 13:20:44 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[LJC]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=487</guid>
		<description><![CDATA[&#8230; is hidden away on the last tab of the Java Formatting Profile editor (Preferences -> Java -> Code Style -> Formatter -> Edit). They&#8217;ve finally (after nearly six years) added the ability to temporarily turn the code formatter off for a tricksy block that needs its own custom formatting. e.g.: // @formatter:off xml .append&#40; [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230; is hidden away on the last tab of the Java Formatting Profile editor (Preferences -> Java -> Code Style -> Formatter -> Edit).</p>
<p>They&#8217;ve finally (after <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=76435">nearly six years</a>) added the ability to temporarily turn the code formatter off for a tricksy block that needs its own custom formatting. e.g.:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">			<span style="color: #666666; font-style: italic;">// @formatter:off</span>
			xml
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;&lt;node id='&quot;</span> <span style="color: #009900;">&#41;</span>
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> protein <span style="color: #009900;">&#41;</span>
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;'&gt;&lt;data key='class'&gt;&quot;</span> <span style="color: #009900;">&#41;</span>
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> cls <span style="color: #009900;">&#41;</span>
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;&lt;/data&gt;&lt;data key='label'&gt;&quot;</span> <span style="color: #009900;">&#41;</span>
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> protein <span style="color: #009900;">&#41;</span>
			.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;&lt;/data&gt;&lt;/node&gt;&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #666666; font-style: italic;">// @formatter:on</span></pre></div></div>

<p>See the Off/On Tags tab for details.</p>
<p>Nice one guys&#8230; Eventually.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/best-new-feature-in-eclipse-3-6-helios/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>NoSuchMethodError when running JUnit tests in Eclipse</title>
		<link>http://biotext.org.uk/nosuchmethoderror-when-running-junit-tests-in-eclipse/</link>
		<comments>http://biotext.org.uk/nosuchmethoderror-when-running-junit-tests-in-eclipse/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 12:25:49 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[LJC]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=439</guid>
		<description><![CDATA[This is worth a quick post as I couldn&#8217;t find a solution on Google and it took me an hour or two of fiddling. I have a Maven project, call it frontend-war, which contains the main service code for FuncNet. A unit test kept failing in Eclipse with NoSuchMethodError, one of my least favourite screw-ups [...]]]></description>
			<content:encoded><![CDATA[<p>This is worth a quick post as I couldn&#8217;t find a solution on Google and it took me an hour or two of fiddling.</p>
<p>I have a Maven project, call it <code>frontend-war</code>, which contains the main service code for <a href="http://funcnet.eu/">FuncNet</a>. A unit test kept failing in Eclipse with <code>NoSuchMethodError</code>, one of my least favourite screw-ups to disentangle.</p>
<p>In this case it was particularly frustrating, as the method (on a class in one of the main project&#8217;s dependent jars, called <code>service-utils</code>) definitely existed, was public, and had the right signature. Also, even more weirdly, when I ran the tests in Maven from the command line, they passed.</p>
<p>Cue all the usual Eclipse cargo-cult dead-chicken-waving &#8212; cleaning everything, closing and reopening projects, etc. etc. No joy.</p>
<p>Then it hit me&#8230; (solution below the jump)</p>
<p><span id="more-439"></span><br />
One of the other jars included by <code>frontend-war</code>, called <code>sessionDB</code>, <em>also</em> included <code>service-utils</code> &#8212; and was using an out-of-date version. This version didn&#8217;t include the method I was calling (at least not with that signature). The dependency hierarchy looked something like:</p>
<p><code>frontend-war-CURRENT</code><br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>service-utils-1.2.9</code><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8230;<br />
&nbsp;&nbsp;&nbsp;&nbsp;<code>sessionDB-1.3.3</code><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>service-utils-1.2.4</code><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8230;</p>
<p>So I rebuilt <code>sessionDB</code> against the latest version of <code>service-utils</code>, then rebuilt <code>frontend-war</code> against that, and it worked.</p>
<p>So, my fault for getting myself into <a href="http://en.wikipedia.org/wiki/Java_Classloader#JAR_hell">jar hell</a>, although even if you don&#8217;t bring it on yourself, it&#8217;s hard to avoid it if you use a lot of open-source components, and Maven &#8212; which I still argue is a timesaver overall &#8212; tends to exacerbate it. Take a look at the Dependency Graph view in Eclipse&#8217;s POM Editor sometime &#8212; if you see any red arrows, that means two or more different versions of a dependency are being requested by different modules within your project.</p>
<p>So why did it work on the command line and not in Eclipse? To be honest, I don&#8217;t know in detail. But in cases like this, the classloader will (AFAIK) just pull in whichever version is requested first, so Eclipse&#8217;s classpath management must have happened to process the dependencies in a different order from Maven&#8217;s &#8212; meaning it worked by pure luck.</p>
<p><strong>Note:</strong> My solution &#8212; updating <code>sessionDB</code> to use the latest <code>service-utils</code> &#8212; wasn&#8217;t a problem, because all three of the modules in the unholy <i>ménage à trois</i> belonged to me. But what do you do if two third-party libraries request different versions of the same jar?</p>
<p>A <del datetime="2010-03-17T11:50:48+00:00">famous</del> notorious example of this tends to happen with <a href="https://www.hibernate.org/">Hibernate</a>, which depends on a really out-of-date version of <a href="http://asm.ow2.org/">ASM</a> &#8212; or at least it used to, I haven&#8217;t checked recently. Lots of open-source projects use ASM but more recent versions clash nastily with the old one Hibernate requires.</p>
<p>The <a href="http://blog.springsource.com/2007/06/11/asm-version-incompatibilities-using-spring-autowired-with-hibernate/">solution in this case</a> is to use Maven&#8217;s exclusions clause to specifically exclude ASM from Hibernate&#8217;s transitive dependencies. Thankfully it can just use the more recent versions without problems.</p>
<p>But what would you do if one of the libraries you were using depended on a method that was <em>no longer available</em> in a more recent jar? Then you&#8217;re really in jar hell. Answers on a postcard&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/nosuchmethoderror-when-running-junit-tests-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Help! Eclipse won’t believe I have Maven 2.2.1</title>
		<link>http://biotext.org.uk/help-eclipse-won%e2%80%99t-believe-i-have-maven-2-2-1/</link>
		<comments>http://biotext.org.uk/help-eclipse-won%e2%80%99t-believe-i-have-maven-2-2-1/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 19:25:57 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Questions]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=423</guid>
		<description><![CDATA[I have a project (built from an AppFuse template) that requires Maven 2.2.1. So I upgraded to this (from 2.1.0) and set my path and my M2_HOME and MAVEN_HOME env variables. Then I ran mvn eclipse:eclipse and imported the project into Eclipse (Galileo). However, in the problems list for the project (and at the top [...]]]></description>
			<content:encoded><![CDATA[<p>I have a project (built from an AppFuse template) that requires Maven 2.2.1. So I upgraded to this (from 2.1.0) and set my path and my M2_HOME and MAVEN_HOME env variables.</p>
<p>Then I ran mvn eclipse:eclipse and imported the project into Eclipse (Galileo).</p>
<p>However, in the problems list for the project (and at the top of the pom.xml GUI editor) it says:</p>
<blockquote><p>Unable to build project &#8216;/export/people/clegg/data/GanymedeWorkspace/funcserve/pom.xml; it requires Maven version 2.2.1</p></blockquote>
<p>This persists whether I set Eclipse to use its Embedded Maven implementation, or the external 2.2.1 installation, in the Preferences -> Maven -> Installations dialog.</p>
<p>I&#8217;ve tried closing and reopening the project, reindexing the repository, cleaning the project, restarting the IDE, logging out and back in again, everything I can think of! But Eclipse still won&#8217;t believe I have Maven 2.2.1.</p>
<p>I just did a plugin update so I have the latest version of Maven Integration for Eclipse &#8212; 0.9.8.200905041414.</p>
<p>Does anyone know how to convince Eclipse I really do have the right version of Maven? It&#8217;s like it&#8217;s recorded the previous version somewhere else and won&#8217;t pay any attention to my changes <img src='http://biotext.org.uk/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<p>If you have any clue whatsoever &#8212; <a href="http://stackoverflow.com/questions/1805274/eclipse-wont-believe-i-have-maven-2-2-1">please drop an answer here</a>&#8230;</p>
<p>Thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/help-eclipse-won%e2%80%99t-believe-i-have-maven-2-2-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RetriableTask &#8212; a generic wrapper for retrying operations in Java</title>
		<link>http://biotext.org.uk/retriabletask-a-generic-wrapper-for-retrying-operations-in-java/</link>
		<comments>http://biotext.org.uk/retriabletask-a-generic-wrapper-for-retrying-operations-in-java/#comments</comments>
		<pubDate>Wed, 20 May 2009 16:27:38 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[LJC]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=360</guid>
		<description><![CDATA[A couple of times recently I&#8217;ve needed to write methods that retry up to n times if an error occurs, and surprisingly, couldn&#8217;t find any standard patterns to accomplish this on the web. So I wrote my own. All comments appreciated (there may well be massive holes in my logic but it works so far). [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of times recently I&#8217;ve needed to write methods that retry up to n times if an error occurs, and surprisingly, couldn&#8217;t find any standard patterns to accomplish this on the web. So I wrote my own. All comments appreciated (there may well be massive holes in my logic but it works so far).</p>
<p><span id="more-360"></span></p>
<pre class="brush: java">
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.logging.Logger;

/**
 * This class is a wrapper for a Callable that adds retry functionality.
 * The user supplies an existing Callable, a maximum number of tries,
 * and optionally a Logger to which exceptions will be logged. Calling
 * the call() method of RetriableTask causes the wrapped object&#039;s call()
 * method to be called, and any exceptions thrown from the inner call()
 * will cause the entire inner call() to be repeated from scratch, as
 * long as the maximum number of tries hasn&#039;t been exceeded.
 * InterruptedException and CancellationException are allowed to
 * propogate instead of causing retries, in order to allow cancellation
 * by an executor service etc.
 *
 * @param &lt;T&gt; the return type of the call() method
 */
public class RetriableTask&lt;T&gt; implements Callable&lt;T&gt;
{

    private final Callable&lt;T&gt; _wrappedTask;

    private final int _tries;

    private final Logger _log;

    /**
     * Creates a new RetriableTask around an existing Callable. Supplying
     * zero or a negative number for the tries parameter will allow the
     * task to retry an infinite number of times -- use with caution!
     *
     * @param taskToWrap the Callable to wrap
     * @param tries the max number of tries
     * @param log a Logger to log exceptions to (null == no logging)
     */
    public RetriableTask ( final Callable&lt;T&gt; taskToWrap, final int tries, final Logger log )
    {
        _wrappedTask = taskToWrap;
        _tries = tries;
        _log = log;
    }

    /**
     * Invokes the wrapped Callable&#039;s call method, optionally retrying
     * if an exception occurs. See class documentation for more detail.
     *
     * @return the return value of the wrapped call() method
     */
    public T call() throws Exception
    {
        int triesLeft = _tries;
        while( true )
        {
            try
            {
                return _wrappedTask.call();
            }
            catch( final InterruptedException e )
            {
                // We don&#039;t attempt to retry these
                throw e;
            }
            catch( final CancellationException e )
            {
                // We don&#039;t attempt to retry these either
                throw e;
            }
            catch( final Exception e )
            {
                triesLeft--;

                // Are we allowed to try again?
                if( triesLeft == 0 ) // No -- rethrow
                    throw e;

                // Yes -- log and allow to loop
                if( _log != null )
                    _log.warning( &quot;Caught exception, retrying... Error was: &quot; + e.getMessage() );
            }
        }

    }

}
</pre>
<p><strong>EDIT:</strong> Just to make it clear how I would use this, it works best in the context of an ExecutorService, which manages multi-threading and timeouts for you. So for example, I could create an executor service like so:</p>
<pre class="brush: java">
ExecutorService pool = Executors.newCachedThreadPool();
</pre>
<p>Then create all the tasks I need, and wrap them in RetriableTasks:</p>
<pre class="brush: java">
// Create a task that returns a String
Callable&lt;String&gt; task1 = new Callable&lt;String&gt;()
{
    public String call()
    {
        // Do stuff here
    }
};
// Make it try up to three times
RetriableTask&lt;String&gt; retriable1 =
    new RetriableTask&lt;String&gt;( task1, 3, null );
</pre>
<p>Then add all the RetriableTasks to a Collection, and execute them all on the thread pool:</p>
<pre class="brush: java">
Collection&lt;Callable&lt;String&gt;&gt; tasks =
    new ArrayList&lt;Callable&lt;String&gt;&gt;();
tasks.add( retriable1 );
// TIMEOUT == timeout in seconds
List&lt;Future&lt;String&gt;&gt; results =
    pool.invokeAll( tasks, TIMEOUT, TimeUnit.SECONDS );
</pre>
<p>Finally, iterate through the results list to get all the return values:</p>
<pre class="brush: java">
for( Future&lt;String&gt; result : results )
{
    // Un-retried exceptions will pop out here
    String returnValue = result.get();
}
</pre>
<p>Or use a <a href="http://eng.genius.com/blog/2009/04/29/java-completionservice/">CompletionService</a>.</p>
<p>Obviously there&#8217;s lots of other things you could do within the same framework &#8212; introducing a delay before retrying would be useful in a lot of circumstances, and also you could supply a list of exceptions that would be allowed to propagate. Or only retry on checked exceptions, and automatically bubble unchecked ones. Really it depends on the use case.</p>
<p>Feel free to write an extended version and post it here or link to it <img src='http://biotext.org.uk/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Andrew.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/retriabletask-a-generic-wrapper-for-retrying-operations-in-java/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Execute SQL outside of a transaction in Hibernate</title>
		<link>http://biotext.org.uk/execute-sql-outside-of-a-transaction-in-hibernate/</link>
		<comments>http://biotext.org.uk/execute-sql-outside-of-a-transaction-in-hibernate/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 19:01:27 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[postgresql]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=262</guid>
		<description><![CDATA[I hit upon a snag today &#8212; while PostgreSQL requires that certain maintenance commands (e.g. vacuum analyze) are executed outside of a transactional context, it&#8217;s actually quite hard to get at Hibernate&#8217;s underlying database connection directly. Each Session object has a connection() method which returns a JDBC connection object, but this actually turns out to [...]]]></description>
			<content:encoded><![CDATA[<p>I hit upon a snag today &#8212; while PostgreSQL requires that certain maintenance commands (e.g. <code>vacuum analyze</code>) are executed outside of a transactional context, it&#8217;s actually quite hard to get at Hibernate&#8217;s underlying database connection directly. Each <code>Session</code> object has a <code>connection()</code> method which returns a JDBC connection object, but this actually turns out to be a Hibernate-generated proxy for the real connection object, which refuses to work outside of a transaction.</p>
<p>You can probably get around this by using <a href="http://www.hibernate.org/403.html">autocommit mode</a> instead of explicit transactions, but this is a configuration property that affects your whole application, and is considered harmful.</p>
<p>Eventually I hit on a really dodgy workaround. You can manually rollback the transaction at the start of your SQL statement the old-fashioned way:</p>
<pre class="brush: xml">

&lt;sql-query name=&quot;nasty.hack&quot;&gt;
&lt;![CDATA[
rollback transaction; vacuum analyze;
]]&gt;
&lt;/sql-query&gt;
</pre>
<p>This also works when used with the <code>prepareStatement()</code> method as shown <a href="http://www.hibernate.org/118.html#A26">here</a>.</p>
<p>Frightening but effective. If you know of a better way, let me know!</p>
<p>Andrew.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/execute-sql-outside-of-a-transaction-in-hibernate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>IteratorReader &#8212; streaming character data from an iterator</title>
		<link>http://biotext.org.uk/iteratorreader-streaming-character-data-from-an-iterator/</link>
		<comments>http://biotext.org.uk/iteratorreader-streaming-character-data-from-an-iterator/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 11:10:02 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[LJC]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=146</guid>
		<description><![CDATA[Recently when plugging two components of a high-throughput web service together, I ran into a snag. One component (a data repository) exposes an Iterator for pulling XML-formatted records out of it one by one. The other (for serving SOAP response documents) needed, ideally, something that could be wrapped in a StreamSource &#8212; i.e. an InputStream [...]]]></description>
			<content:encoded><![CDATA[<p>Recently when plugging two components of a <a title="FuncNet" href="http://funcnet.eu/">high-throughput web service</a> together, I ran into a snag. One component (a data repository) exposes an Iterator for pulling XML-formatted records out of it one by one. The other (for serving SOAP response documents) needed, ideally, something that could be wrapped in a StreamSource &#8212; i.e. an InputStream or Reader. But although these are both pull-based ways of providing (in this case) character data, they&#8217;re not compatible.</p>
<p>One easy option is to iterate over the whole Iterator and buffer the results in a String, and then use a StringReader. But that&#8217;s not terribly efficient, when you might well be dealing with XML documents in the 10-20MB range. So I wrote an IteratorReader class, which is a Reader that can be wrapped around any Iterator. Each time it&#8217;s read from, it pulls enough elements from the Iterator to enable the request to be fulfilled, and buffers any remainder. This keeps its memory usage down, although this of course depends on (a) the number of characters requested at once from its read method, and (b) the size of the elements coming off the Iterator. (Each element is simply converted into a String via its toString method before being stored in a character buffer.)</p>
<p>Surprisingly, given the vast amount of Java source out there, I couldn&#8217;t find an existing solution for this &#8212; not even in the usually comprehensive <a title="Apache Commons" href="http://commons.apache.org/">Apache Commons</a>. The code is below, and you are free to do what you like with it, but a credit would be nice if you use it, and if you come up with any improvements I&#8217;d be interested to hear about them. In particular, I&#8217;m sure it could be optimized more, as it spends a lot of time garbage collecting in its current form. It&#8217;s pretty thoroughly tested, with an ArrayList of two million random strings as the source of the Iterator, and seems to work fine both with single-character reads and a BufferedReader wrapped round it. Actually, testing taught me some very interesting lessons, but that&#8217;s another post.</p>
<p><span id="more-146"></span></p>
<p><strong>Implementation note:</strong> As well as providing the Iterator to read from, you can optionally provide an object that implements the Closeable interface. This is because in the scenario I developed this for, the Iterator in question represented a stream of objects that was being generated on-the-fly from a live database connection, and implemented Closeable as well as Iterator so the connection could be closed when necessary. I needed a way of doing this automatically from the Reader&#8217;s point of view, so when the Iterator runs out of data (hasNext returns false) the close method of the attached Closeable, if present, is called.</p>
<p>Download the file: <a href="http://biotext.org.uk/static/IteratorReader.java.v0_1">IteratorReader.java.v0_1</a></p>
<p>All comments very gratefully received.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * IteratorReader v. 0.1
 * Andrew B. Clegg
 */</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.Closeable</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.IOException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.Reader</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Iterator</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> IteratorReader <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">Reader</span>
<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// The iterator from which we'll read</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Iterator<span style="color: #339933;">&lt;?</span> <span style="color: #000000; font-weight: bold;">extends</span> Object<span style="color: #339933;">&gt;</span> _iterator<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Optionally, an object to close when we're done</span>
    <span style="color: #000000; font-weight: bold;">private</span> Closeable _closeable<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Buffer to hold character pulled from iterator before they're read</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> _leftoverCharsFromLastRead <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Flag to indicate when iterator is out of elements</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> _iteratorExhausted <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Creates a new IteratorReader.
     * @param iterator the Iterator to read from
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> IteratorReader<span style="color: #009900;">&#40;</span> Iterator<span style="color: #339933;">&lt;?</span> <span style="color: #000000; font-weight: bold;">extends</span> Object<span style="color: #339933;">&gt;</span> iterator <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        _iterator <span style="color: #339933;">=</span> iterator<span style="color: #339933;">;</span>
        _closeable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Creates a new IteratorReader whose Iterator is backed by a Closeable
     * object that must be cleanly closed when no longer needed.
     * @param iterator the Iterator to read from
     * @param closeable the Closeable object backing the Iterator
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> IteratorReader<span style="color: #009900;">&#40;</span> Iterator<span style="color: #339933;">&lt;?</span> <span style="color: #000000; font-weight: bold;">extends</span> Object<span style="color: #339933;">&gt;</span> iterator, Closeable closeable <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        _iterator <span style="color: #339933;">=</span> iterator<span style="color: #339933;">;</span>
        _closeable <span style="color: #339933;">=</span> closeable<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Closes the Closeable object on which this reader's Iterator depends.
     * If there is no such Closeable, or it has already been closed, this
     * method does nothing. This method is automatically called when Iterator's
     * hasNext method returns false, but can be called earlier.
     * @throws IOException if the Closeable encounters a problem when closing
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> close<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">IOException</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> _closeable <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            _closeable.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            _closeable <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Reads characters into a portion of an array. See Reader.
     * @param outBuf array to copy the characters into
     * @param outBufOffset offset at which to start storing characters
     * @param charsRequested maximum number of characters to read
     * @return the number of characters read, or -1 if the end of the iterator has been reached
     * @throws IOException if the Closeable encounters a problem when closing
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">int</span> read<span style="color: #009900;">&#40;</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> outBuf, <span style="color: #000066; font-weight: bold;">int</span> outBufOffset, <span style="color: #000066; font-weight: bold;">int</span> charsRequested <span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">IOException</span>
    <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">//        System.out.format( &quot;read called: outBufOffset=%d, charsRequested=%d\n&quot;, outBufOffset, charsRequested );</span>
<span style="color: #666666; font-style: italic;">//        System.out.format( &quot;current state: _leftoverCharsFromLastRead has %d characters, _iteratorExhausted=%b\n&quot;,</span>
<span style="color: #666666; font-style: italic;">//                _leftoverCharsFromLastRead.length, _iteratorExhausted );</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// Have we already read enough characters from the iterator to feed this request?</span>
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> charsRequested <span style="color: #339933;">&lt;=</span> _leftoverCharsFromLastRead.<span style="color: #006633;">length</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// Yes, we already have enough characters, copy them into output buffer</span>
            <span style="color: #003399;">System</span>.<span style="color: #006633;">arraycopy</span><span style="color: #009900;">&#40;</span> _leftoverCharsFromLastRead, <span style="color: #cc66cc;">0</span>, outBuf, outBufOffset, charsRequested <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #666666; font-style: italic;">// Are there any left over?</span>
            <span style="color: #000066; font-weight: bold;">int</span> remainder <span style="color: #339933;">=</span> _leftoverCharsFromLastRead.<span style="color: #006633;">length</span> <span style="color: #339933;">-</span> charsRequested<span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">assert</span><span style="color: #009900;">&#40;</span> remainder <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> remainder <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">// Copy remaining characters to new buffer (i.e. shrink buffer)</span>
                <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> tempBuf <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> remainder <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                <span style="color: #003399;">System</span>.<span style="color: #006633;">arraycopy</span><span style="color: #009900;">&#40;</span> _leftoverCharsFromLastRead, charsRequested, tempBuf, <span style="color: #cc66cc;">0</span>, remainder <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                _leftoverCharsFromLastRead <span style="color: #339933;">=</span> tempBuf<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">else</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">// None left over, so reset buffer to zero-length</span>
                _leftoverCharsFromLastRead <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #666666; font-style: italic;">// Return the number of characters read</span>
            <span style="color: #666666; font-style: italic;">// (in this case, all the characters requested)</span>
            <span style="color: #000000; font-weight: bold;">return</span> charsRequested<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">else</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// We have been asked for more characters than we currently have, so we</span>
            <span style="color: #666666; font-style: italic;">// can return what we have (if there are no more in the iterator) or</span>
            <span style="color: #666666; font-style: italic;">// try to acquire more from the iterator</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">// If iterator is exhausted and read has been called again, clean up and</span>
            <span style="color: #666666; font-style: italic;">// return straight away, after copying as many characters as we have left</span>
            <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> _iteratorExhausted <span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #000066; font-weight: bold;">int</span> charsAvailable <span style="color: #339933;">=</span> _leftoverCharsFromLastRead.<span style="color: #006633;">length</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> charsAvailable <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #666666; font-style: italic;">// Nothing in the iterator or the buffer, we're done</span>
                    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">else</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #666666; font-style: italic;">// Copy what we have into output buffer</span>
                    <span style="color: #003399;">System</span>.<span style="color: #006633;">arraycopy</span><span style="color: #009900;">&#40;</span> _leftoverCharsFromLastRead, <span style="color: #cc66cc;">0</span>, outBuf, outBufOffset, charsAvailable <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// Clean up our own buffer and return number of characters copied</span>
                    _leftoverCharsFromLastRead <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                    <span style="color: #000000; font-weight: bold;">return</span> charsAvailable<span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #000000; font-weight: bold;">else</span>
            <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">// There's still data in the iterator, so we can attempt to satisfy the whole request</span>
                <span style="color: #666666; font-style: italic;">// by doing another read -- open a stringbuilder of the desired length</span>
                StringBuilder sb <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span> charsRequested <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #666666; font-style: italic;">// Insert however many characters we do have and reset our buffer to zero-length</span>
                <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> _leftoverCharsFromLastRead.<span style="color: #006633;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> _leftoverCharsFromLastRead <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    _leftoverCharsFromLastRead <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000066; font-weight: bold;">int</span> charsStillRequired <span style="color: #339933;">=</span> charsRequested <span style="color: #339933;">-</span> _leftoverCharsFromLastRead.<span style="color: #006633;">length</span><span style="color: #339933;">;</span>
                <span style="color: #666666; font-style: italic;">// Iteratively add new strings until no more characters are required</span>
                <span style="color: #000000; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span> charsStillRequired <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span>_iteratorExhausted <span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #666666; font-style: italic;">// Read another string from the underlying iterator</span>
                    <span style="color: #003399;">String</span> string <span style="color: #339933;">=</span> nextString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// Add it to stringbuffer</span>
                    sb.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span> string <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// Adjust number still required</span>
                    charsStillRequired <span style="color: #339933;">=</span> charsStillRequired <span style="color: #339933;">-</span> string.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #666666; font-style: italic;">// Did we read to the end of the iterator?</span>
                <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> _iteratorExhausted <span style="color: #009900;">&#41;</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #666666; font-style: italic;">// We have read all the strings from the iterator, but can only return</span>
                    <span style="color: #666666; font-style: italic;">// as many characters as we managed to read, or as many as were requested,</span>
                    <span style="color: #666666; font-style: italic;">// whichever is lower</span>
                    <span style="color: #000066; font-weight: bold;">int</span> charsObtained <span style="color: #339933;">=</span> sb.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> tempBuf <span style="color: #339933;">=</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toCharArray</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// charsToReturn is the number of chars requested, or obtained, whichever is lower</span>
                    <span style="color: #000066; font-weight: bold;">int</span> charsToReturn <span style="color: #339933;">=</span> <span style="color: #003399;">Math</span>.<span style="color: #006633;">min</span><span style="color: #009900;">&#40;</span> charsRequested, charsObtained <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// Copy this many characters into output buffer</span>
                    <span style="color: #003399;">System</span>.<span style="color: #006633;">arraycopy</span><span style="color: #009900;">&#40;</span> tempBuf, <span style="color: #cc66cc;">0</span>, outBuf, outBufOffset, charsToReturn <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// Do we have any left over in our buffer?</span>
                    <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> charsObtained <span style="color: #339933;">&gt;</span> charsRequested <span style="color: #009900;">&#41;</span>
                    <span style="color: #009900;">&#123;</span>
                        <span style="color: #666666; font-style: italic;">// Yes -- more obtained than requested -- save them for next request</span>
                        <span style="color: #000066; font-weight: bold;">int</span> charsToSave <span style="color: #339933;">=</span> charsObtained <span style="color: #339933;">-</span> charsRequested<span style="color: #339933;">;</span>
                        <span style="color: #000000; font-weight: bold;">assert</span><span style="color: #009900;">&#40;</span> charsToSave <span style="color: #339933;">+</span> charsToReturn <span style="color: #339933;">==</span> tempBuf.<span style="color: #006633;">length</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        _leftoverCharsFromLastRead <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> charsToSave <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                        <span style="color: #003399;">System</span>.<span style="color: #006633;">arraycopy</span><span style="color: #009900;">&#40;</span> tempBuf, charsToReturn, _leftoverCharsFromLastRead, <span style="color: #cc66cc;">0</span>, charsToSave <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                    <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> charsObtained <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span>
                    <span style="color: #009900;">&#123;</span>
                        <span style="color: #666666; font-style: italic;">// No characters left in buffer or iterator; return -1 immediately</span>
                        _leftoverCharsFromLastRead <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                    <span style="color: #000000; font-weight: bold;">else</span>
                    <span style="color: #009900;">&#123;</span>
                        <span style="color: #666666; font-style: italic;">// There are some remaining in buffer for next time, so just return</span>
                        <span style="color: #666666; font-style: italic;">// the number we acquired this time</span>
                        <span style="color: #000000; font-weight: bold;">return</span> charsToReturn<span style="color: #339933;">;</span>
                    <span style="color: #009900;">&#125;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">else</span>
                <span style="color: #009900;">&#123;</span>
                    <span style="color: #666666; font-style: italic;">// sb now contains text to return, and there are more strings to iterate through.</span>
                    <span style="color: #666666; font-style: italic;">// We can save a bit of effort by putting the entire contents of sb into</span>
                    <span style="color: #666666; font-style: italic;">// our 'leftover' characters buffer, and calling this method again to copy it over</span>
                    _leftoverCharsFromLastRead <span style="color: #339933;">=</span> sb.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toCharArray</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                    <span style="color: #000000; font-weight: bold;">return</span> read<span style="color: #009900;">&#40;</span> outBuf, outBufOffset, charsRequested <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nextString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">IOException</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// This should never get called after _iteratorExhausted has been set</span>
        <span style="color: #000000; font-weight: bold;">assert</span><span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span>_iteratorExhausted <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span> _iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> _iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">else</span>
        <span style="color: #009900;">&#123;</span>
            _iteratorExhausted <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
            close<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/iteratorreader-streaming-character-data-from-an-iterator/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Java web service frameworks &#8212; a brief survey</title>
		<link>http://biotext.org.uk/java-web-service-frameworks-a-brief-survey/</link>
		<comments>http://biotext.org.uk/java-web-service-frameworks-a-brief-survey/#comments</comments>
		<pubDate>Sat, 27 Dec 2008 16:23:32 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Research]]></category>
		<category><![CDATA[axis2]]></category>
		<category><![CDATA[cxf]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jax-ws]]></category>
		<category><![CDATA[jboss]]></category>
		<category><![CDATA[metro]]></category>
		<category><![CDATA[soaplab]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=64</guid>
		<description><![CDATA[One of the current ongoing R&#38;D projects at CATH is the development of a library of web services for both internal and external use. The first step in this process was the selection of a web service toolkit (or &#8216;stack&#8217;) to use, as there are several competing (and often mutually incompatible) frameworks available. This page [...]]]></description>
			<content:encoded><![CDATA[<p>One of the current ongoing R&amp;D projects at <a title="CATH database" href="http://cathdb.info">CATH</a> is the development of a library of web services for both internal and external use. The first step in this process was the selection of a web service toolkit (or &#8216;stack&#8217;) to use, as there are several competing (and often mutually incompatible) frameworks available. This page compares some of them in brief based on some informal evaluations and background reading.</p>
<p>Note that I am far from being an expert in this field, so feel free to leave a comment if there&#8217;s anything here you disagree with. I am, as ever, happy to be corrected.</p>
<p>Also, please don&#8217;t get the impression that this is a methodical side-by-side comparison. I would have liked to implement the exact same non-trivial service in each stack, and report systematically on my experiences with each, but in reality I just didn&#8217;t have time to do it that rigourously. What I present here is the result of going through one or two <a title="Glen Mazza's WSDL-first tutorial for CXF and Metro" href="http://www.jroller.com/gmazza/date/20080417">tutorials</a> (mostly of the Hello World/echo-a-string/double-a-number kind), reading the docs, hanging out on forums and garnering opinion from blog posts and articles. And the amount of time I spent with each toolkit is admittedly variable.</p>
<p>I hope it will be useful to someone, despite the caveats.</p>
<p>Andrew.</p>
<p><span id="more-64"></span></p>
<h3><a name="background">Background and assumptions</a></h3>
<p>All of these toolkits are primarily for the development of <a href="http://en.wikipedia.org/wiki/SOAP">SOAP</a> web services, although some provide facilities for other paradigms too (e.g. <a href="http://en.wikipedia.org/wiki/REST">REST</a> or <a href="http://en.wikipedia.org/wiki/POX">POX</a>). In addition, they were evaluated from the point of view of top-down (contract-first) design, which is when a <a href="http://en.wikipedia.org/wiki/Web_Services_Description_Language">WSDL</a> file and <a href="http://en.wikipedia.org/wiki/XML_Schema">XML Schema</a> are drawn up first, containing a description of the services available and their input-output formats. This is then used to generate code (more or less automatically) to handle the requests and responses at the client and/or server ends.</p>
<p>The opposite model, bottom-up (code-first), is very popular in the business world, as when the person writing the clients to access your services is in the same organization as you, internal standards and practices can be enforced at the code level and the actual service definitions can be a bit of an afterthought. Indeed it is relatively common for service or client programmers in this context to never even look at the generated WSDLs. However, there are <a href="http://static.springframework.org/spring-ws/sites/1.5/reference/html/why-contract-first.html">good arguments</a> for contract-first design, and all the more so when (a) you have to design services compliant with externally-imposed standards and (b) the clients accessing your services may be written using radically different toolkits, design philosophies or programming languages to your own. Much of the literature on the web relates to bottom-up design, and some of the claims made about different toolkits are only true of bottom-up projects, so <em>caveat lector</em>.</p>
<p>Also, there are two main competing service definition paradigms for web services, rpc/encoded and document/literal. Of these, the former is still only in widespread use in <a href="http://biomoby.open-bio.org/">MOBY</a> and in the Perl world, while the latter has become a de-facto standard elsewhere, particularly in its &#8216;wrapped&#8217; dialect. (The details of the differences are beyond the scope of this introduction but there&#8217;s a good technical article about them <a href="http://www.ibm.com/developerworks/webservices/library/ws-whichwsdl/">here</a>.) Document/literal is now becoming an &#8216;official&#8217; standard too with its adoption by the <a href="http://www.ws-i.org/">Web Services Interoperability</a> consortium. Therefore, all the frameworks below were assessed in the context of producing document/literal wrapped services.</p>
<p>There is a detailed (if slightly out-of-date) five-way interview with the lead developers/architects of Axis2, Metro, JBossWS, CXF and Spring-WS <a href="http://www.infoq.com/articles/os-ws-stacks-background">here</a>. It discusses the design philosophies and architectures of these five frameworks, although it doesn&#8217;t cover subjective aspects like ease-of-use.</p>
<h3><a name="axis2">Axis2</a></h3>
<p>This is an Apache project and largely unrelated to its predecessor Axis. It is a general-purpose implementation of SOAP web services which predates the now-standard JAX-WS model (see below). See: <a href="http://ws.apache.org/axis2/">http://ws.apache.org/axis2/</a></p>
<p>Pros:</p>
<ul>
<li>Broad choice of databinding and deployment models</li>
<li>Good community/developer support</li>
<li>Code generation tools produce skeleton implementation classes as well as just interfaces</li>
<li>REST/POX support requires little extra work</li>
</ul>
<p>Cons:</p>
<ul>
<li>Broad choice of databinding and deployment models (!)</li>
<li>Generated code seems to come in for criticism on the net</li>
<li>JAX-WS/JAXB-style services supported but still a bit crude; tools only produce interfaces, not skeleton classes</li>
<li>Error diagnosis can be awkward, requiring inspection of server logs</li>
</ul>
<h3><a name="metro">JAX-WS RI (Metro)</a></h3>
<p>Sun&#8217;s &#8216;Reference Implementation&#8217; of the <a href="http://en.wikipedia.org/wiki/JAX-WS">JAX-WS</a> standard, bundled alongside the <a href="https://glassfish.dev.java.net/">GlassFish</a> application server as part of the Java Enterprise Edition SDK. See: <a href="https://jax-ws.dev.java.net/">https://jax-ws.dev.java.net/</a></p>
<p>Pros:</p>
<ul>
<li>Sun are pushing it heavily = likely to be widespread adoption and good tool support</li>
<li>JAXB databinding and generated code are elegant and easy to use</li>
<li>Some of our <a href="http://www.enfin.org/">collaborators</a> use it already</li>
</ul>
<p>Cons:</p>
<ul>
<li>The code generation tools require you to do a lot more work for yourself than Axis2&#8242;s, e.g. writing the implementation classes from scratch rather than from auto-generated skeletons</li>
<li>The server/service configuration files are quite fiddly</li>
<li>Together these mean that adding new services or changing the interface of existing ones is a bit of a hassle</li>
<li>Error diagnosis can be awkward, requiring inspection of server logs</li>
</ul>
<h3><a name="jboss">JBossWS</a></h3>
<p>This is an implementation of the JAX-WS standard by <a href="http://www.jboss.com/">RedHat</a> and the <a href="http://www.jboss.org">JBoss community</a>. Seems to work in a very similar way to Metro, similar advantages, same major disadvantage. See: <a href="http://www.jboss.org/jbossws/">http://www.jboss.org/jbossws/</a></p>
<p>I have to admit, I didn&#8217;t actually go much beyond installing this and reading the docs. If anyone has any practical experiences to share, please add some comments below! Thanks.</p>
<h3><a name="cxf">CXF</a></h3>
<p>Formed from the merger of two older projects, Celtix and XFire, and has now been adopted by the Apache Foundation. Yes, this does mean that there are two entirely separate Apache web service platforms. Such is the bountiful joy of open-source.</p>
<p>Pros:</p>
<ul>
<li>Uses JAX-WS/JAXB natively, so compatibility and tool support shouldn&#8217;t be an issue</li>
<li>Generates skeleton implementation classes as well as just interfaces</li>
<li>Automatic generation of JavaScript client code, for testing or AJAX interfaces</li>
<li>More meaningful error messages than Metro or Axis2</li>
<li> Good community/developer support</li>
<li>Adding new services/operations or modifying existing ones is pretty intuitive</li>
<li>Support for REST via <a href="https://jsr311.dev.java.net/">JAX-RS</a> standard, and various other communication methods like <a href="http://java.sun.com/products/jms/">JMS</a></li>
</ul>
<p>Cons:</p>
<ul>
<li>Configuration can seem <em>horribly</em> complex &#8212; there&#8217;s almost too much flexibility</li>
<li>Non-Spring-programmers may be intimated by Spring-based architecture (also see Spring-WS below)</li>
</ul>
<h3><a name="spring">Spring-WS</a></h3>
<p>Spring Web Services is (obviously) the web services component of the Spring Framework, a popular application development framework that also provides useful facilities like configuration, transaction management, object-relational mapping, database abstraction, logging etc. See: <a href="http://www.springframework.org/">http://www.springframework.org/</a></p>
<p>Pros:</p>
<ul>
<li>Integration with rest of Spring could be useful (although CXF also designed to facilitate this)</li>
<li>Very firm (actually exclusive) focus on contract-first design</li>
<li>Tool for constructing WSDL automatically from XSD (<em>really</em> contract-first)</li>
<li>User can tie in support for various databinding technologies</li>
</ul>
<p>Cons:</p>
<ul>
<li>Young compared to the other frameworks</li>
<li>Additional learning curve for non-Spring-programmers</li>
<li>No tools for generating Java classes/interface automatically from XSD/WSDL = more trivial hand-coding</li>
<li>Document/message-centric model at odds with operation-centric (RPC-like) model used by most other frameworks &#8212; you get a blob of XML and can do with it what you want</li>
</ul>
<p>N.B. The last of these disadvantages is actually, if you believe the Spring-WS team, an advantage after all. This is quite a persuasive argument, since you can plug in any of several unmarshalling (i.e. databinding) steps if you like, or just pull bits out of the XML tree with a parser (again there are several available). Your implementation then won&#8217;t be tied to any particular databinding object model, freeing you from the danger of ending up with incorrectly-generated classes or XSD structures that can&#8217;t be well represented in Java. Also in many cases you ought to be able to expect better performance this way, e.g. by using forward-only streaming. But it makes the endpoint classes more verbose and slower to create, which would be an issue if you&#8217;re providing a lot of services.</p>
<p>See the Epilogue below for more on this way of working.</p>
<h3><a name="soaplab">Soaplab2</a></h3>
<p>Largely developed at the <a href="http://www.ebi.ac.uk/">EBI</a>, and replacing the earlier Soaplab, Soaplab2 is a toolkit to enable wrapping of existing software in web service front-ends with the minimum of actual coding. See: <a href="http://soaplab.sourceforge.net/soaplab2/">http://soaplab.sourceforge.net/soaplab2/</a></p>
<p>Pros:</p>
<ul>
<li>Consistent access method across different back-end operation</li>
<li>Server-side asynchronous functionality like status polling, job cancellation etc. is built in</li>
<li>Provides web and command-line clients</li>
<li>Creation of web services wrappers around existing programs is swift and usually doesn&#8217;t require any hand-coding</li>
</ul>
<p>Cons:</p>
<ul>
<li>All Soaplab2 services are designed contract-first, but in <a href="http://soaplab.sourceforge.net/soaplab2/MetadataGuide.html">ACD</a>, not WSDL/XSD</li>
<li>Doesn&#8217;t use XML Schema to describe input and output types (not in any useful sense)</li>
<li>WSDLs contain no details of the actual underlying programs or their data requirements</li>
</ul>
<p>Although it&#8217;s a powerful tool, Soaplab2&#8242;s approach to SOAP/WSDL is extremely unusual and seems, in a sense, to miss the point. The WSDLs and XSDs it produces don&#8217;t even attempt to describe the underlying processes &#8212; it just provides generically-named operations like <code>createJob</code>, <code>run</code>, <code>destroy</code>, <code>getSomeResults</code> etc. where the actual &#8216;service&#8217; required (known as an &#8216;analysis&#8217;) is one of the parameters. Instead of listing these services in the WSDL and providing distinct SOAP endpoints to access them, it provides a list of available analyses via another web service. Elements tend to have non-descriptive names like arg0, arg1 etc. and parameters are generally passed in name-value pairs rather than proper typed data structures.</p>
<p>EDIT (13 Jan 2009): Apparently the Soaplab team have recently started working on &#8216;typed&#8217; WSDLs (i.e. WSDLs how most other people use them) which may render some of these objections obselete. However, I don&#8217;t think they&#8217;ve actually released a new version yet which includes these.</p>
<h3><a name="others">Others?</a></h3>
<p>These are all of the open-source options that I&#8217;m currently aware of. There are some commercial options around, but even some of these use open-source products under the hood (e.g. IBM WebSphere which is apparently Axis2-based).</p>
<p>Drop a comment if you know any different.</p>
<h3><a name="conclusions">Conclusions</a></h3>
<p>It is a shame that Soaplab2 web services have such a unique and quirky architecture, since its overall aim &#8212; enabling easy access to existing bioinformatics resources and tools &#8212; covers 90% of what we need web services for at CATH. However, taking the Soaplab2 option would enforce a certain amount of &#8216;vendor&#8217; lock-in, since only Soaplab2-aware tools would be able to get the best out of the resulting services. For other clients, it would lead to an extra level of abstraction between the service consumer and the service. Rather than simply looking for suitable WSDL-based service descriptions in a registry, one would have to find every Soaplab2-based service and then query each one in order to find out what services it actually offered. The consequences for registry architecture of having some services fully described by their WSDLs and others with definitions hidden in Soaplab2 responses are not clear, but they can&#8217;t be good, and the same goes for consistent test suites and automatic service level monitoring.</p>
<p>It is also unclear how Soaplab2-based services would allow for semantic markup of the sort provided by methods like <a href="http://www.w3.org/TR/sawsdl/">SAWSDL</a>, since the same SOAP operation (e.g. <code>createJob</code>) could take parameters with any one of many different semantic types &#8212; sequence, accession number, structure, <a href="http://www.geneontology.org/">GO term</a>, whatever &#8212; depending on what actual underlying process was being invoked. This would seriously reduce the potential for interoperability, automated service discovery and semantic data mining that could be provided by properly-specified services. One of the Soaplab2 developers claimed in June 2008 on the embrace-tech mailing list that &#8216;typed&#8217; services were on the to-do list and would be ready in a matter of “weeks or months”, but this is apparently still a work-in-progress six months later, and of course we cannot be certain what form these will take when they do appear. EDIT (13 Jan 2009): This is apparently now being worked on, see above.</p>
<p>Looking instead at general-purpose web service stacks, I would consider Spring-WS if we already possessed in-house Spring expertise, since the focus on contract-first development is a good match for our requirements. Furthermore the Spring framework is very popular with Java developers and seems to provide useful solutions to a lot of common [web] application development problems. The lack of class generation tools could be problematic but is probably solvable with Ant tasks or even Perl scripts. However, the exhaustive feature list and broad compatibility of CXF, coupled with its good reputation on blogs and discussion fora, make it the best candidate available. And it offers Spring integration itself, meaning that should we wish to explore the capabilities of Spring later on, we will still have that option.</p>
<h3><a name="epilogue">Epilogue</a></h3>
<p>Having eventually gone for CXF, I quickly discovered that for performance reasons, <a href="http://funcnet.eu/">our first Java web services project</a> would need to use raw XML messages, rather than databinding to JAXB objects. Thankfully, it&#8217;s pretty straightforward to <a href="http://cwiki.apache.org/CXF20DOC/provider-services.html">bypass the unmarshalling steps</a> and just treat a SOAP message as raw XML, exactly like Spring-WS does. This is very useful if you want to produce high-throughput web services that process a large amount of data. Several of the services in the project use Oracle to output XML directly (up to tens of thousands of rows at a time) which can be injected into the body of a SOAP message by CXF, using a &#8216;payload provider&#8217; service. Fast and simple.</p>
<p>I believe Metro also supports provider services, as well as the corresponding &#8216;dispatch&#8217; clients for sending raw chunks of XML, as these are part of the JAX-WS spec &#8212; so this solution could also have been implemented with Metro. Although, having got my head around CXF&#8217;s complexity, I am still highly impressed by its flexibility as well as the quality of feedback from its developers and community. So I would have no qualms about recommending it again.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/java-web-service-frameworks-a-brief-survey/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>What&#8217;s wrong with Hibernate, #4</title>
		<link>http://biotext.org.uk/whats-wrong-with-hibernate-4/</link>
		<comments>http://biotext.org.uk/whats-wrong-with-hibernate-4/#comments</comments>
		<pubDate>Fri, 19 Dec 2008 16:04:23 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Rants]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=25</guid>
		<description><![CDATA[Hibernate is supposed to allow you to write queries and manipulate data in the normal Java idiom. Which is true up to a point, and that point is almost five years in the past, when Java introduced generics. Generics are absolutely standard practice in Java these days, and have been for two (nearly three) versions. [...]]]></description>
			<content:encoded><![CDATA[<p>Hibernate is supposed to allow you to write queries and manipulate data in the normal Java idiom. Which is true up to a point, and that point is almost five years in the past, <a title="Understanding generics" href="http://www.javaworld.com/javaworld/jw-06-2004/jw-0607-tiger2.html">when Java introduced generics</a>.</p>
<p>Generics are <em>absolutely</em> standard practice in Java these days, and have been for two (nearly three) versions. But Hibernate still doesn&#8217;t support them, despite lead developer Gavin King <a title="The Scope of Hibernate Three" href="http://blog.hibernate.org/1524.lace">saying at the time</a>:</p>
<blockquote><p>We will also need to support Java generics, which basically boils down to allowing typesafe collections (which is very trivial).</p></blockquote>
<p>Nearly five years later, this still hasn&#8217;t happened, and you still need to manually cast the results of queries and liberally add <code>@SuppressWarnings("unchecked")</code> to demonstrate that you&#8217;re aware you&#8217;re doing things <em>a bit wrong</em>.</p>
<p>Andrew.</p>
<p>There are <a title="Other Hibernate posts" href="/?tag=hibernate">several other posts</a> in this series. Please read the <a title="Disclaimer" href="/index.php/whats-wrong-with-hibernate-1/">disclaimer</a> before you write an angry reply.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/whats-wrong-with-hibernate-4/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>What’s wrong with Hibernate, #3</title>
		<link>http://biotext.org.uk/whats-wrong-with-hibernate-3/</link>
		<comments>http://biotext.org.uk/whats-wrong-with-hibernate-3/#comments</comments>
		<pubDate>Fri, 19 Dec 2008 11:00:16 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Rants]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=20</guid>
		<description><![CDATA[Unfortunately, open-source projects above a certain size seem to become victims of their own success. Many other excellent OSS products like Guice or CXF have user-centred mailing lists that the developers also read. These developers are generally very willing to help out with problems, and the users &#8212; having been treated kindly when they started [...]]]></description>
			<content:encoded><![CDATA[<p>Unfortunately, open-source projects above a certain size seem to become victims of their own success.</p>
<p>Many other excellent OSS products like <a title="Google Guice" href="http://code.google.com/p/google-guice/">Guice</a> or <a title="Apache CXF" href="http://cxf.apache.org/">CXF</a> have user-centred mailing lists that the developers also read. These developers are generally very willing to help out with problems, and the users &#8212; having been treated kindly when they started out &#8212; are equally keen to help with the areas that they have experience of.</p>
<p>Hibernate has no user mailing list, just a large forum site that&#8217;s easy to ignore. Mailing lists encourage people to respond because queries drop in their inboxes; forums tend to be visited in times of need, and people are probably less likely to drop by for philanthropic reasons.</p>
<p>As an example, I&#8217;ve posted <a title="Hibernate Forums" href="http://forum.hibernate.org/search.php?search_author=andrewclegg&amp;mode=results">three queries (plus one repost and various followups)</a> in the Hibernate forums over the course of a month, politely and with plenty of information. Despite hundreds of views, and the fact that two of them highlight features which don&#8217;t work as described, not a single reply from anyone else has been forthcoming. Not even a one-liner saying &#8220;bad question, RTFM&#8221; or &#8220;working as designed&#8221; or &#8220;known bug&#8221;.</p>
<p>Maybe this is sour grapes, but the amount of community feedback from other OSS projects puts this to shame.</p>
<p>Andrew.</p>
<p>There are <a title="Other Hibernate posts" href="/?tag=hibernate">several other posts</a> in this series. Please read the <a title="Disclaimer" href="/index.php/whats-wrong-with-hibernate-1/">disclaimer</a> before you write an angry reply.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/whats-wrong-with-hibernate-3/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>What&#8217;s wrong with Hibernate, #2</title>
		<link>http://biotext.org.uk/whats-wrong-with-hibernate-2/</link>
		<comments>http://biotext.org.uk/whats-wrong-with-hibernate-2/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 18:25:05 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[Rants]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://biotext.org.uk/?p=5</guid>
		<description><![CDATA[On the Hibernate website (and elsewhere), one of the touted advantages of Hibernate over roll-your-own SQL is: Hibernate Core for Java generates SQL for you, relieves you from manual JDBC result set handling and object conversion, and keeps your application portable to all SQL databases. Well, not exactly. Many functions in HQL (Hibernate Query Language) [...]]]></description>
			<content:encoded><![CDATA[<p>On the <a title="Hibernate Core" href="http://hibernate.org/344.html">Hibernate website</a> (and elsewhere), one of the touted advantages of Hibernate over roll-your-own SQL is:</p>
<blockquote><p>Hibernate Core for Java generates SQL for you, relieves you from manual JDBC result set handling and object conversion, and keeps your application portable to all SQL databases.</p></blockquote>
<p>Well, not exactly. Many functions in HQL (Hibernate Query Language) are simply passed through verbatim to the underlying database engine, without any modification.</p>
<p>This is normally fine, but on my first ever HQL query I tried to use a natural-logarithms function &#8212; which is log() in HSQLDB (my testing server) and ln() in PostgreSQL (my production server). Which means that queries written to target the production environment fail with a charming <code>NullPointerException</code> in the test environment. Half a day&#8217;s debugging, right there.</p>
<p>More worryingly, imagine if I had innocently written the query using log(). All my tests would have passed. Then I would have deployed the application to the production environment, and it would still have worked, but <strong>all the queries would have happily returned the wrong answers</strong> &#8212; because log() in PostgreSQL means base-10 logarithms.</p>
<p>Hibernate not only fails to insulate you from dialect differences like these, it also introduces a false sense of safety by pretending that it does.</p>
<p>Andrew.</p>
<p>There are <a title="Other Hibernate posts" href="/?tag=hibernate">several other posts</a> in this series. Please read the <a title="Disclaimer" href="/index.php/whats-wrong-with-hibernate-1/">disclaimer</a> before you write an angry reply.</p>
]]></content:encoded>
			<wfw:commentRss>http://biotext.org.uk/whats-wrong-with-hibernate-2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
