<?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>Ted Naleid &#187; groovy</title>
	<atom:link href="http://naleid.com/blog/category/groovy/feed/" rel="self" type="application/rss+xml" />
	<link>http://naleid.com/blog</link>
	<description>Groovy, Grails and OS X tips and tricks</description>
	<lastBuildDate>Wed, 16 Jun 2010 17:38:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Groovy Each Iterator with Peek-ahead at Next Collection Value</title>
		<link>http://naleid.com/blog/2010/06/15/groovy-each-iterator-with-peek-ahead-at-next-collection-value/</link>
		<comments>http://naleid.com/blog/2010/06/15/groovy-each-iterator-with-peek-ahead-at-next-collection-value/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 04:55:10 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[shortcut]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=191</guid>
		<description><![CDATA[Groovy closures combined with iterators make it simple to create our own enhanced iterators that let us process a collection how we want to.
I write my own custom iterators all the time and name them something descriptive.  This makes the code much more readable. Rather than trying to decipher what a for loop is [...]]]></description>
			<content:encoded><![CDATA[<p>Groovy closures combined with iterators make it simple to create our own enhanced iterators that let us process a collection how we want to.</p>
<p>I write my own custom iterators all the time and name them something descriptive.  This makes the code much more readable. Rather than trying to decipher what a for loop is trying to do, we wrap up all of that iteration logic into a meaningful name and we cleanly separate that iteration from the processing that we&#8217;re doing with each element.</p>
<p>This kind of design is a core concept in Uncle Bob&#8217;s <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882" onclick="pageTracker._trackPageview('/outgoing/www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882?referer=');">Clean Code</a>, one of my favorite programming books in the last few years.</p>
<p>This example iterates over a collection and calls the passed in closure until we hit a value greater than 5.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> eachUntilGreaterThanFive <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> collection, closure <span style="color: #669966;">-&gt;</span>
    <span style="color: #996600;">for</span> <span style="color: #669966;">&#40;</span> value <span style="color: #996600;">in</span> collection <span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span> value  <span style="color: #669966;">&gt;</span> <span style="color: #cc66cc;">5</span> <span style="color: #669966;">&#41;</span> <span style="color: #000000; font-weight: bold;">break</span>
        closure<span style="color: #669966;">&#40;</span>value<span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> a <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">7</span><span style="color: #669966;">&#93;</span>
&nbsp;
eachUntilGreaterThanFive<span style="color: #669966;">&#40;</span>a<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    <span style="color: #663366;">println</span> it
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>prints:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #cc66cc;">1</span>
<span style="color: #cc66cc;">2</span>
<span style="color: #cc66cc;">3</span>
<span style="color: #cc66cc;">4</span>
<span style="color: #cc66cc;">5</span></pre></div></div>

<p>This code makes it obvious what the iterator is doing (looping till we hit a condition) as well as what will happen with each element iterated over (print it out).</p>
<p>For a real life example, I had a need to iterate over a list of values and where I needed both the current object as well as a peek at the next object in the list.</p>
<p>Doing this is Java is a bit of a pain, but groovy makes it easy to write and (hopefully) to read, we can also add it directly onto the Collection metaClass so that it&#8217;s available for all of our Collection instances:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #aaaadd; font-weight: bold;">Collection</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> closure <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">def</span> last <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">null</span>
    delegate<span style="color: #669966;">?</span>.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span> current <span style="color: #669966;">-&gt;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>last<span style="color: #669966;">&#41;</span> closure<span style="color: #669966;">&#40;</span>last, current<span style="color: #669966;">&#41;</span>
        last <span style="color: #669966;">=</span> current
    <span style="color: #669966;">&#125;</span>
    <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>last<span style="color: #669966;">&#41;</span> closure<span style="color: #669966;">&#40;</span>last, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #669966;">&#41;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>These test cases show that as we iterate through the collection, we can see the current item and peek at the next one (if any).  If the collection is empty, we don&#8217;t execute the closure it, and if we&#8217;re at the end of the list there isn&#8217;t anything to peek at:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">&#123;</span> current, peek <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #000000; font-weight: bold;">false</span> <span style="color: #808080; font-style: italic;">// shouldn't get here, nothing to iterate through</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #669966;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">&#123;</span> current, peek <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> current <span style="color: #669966;">==</span> <span style="color: #cc66cc;">1</span>
    <span style="color: #000000; font-weight: bold;">assert</span> peek <span style="color: #669966;">==</span> <span style="color: #000000; font-weight: bold;">null</span>  <span style="color: #808080; font-style: italic;">// only 1 element, nothing to peek at</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> results <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>
<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span><span style="color: #669966;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">&#123;</span> current, peek <span style="color: #669966;">-&gt;</span>
    results <span style="color: #669966;">&lt;&lt;</span> <span style="color: #669966;">&#91;</span>current, peek<span style="color: #669966;">&#93;</span>
<span style="color: #669966;">&#125;</span>
<span style="color: #000000; font-weight: bold;">assert</span> results <span style="color: #669966;">==</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">5</span>, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#93;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/06/15/groovy-each-iterator-with-peek-ahead-at-next-collection-value/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data plugin version 1.0 released</title>
		<link>http://naleid.com/blog/2010/03/17/grails-build-test-data-plugin-version-1-0-released/</link>
		<comments>http://naleid.com/blog/2010/03/17/grails-build-test-data-plugin-version-1-0-released/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 04:48:53 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=171</guid>
		<description><![CDATA[I&#8217;ve finally released version 1.0 of the grails build-test-data plugin.
If you&#8217;re not familiar with build-test-data, the quick summary is that it puts a build() method on all grails domain objects.  Calling that method will automatically construct and save an instance of that domain object that conforms to all of the domain&#8217;s constraints.  It [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve finally released version 1.0 of the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">grails build-test-data plugin</a>.</p>
<p>If you&#8217;re not familiar with build-test-data, the quick summary is that it puts a <code>build()</code> method on all grails domain objects.  Calling that method will automatically construct and save an instance of that domain object that conforms to all of the domain&#8217;s constraints.  It also allows you to override the values that you want to explicitly set.  It makes your tests much cleaner and less fragile as you only need to specify the values that actually matter to a particular test method instead of building a huge graph of objects just to satisfy constraints.</p>
<p>The plugin has been quite stable for the past 6 months or so, and has survived upgrades from grails 1.0.X through grails 1.2.1 with minimal changes.  Because of this, I&#8217;ve decided to move the version from 0.2.3 to 1.0 to indicate that the plugin is stable and ready to be used.  I&#8217;ve also added the <a href="http://bitbucket.org/tednaleid/grails-test-data/src/tip/build-test-data/LICENSE" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/src/tip/build-test-data/LICENSE?referer=');">LICENSE</a> file releasing the plugin under the Apache 2.0 open source license (the same license as grails).  It was always open source, but I had neglected to add the official license file in the past.</p>
<p>If you&#8217;re not familiar with the build-test-data plugin, the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">documentation on the wiki</a> is thorough, I&#8217;ve also given <a href="http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/">a presentation on build-test-data</a> that explains why it&#8217;s better than other existing data generation technologies. </p>
<p>The biggest changes for this release compared to the last are a number of bugfixes around making sure that both sides of a one-to-many relationship get populated correctly and that there isn&#8217;t a need to <code>refresh()</code> from the database.</p>
<p>Previously, if you had an Author that <code>hasMany</code> Books, and each Book <code>belongsTo</code> an Author, you&#8217;d need to <code>refresh</code> the Author if you tried to build a new book with an existing author:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Author eap <span style="color: #669966;">=</span> Author.<span style="color: #006600;">findByName</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;Edgar Allan Poe&quot;</span><span style="color: #669966;">&#41;</span>
<span style="color: #aaaadd; font-weight: bold;">Book</span> b <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">build</span><span style="color: #669966;">&#40;</span>author: eap, title: <span style="color: #aa0000;">&quot;The Tell-Tale Heart&quot;</span><span style="color: #669966;">&#41;</span>
&nbsp;
assertEquals eap.<span style="color: #006600;">name</span>, b.<span style="color: #006600;">author</span>.<span style="color: #006600;">name</span>  <span style="color: #808080; font-style: italic;">// works, linked in OK previously</span>
assertEquals <span style="color: #cc66cc;">1</span>, eap.<span style="color: #006600;">books</span>.<span style="color: #663399;">size</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// FAILED previously WORKS now, previously the book wasn't added properly to the author side of things</span></pre></div></div>

<p>The previous workaround was to call <code>eap.refresh()</code> to reload the author from the database, or to have the user manually <code>addToBooks(b)</code>.  Both solutions were ugly and kludgy and this issue has now been fixed.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/03/17/grails-build-test-data-plugin-version-1-0-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Interrogating Arbitrary Groovy Closures for Values</title>
		<link>http://naleid.com/blog/2010/01/24/interrogating-arbitrary-groovy-closures-for-values/</link>
		<comments>http://naleid.com/blog/2010/01/24/interrogating-arbitrary-groovy-closures-for-values/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 01:24:25 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=136</guid>
		<description><![CDATA[Inspired by this question on stackoverflow, I decided to create a utility class that allowed me to determine generically what calls a closure makes (without actually letting it make any calls).  This lets me see what it&#8217;s trying to do before letting it actually do it.

It works by overriding the delegate of the closure [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://stackoverflow.com/questions/2128115/access-values-of-static-closure-in-groovy" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/questions/2128115/access-values-of-static-closure-in-groovy?referer=');">this question on stackoverflow</a>, I decided to create a utility class that allowed me to determine generically what calls a closure makes (without actually letting it make any calls).  This lets me see what it&#8217;s trying to do before letting it actually do it.<br />
<span id="more-136"></span><br />
It works by overriding the delegate of the closure (a delegate intercepts all method and property get/set calls that have not already been dealt with).  It assigns it to an instance of the ClosureInterrogator which implements the propertyMissing and methodMissing methods.  Any property or set method that is called gets saved in a map that is returned to the caller.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> ClosureInterrogator <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> closureValueMap <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>:<span style="color: #669966;">&#93;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> extractValuesFromClosure<span style="color: #669966;">&#40;</span>Closure closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> interrogator <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClosureInterrogator<span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">return</span> interrogator.<span style="color: #006600;">closureValueMap</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> ClosureInterrogator<span style="color: #669966;">&#40;</span>Closure closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> oldResolveStrategy <span style="color: #669966;">=</span> closure.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">def</span> oldDelegate <span style="color: #669966;">=</span> closure.<span style="color: #006600;">getDelegate</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        closure.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>
        closure.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_FIRST</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #669966;">&#123;</span>
            closure<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #669966;">&#123;</span>        
            closure.<span style="color: #006600;">setDelegate</span><span style="color: #669966;">&#40;</span>oldDelegate<span style="color: #669966;">&#41;</span>
            closure.<span style="color: #006600;">setResolveStrategy</span><span style="color: #669966;">&#40;</span>oldResolveStrategy<span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">// property getter</span>
    <span style="color: #000000; font-weight: bold;">def</span> propertyMissing<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">// property setter</span>
    <span style="color: #000000; font-weight: bold;">def</span> propertyMissing<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, value<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span> <span style="color: #669966;">=</span> value
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> methodMissing<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, args<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>args.<span style="color: #663399;">size</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span> <span style="color: #669966;">=</span> args<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">&#93;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
            closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span> <span style="color: #669966;">=</span> args
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>This technique is the basis for all groovy mocking techniques and libraries, it&#8217;s also the main technique used to create a <acronym title="Domain Specific Language">DSL</acronym> with groovy.</p>
<p>Here is a sample class that has a closure (&#8220;something&#8221;) that we want to extract the values from.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SomeClass <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">static</span> something <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span>
        key1 <span style="color: #aa0000;">&quot;value1&quot;</span>              <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key1&quot;, [&quot;value1&quot;])</span>
        key2<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;value2&quot;</span><span style="color: #669966;">&#41;</span>             <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key2&quot;, [&quot;value2&quot;])</span>
        key3 <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;value3&quot;</span>            <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key3&quot;, &quot;value3&quot;)</span>
        key4 <span style="color: #aa0000;">&quot;foo&quot;</span>, <span style="color: #aa0000;">&quot;bar&quot;</span>, <span style="color: #aa0000;">&quot;baz&quot;</span>   <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key4&quot;, [&quot;foo&quot;,&quot;bar&quot;,&quot;baz&quot;])</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>If we call &#8220;extractValuesFromClosure&#8221; on the &#8220;something&#8221; closure, we&#8217;ll get back a map that has all of the values we want in it.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> closureValueMap <span style="color: #669966;">=</span> ClosureInterrogator.<span style="color: #006600;">extractValuesFromClosure</span><span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SomeClass<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">something</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value1&quot;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key1&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key1&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value2&quot;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key2&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key2&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value3&quot;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key3&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key3&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;foo&quot;</span>, <span style="color: #aa0000;">&quot;bar&quot;</span>, <span style="color: #aa0000;">&quot;baz&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key4&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key4&quot;)</span></pre></div></div>

<p>This class will work with any type of closure, such as this closure used by the <a href="http://www.grails.org/Mail+plugin" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/Mail+plugin?referer=');">grails mail plugin</a> to send mail.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> mailClosure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span>
   to <span style="color: #aa0000;">&quot;fred@g2one.com&quot;</span>,<span style="color: #aa0000;">&quot;ginger@g2one.com&quot;</span>
   from <span style="color: #aa0000;">&quot;john@g2one.com&quot;</span>
   cc <span style="color: #aa0000;">&quot;marge@g2one.com&quot;</span>, <span style="color: #aa0000;">&quot;ed@g2one.com&quot;</span>
   bcc <span style="color: #aa0000;">&quot;joe@g2one.com&quot;</span>
   subject <span style="color: #aa0000;">&quot;Hello John&quot;</span>
   body <span style="color: #aa0000;">'this is some text'</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> results <span style="color: #669966;">=</span> ClosureInterrogator.<span style="color: #006600;">extractValuesFromClosure</span><span style="color: #669966;">&#40;</span>mailClosure<span style="color: #669966;">&#41;</span>
<span style="color: #663366;">println</span> results
<span style="color: #808080; font-style: italic;">// prints:</span>
<span style="color: #808080; font-style: italic;">// [to:[fred@g2one.com, ginger@g2one.com], from:john@g2one.com, cc:[marge@g2one.com, ed@g2one.com], bcc:joe@g2one.com, subject:Hello John, body:this is some text]</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> results.<span style="color: #006600;">to</span>.<span style="color: #006600;">every</span> <span style="color: #669966;">&#123;</span> it.<span style="color: #006600;">endsWith</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;g2one.com&quot;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#125;</span></pre></div></div>

<p>If we wanted to assert that within a test environment, we&#8217;re only sending e-mail to a specific domain, this would be one technique to assert it before we actually send the e-mail off.</p>
<p>ClosureInterrogator is generic enough that it could also be used on a number of Grails/GORM domain closures such as &#8220;constraints&#8221; and &#8220;mapping&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/01/24/interrogating-arbitrary-groovy-closures-for-values/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Grails Testing Alias to Rerun Failed Tests</title>
		<link>http://naleid.com/blog/2009/11/03/grails-testing-alias-to-rerun-failed-tests/</link>
		<comments>http://naleid.com/blog/2009/11/03/grails-testing-alias-to-rerun-failed-tests/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 03:29:58 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[command line]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[shortcut]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[zshrc]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=99</guid>
		<description><![CDATA[A while ago I blogged about my grails testing aliases and how much time they save me.
I&#8217;ve made some enhancements to them in the interim that have made them even easier to use.  
The most important alias is gtaf, which is short for &#8220;grails test-app&#8221; for failed tests.
It will search through your test output [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I <a href="http://naleid.com/blog/2009/06/14/grails-testing-command-line-aliases/">blogged about my grails testing aliases</a> and how much time they save me.</p>
<p>I&#8217;ve made some enhancements to them in the interim that have made them even easier to use.  </p>
<p>The most important alias is <code>gtaf</code>, which is short for &#8220;grails test-app&#8221; for failed tests.</p>
<p>It will search through your test output directory and look for any tests that failed.  If it finds any, it will rerun only those tests.  Otherwise, it will rerun all tests.  That makes it easy to just use <code>gtaf</code> all the time.  If any tests fail, it will open them up using Console.app.  </p>
<p>If you&#8217;re not on OSX, or would like to use something else to view the failed test logs, just modify the <code>testlog</code> alias to do something different.<br />
<span id="more-99"></span><br />
There are alternative versions of it to only run failed integration tests (<code>gtaif</code> &#8211; Grails Test App Integration Failed), failed unit tests (<code>gtauf</code> &#8211; Grails Test App Unit Failed) or attach a debugger to the tests as they run (<code>gtadf</code> &#8211; Grails Test App Debug Failed).</p>
<p>These aliases, plus most of the rest of my zsh setup, is <a href="http://bitbucket.org/tednaleid/shared-zshrc/src/" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/shared-zshrc/src/?referer=');">available on bitbucket</a>.  If you haven&#8217;t used zsh before and are still using bash, I suggest <a href="http://naleid.com/blog/2009/05/13/shared-zshrc-file/">switching over for the numerous benefits that it gives you</a>.</p>
<p>Here&#8217;s the section of zshrc_general that has the grails testing aliases, just add this to your .zshrc/.bashrc and make sure to uncomment the appropriate GRAILS_TEST_LOG_DIRECTORY export if you&#8217;re not running grails 1.2 yet:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># grails &gt; 1.2</span>
<span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #007800;">GRAILS_TEST_LOG_DIRECTORY</span>=target<span style="color: #000000; font-weight: bold;">/</span>test-reports
&nbsp;
<span style="color: #666666; font-style: italic;"># grails &lt; 1.2</span>
<span style="color: #666666; font-style: italic;"># export GRAILS_TEST_LOG_DIRECTORY=test/reports</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># after grails-test if there were ERROR messages, you can open those logs with the Console.app using this</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">testlog</span>=<span style="color: #ff0000;">'for F in `grep -lE &quot;FAILED|Caused\ an\ ERROR&quot; $GRAILS_TEST_LOG_DIRECTORY/plain/*.txt`; do echo &quot;&gt;&gt;&gt; opening&quot; $F; open -a Console $F; done;'</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># grails-debug-suspend doesn't exist by default, it's a copy of grails-debug with the suspend flag changed to &quot;y&quot; so that</span>
<span style="color: #666666; font-style: italic;"># we can attach a remote debugger before it proceeds past startup</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># aliases where you can optionally pass in a set of tests to run (or no argument to run all tests in that group)</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gta</span>=grailsTestApp
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtad</span>=grailsTestAppDebug
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtau</span>=grailsTestAppUnit
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaud</span>=grailsTestAppUnitDebug
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtai</span>=grailsTestAppIntegration
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaid</span>=grailsTestAppIntegrationDebug
&nbsp;
<span style="color: #666666; font-style: italic;"># aliases that will rerun any failed tests (or all tests if there aren't any failed tests)</span>
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaf</span>=grailsTestAppFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtadf</span>=grailsTestAppDebugFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtauf</span>=grailsTestAppUnitFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaudf</span>=grailsTestAppUnitDebugFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaif</span>=grailsTestAppIntegrationFailed
<span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">gtaidf</span>=grailsTestAppIntegrationDebugFailed
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestApp<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #ff0000;">&quot;&quot;</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails <span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #ff0000;">&quot;&quot;</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppDebugFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails-debug-suspend <span style="color: #ff0000;">&quot;&quot;</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnit<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #660033;">-unit</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails <span style="color: #660033;">-unit</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #660033;">-unit</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppUnitDebugFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails-debug-suspend <span style="color: #660033;">-unit</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegration<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails <span style="color: #660033;">-integration</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails <span style="color: #660033;">-integration</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationDebug<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsTest grails-debug-suspend <span style="color: #660033;">-integration</span> $<span style="color: #000000;">1</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #000000; font-weight: bold;">function</span> grailsTestAppIntegrationDebugFailed<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span> grailsFailedTests grails-debug-suspend <span style="color: #660033;">-integration</span> <span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsFailedTests<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
	<span style="color: #007800;">FAILED_TESTS</span>=<span style="color: #ff0000;">''</span>
	<span style="color: #000000; font-weight: bold;">for</span> F <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-lE</span> <span style="color: #ff0000;">&quot;FAILED|Caused\ an\ ERROR&quot;</span> <span style="color: #007800;">$GRAILS_TEST_LOG_DIRECTORY</span><span style="color: #000000; font-weight: bold;">/</span>plain<span style="color: #000000; font-weight: bold;">/*</span>.txt<span style="color: #000000; font-weight: bold;">`</span>; <span style="color: #000000; font-weight: bold;">do</span>
		<span style="color: #007800;">FAILED_TESTS</span>=<span style="color: #ff0000;">&quot;<span style="color: #007800;">$FAILED_TESTS</span> <span style="color: #780078;">`echo $F | sed -E 's/.*TEST-(.*)Tests.txt/\1/g'`</span>&quot;</span>
	<span style="color: #000000; font-weight: bold;">done</span>;
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;failed tests: <span style="color: #007800;">$FAILED_TESTS</span>&quot;</span>
	grailsTest $<span style="color: #000000;">1</span> $<span style="color: #000000;">2</span> <span style="color: #007800;">$FAILED_TESTS</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> grailsTest<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Running: $1 test-app $2 $3 || testlog &quot;</span>
    <span style="color: #000000; font-weight: bold;">time</span> $<span style="color: #000000;">1</span> test-app $<span style="color: #000000;">2</span> $<span style="color: #000000;">3</span> <span style="color: #000000; font-weight: bold;">||</span> testlog
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<p>I believe that they&#8217;ll also work fine as-is in bash, though I haven&#8217;t tested them.</p>
<p><script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/11/03/grails-testing-alias-to-rerun-failed-tests/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Grails Markdown Plugin 0.1 Released</title>
		<link>http://naleid.com/blog/2009/10/06/grails-markdown-plugin-0-1-released/</link>
		<comments>http://naleid.com/blog/2009/10/06/grails-markdown-plugin-0-1-released/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 05:46:10 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=87</guid>
		<description><![CDATA[I&#8217;ve just released a quick plugin that I put together tonight to help render markdown text as HTML within a grails application.  It leverages the MarkdownJ library.
I&#8217;m a big fan of storing information in markdown format as it is easy to read, easy to write, and easy to transform.  A number of big [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just released a quick plugin that I put together tonight to help render <a href="http://en.wikipedia.org/wiki/Markdown" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Markdown?referer=');">markdown</a> text as HTML within a grails application.  It leverages the <a href="http://markdownj.org/" onclick="pageTracker._trackPageview('/outgoing/markdownj.org/?referer=');">MarkdownJ</a> library.</p>
<p>I&#8217;m a big fan of storing information in markdown format as it is easy to read, easy to write, and easy to transform.  A number of big websites like <a href="http://stackoverflow.com/editing-help" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/editing-help?referer=');">stackoverflow.com</a> support the entry and display of markdown text to help people format their questions and answers without having to remember to properly format HTML.</p>
<p>If you&#8217;re unfamiliar with <a href="http://en.wikipedia.org/wiki/Markdown" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Markdown?referer=');">Markdown</a> there are a number of <a href="http://stackoverflow.com/editing-help" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/editing-help?referer=');">good</a> <a href="http://daringfireball.net/projects/markdown/syntax" onclick="pageTracker._trackPageview('/outgoing/daringfireball.net/projects/markdown/syntax?referer=');">references</a> on it&#8217;s use.</p>
<p>The grails markdown plugin is a very basic plugin.  Currently, it just wraps the markdown libarary with a single TagLib that lets you easily render html from a markdown string within your gsp pages.   </p>
<p>To install it, just type:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">grails install-plugin markdown</pre></div></div>

<p>To use it in your gsp file:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&lt;</span>markdown:renderHtml<span style="color: #669966;">&gt;</span>
The <span style="color: #669966;">*</span>four<span style="color: #669966;">*</span> cardinal directions are
&nbsp;
<span style="color: #669966;">-</span> North
<span style="color: #669966;">-</span> South
<span style="color: #669966;">-</span> East
<span style="color: #669966;">-</span> West
<span style="color: #669966;">&lt;</span>/markdown:renderHtml<span style="color: #669966;">&gt;</span></pre></div></div>

<p>renders the html:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;p&gt;The &lt;em&gt;four&lt;/em&gt; cardinal directions are&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;North&lt;/li&gt;
    &lt;li&gt;South&lt;/li&gt;
    &lt;li&gt;East&lt;/li&gt;
    &lt;li&gt;West&lt;/li&gt;
&lt;/ul&gt;</pre></div></div>

<p>Or you can use the &#8220;text&#8221; attribute of the taglib:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&lt;</span>markdown:renderHtml text<span style="color: #669966;">=</span><span style="color: #aa0000;">&quot;${post.body}&quot;</span>/<span style="color: #669966;">&gt;</span></pre></div></div>

<p>See the <a href="http://bitbucket.org/tednaleid/grails-markdown/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-markdown/wiki/Home?referer=');">Grails Markdown Wiki</a> and source for more details.</p>
<p><script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/10/06/grails-markdown-plugin-0-1-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Batch Import Performance with Grails and MySQL</title>
		<link>http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql/</link>
		<comments>http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 05:53:47 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=66</guid>
		<description><![CDATA[I&#8217;ve spent some time over the last couple of weeks working on a Grails service that allows us to import new records into our MySQL database.
A number of interesting techniques have popped out of this that I think would be useful for others doing similar types of importing using GORM/Hibernate/MySQL.
Background
For background, the imports in our [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent some time over the last couple of weeks working on a Grails service that allows us to import new records into our MySQL database.</p>
<p>A number of interesting techniques have popped out of this that I think would be useful for others doing similar types of importing using GORM/Hibernate/MySQL.<span id="more-66"></span></p>
<h2>Background</h2>
<p>For background, the imports in our app happen a few times a week, and range in size from less than a hundred up to a few hundred thousand new records.</p>
<p>It is also possible for us to get updates on previous data that we&#8217;ve imported, if a record in the import matches a record in our database, we  want to update the existing record rather than inserting a duplicate.</p>
<p>We had a desire to use a Grails service to do the importing as we could leverage our existing data model, plus, there are some special cases where the import logic can get a bit hairy and having access to all of our domain methods is nice.</p>
<p>If you&#8217;re doing much more frequent imports, with heavy performance requirements using millions to hundreds of millions of rows, you&#8217;ll likely want to look at another tool more specifically targeted for batch/ETL processes or writing something directly in Java.  For smaller jobs, you might be surprised how far you can get with groovy and grails.</p>
<h2>Example Naive Import Application</h2>
<p>To demonstrate the techniques, I&#8217;ve created a small test application.  This simple app only has Books.  It imports 100,000 randomly generated books in a single job (importing a Library of Books).  If our database already has a book with that ISBN and edition number, we want to update the title of previous book rather than creating a new book.</p>
<p>Here are the setup files that won&#8217;t change as we tweak our application.</p>
<p>The Domain class:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// domain/Book.groovy</span>
<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #aaaadd; font-weight: bold;">Book</span> <span style="color: #669966;">&#123;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> title
    <span style="color: #aaaadd; font-weight: bold;">String</span> isbn
    <span style="color: #aaaadd; font-weight: bold;">Integer</span> edition
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>The BookController that calls the service:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// controller/BookController.groovy</span>
<span style="color: #000000; font-weight: bold;">class</span> BookController <span style="color: #669966;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> bookService
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> index <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> 
        <span style="color: #000000; font-weight: bold;">def</span> library <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Library<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">def</span> startTime <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">System</span>.<span style="color: #006600;">currentTimeMillis</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>		
        bookService.<span style="color: #006600;">importBooksInLibrary</span><span style="color: #669966;">&#40;</span>library<span style="color: #669966;">&#41;</span>	
        render <span style="color: #aa0000;">&quot;time: ${(startTime - System.currentTimeMillis())/1000} seconds&quot;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>And a Library class that&#8217;s the source of our books (don&#8217;t worry too much about the details of the Library class, just know that it&#8217;s the source of the fields that we&#8217;ll be importing.  For each book, it simply returns a map of the field values that should be saved or updated for the Book):</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Library <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #aaaadd; font-weight: bold;">Iterator</span> <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> startTime <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">System</span>.<span style="color: #006600;">currentTimeMillis</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">def</span> lastBatchStarted <span style="color: #669966;">=</span> startTime
    <span style="color: #000000; font-weight: bold;">def</span> BOOKS_IN_LIBRARY <span style="color: #669966;">=</span> <span style="color: #cc66cc;">100000</span>
    <span style="color: #000000; font-weight: bold;">def</span> currentBook <span style="color: #669966;">=</span> <span style="color: #cc66cc;">1</span>
    <span style="color: #000000; font-weight: bold;">def</span> random <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Random</span><span style="color: #669966;">&#40;</span><span style="color: #cc66cc;">12345</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// random generator with defined seed</span>
&nbsp;
    <span style="color: #aaaadd; font-weight: bold;">Iterator</span> iterator<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">this</span> <span style="color: #000000; font-weight: bold;">as</span> <span style="color: #aaaadd; font-weight: bold;">Iterator</span> <span style="color: #669966;">&#125;</span>
    <span style="color: #993333;">boolean</span> hasNext<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> currentBook <span style="color: #669966;">&lt;=</span> BOOKS_IN_LIBRARY <span style="color: #669966;">&#125;</span>
    <span style="color: #993333;">void</span> remove<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #669966;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">def</span> next<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span><span style="color: #669966;">!</span> <span style="color: #669966;">&#40;</span>currentBook <span style="color: #669966;">%</span> <span style="color: #cc66cc;">100</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#41;</span> printStatus<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #669966;">&#91;</span>
            title: <span style="color: #aa0000;">&quot;Book ${currentBook++}&quot;</span>,
            isbn: randomIsbn<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>, 
            edition: randomEdition<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#93;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> randomIsbn<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #808080; font-style: italic;">// one of 50,000 random isbn numbers</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;isbn-${random.nextInt(50000)}&quot;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> randomEdition<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #808080; font-style: italic;">// first through tenth editions</span>
        <span style="color: #000000; font-weight: bold;">return</span> random.<span style="color: #006600;">nextInt</span><span style="color: #669966;">&#40;</span><span style="color: #cc66cc;">9</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">+</span> <span style="color: #cc66cc;">1</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> printStatus<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> batchEnded <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">System</span>.<span style="color: #006600;">currentTimeMillis</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">def</span> seconds <span style="color: #669966;">=</span> <span style="color: #669966;">&#40;</span>batchEnded<span style="color: #669966;">-</span>lastBatchStarted<span style="color: #669966;">&#41;</span>/<span style="color: #cc66cc;">1000</span>
        <span style="color: #000000; font-weight: bold;">def</span> total <span style="color: #669966;">=</span> <span style="color: #669966;">&#40;</span>batchEnded<span style="color: #669966;">-</span>startTime<span style="color: #669966;">&#41;</span>/<span style="color: #cc66cc;">1000</span>
        <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;Library Book $currentBook, last batch: ${seconds}s, total: ${total}s&quot;</span>
        lastBatchStarted <span style="color: #669966;">=</span> batchEnded
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>The Library class is a proxy for whatever the source of your import info is (a .csv/excel file that you&#8217;re parsing through, a webservice, something posted to your server, etc.).</p>
<p>Also, to help see how we affect timing, every 100 books the Library prints out how long it took to process the last 100 books.</p>
<p>Here is the naive BookService that iterates through the Library that the BookController gives it.  For each book it receives a map of the books values.  It does a <code>findByIsbnAndEdition()</code> to see if the book already exists.  If it does, it updates it, otherwise it will create a new book:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> BookService <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> importBooksInLibrary<span style="color: #669966;">&#40;</span>library<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>		
        library.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> bookValueMap <span style="color: #669966;">-&gt;</span>
            updateOrInsertBook<span style="color: #669966;">&#40;</span>bookValueMap<span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>		
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> updateOrInsertBook<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">Map</span> bookValueMap<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> title <span style="color: #669966;">=</span> bookValueMap.<span style="color: #006600;">title</span>
        <span style="color: #000000; font-weight: bold;">def</span> isbn <span style="color: #669966;">=</span> bookValueMap.<span style="color: #006600;">isbn</span>
        <span style="color: #000000; font-weight: bold;">def</span> edition <span style="color: #669966;">=</span> bookValueMap.<span style="color: #006600;">edition</span>
        <span style="color: #000000; font-weight: bold;">def</span> existingBook <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">findByIsbnAndEdition</span><span style="color: #669966;">&#40;</span>isbn, edition<span style="color: #669966;">&#41;</span>
&nbsp;
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>existingBook<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #808080; font-style: italic;">// just update title</span>
            existingBook.<span style="color: #006600;">title</span> <span style="color: #669966;">=</span> title
            existingBook.<span style="color: #006600;">save</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span> 
            <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Book</span><span style="color: #669966;">&#40;</span>bookValueMap<span style="color: #669966;">&#41;</span>.<span style="color: #006600;">save</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>When you run this code, the first thing you notice is how slow it is.  The first 1000 records aren&#8217;t that bad.  On my old laptop they take about 7 seconds to insert.  After that things get slower and slower, books 10,000 to 11,000 take 20 seconds to insert.  Importing gets progressively worse as time goes on.  </p>
<p><img src="http://naleid.com/blog/wp-content/uploads/2009/09/performance_naive.png" alt="Naive Performance" /></p>
<p>Yikes!  It takes 2 hours and 36 minutes to import 100k records?  Over 3 minutes for the last thousand books to get imported? That can&#8217;t be right.</p>
<p>As it runs, if you open up your activity monitor/task manager/top application, you&#8217;ll also see that Grails is running very hot but also that MySQL&#8217;s CPU usage is slowly going up over time.</p>
<h2>MySQL Database Performance Tweaks</h2>
<h3>Start with the obvious: Database Indexes</h3>
<p>If you&#8217;ve done much database work, you know how much indexes can improve the speed of a query.  But how do you know what queries need indexes?</p>
<p>In some situations, like our example above, it can be fairly obvious.  We&#8217;re calling Book.findByIsbnAndEdition().  Chances are we need an index on the &#8220;book&#8221; table that includes the &#8220;isbn&#8221; and &#8220;edition&#8221; fields:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">INDEX</span> <span style="color: #ff0000;">`idx_book_isbn_edition`</span> <span style="color: #993333; font-weight: bold;">ON</span> <span style="color: #ff0000;">`book`</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`isbn`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`edition`</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h4><small>What if it isn&#8217;t so obvious which queries need an index?</small></h4>
<p>There are a number of techniques available to us through grails to see what kind of SQL is getting executed.</p>
<h4><small>Turn on grails SQL logging</small></h4>
<p>Within grails, you can turn on SQL logging by putting this in your Config.groovy&#8217;s log4j closure:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">trace <span style="color: #aa0000;">'org.hibernate.SQL'</span></pre></div></div>

<h4><small>Install the p6spy plugin and JDBC SQL profiler</small></h4>
<p>The <a href="http://grails.org/plugin/p6spy" onclick="pageTracker._trackPageview('/outgoing/grails.org/plugin/p6spy?referer=');">p6spy grails plugin</a> inserts a proxy between your database driver classes and Grails.  Because of this, it knows the full query, including the filled in query parameters and some timing information.</p>
<p>This is useful by itself, but you can have the p6spy plugin log it&#8217;s messages to a log4j socket appender that talks to the <a href="http://sourceforge.net/projects/sqlprofiler/" onclick="pageTracker._trackPageview('/outgoing/sourceforge.net/projects/sqlprofiler/?referer=');">JDBC SQL Profiler</a> which will aggregate all of the information and help you decide where you&#8217;ve got slow queries and need indexes.</p>
<p>Mike Hugo has a <a href="http://www.piragua.com/2009/06/17/grails-p6spy-and-sql-profiler/" onclick="pageTracker._trackPageview('/outgoing/www.piragua.com/2009/06/17/grails-p6spy-and-sql-profiler/?referer=');">great post on using the p6spy plugin with the JDBC SQL profiler</a>.</p>
<h4><small>Turn on the MySQL Slow Query Log</small></h4>
<p>If you&#8217;re using a recent version of MySQL, there&#8217;s an easy, built-in way to see which queries are slow and which queries aren&#8217;t using indexes: the <a href="http://dev.mysql.com/doc/refman/5.1/en/slow-query-log.html" onclick="pageTracker._trackPageview('/outgoing/dev.mysql.com/doc/refman/5.1/en/slow-query-log.html?referer=');">slow query log</a>.</p>
<p>To turn it on, you simply need to add a few lines to your mysql cnf file (by default on OSX just create a file at /etc/my.cnf and it will get loaded):</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #66cc66;">&#91;</span>mysqld<span style="color: #66cc66;">&#93;</span>
log<span style="color: #66cc66;">-</span>slow<span style="color: #66cc66;">-</span>queries
<span style="color: #808080; font-style: italic;">#Log all queries &gt; long_query_time seconds, default 10 seconds</span>
long_query_time<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">1</span></pre></div></div>

<p>This will automatically create a log file in your mysql &#8220;data&#8221; directory called <i>host_name</i>-slow.log that contains all queries taking longer than 1 second.</p>
<p>You can optionally add</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">log<span style="color: #66cc66;">-</span>queries<span style="color: #66cc66;">-</span>not<span style="color: #66cc66;">-</span>using<span style="color: #66cc66;">-</span>indexes</pre></div></div>

<p>And this will also log those queries that don&#8217;t have an index (but don&#8217;t take longer than 1 second to execute).  </p>
<p>MySQL also comes with a perl script to parse through the slow log file and show you the number of times each query is slow with some additional statistics.  To run it, you need to add basedir to your my.cnf file.  The basedir value just holds the location of mysql&#8217;s data directory.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">basedir<span style="color: #669966;">=</span>/usr/local/mysql</pre></div></div>

<p>Then run the script:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">mysqldumpslow</pre></div></div>

<p>These steps should get you a long way towards figuring out which tables need indexes.</p>
<h4><small>Turn on the MySQL General Query log</small></h4>
<p>MySQL has an additional query log called the <a href="http://dev.mysql.com/doc/refman/5.1/en/query-log.html" onclick="pageTracker._trackPageview('/outgoing/dev.mysql.com/doc/refman/5.1/en/query-log.html?referer=');">general query log</a>.  It logs <i>everything</i> that comes into MySQL and is extremely noisy.  One benefit of it though is that it gives you the full query with all parameters, so it&#8217;s more useful than turning on grails SQL trace log and potentially a little quicker to set up than the p6spy plugin.</p>
<p>You can enable it by putting this in your my.cnf:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">general_log<span style="color: #66cc66;">=</span><span style="color: #cc66cc;">1</span></pre></div></div>

<h4><small>Suggested Reading for MySQL indexes</small></h4>
<p>If you haven&#8217;t created many indexes before, I highly suggest reading <a href="http://www.mysqlperformanceblog.com/2009/09/12/3-ways-mysql-uses-indexes/" onclick="pageTracker._trackPageview('/outgoing/www.mysqlperformanceblog.com/2009/09/12/3-ways-mysql-uses-indexes/?referer=');">this post on indexes on the mysql high performance blog</a>.  The executive summary is that multi-key indexes tailored to your query have a performance edge over individual key indexes on each of the fields.  If you&#8217;re executing a query enough times, it might be worth creating a multi-key index like we have above.</p>
<h3>MySQL Database Engines</h3>
<p>If MySQL is still your performance bottleneck, or if you&#8217;re finding that everything else comes to a stop when you&#8217;re running your batch import, check which storage engine you&#8217;re using.</p>
<p>For grails applications, I&#8217;d prefer InnoDB (or Falcon) to the default MyISAM.  MyISAM is good for read-only situations where you don&#8217;t care about enforced foreign key releationships.  Switching to InnoDB has significantly increased the performance of my app in a number of situations.  InnoDB also supports row level locking, whereas MyISAM will lock the <b>entire table</b> when doing an update or an insert.</p>
<p>If you haven&#8217;t explicitly done anything, chances are that all of your grails-generated tables are MyISAM.  You can change the default storage engine for mysql by specifying a different engine in your my.cnf:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">default<span style="color: #66cc66;">-</span>storage<span style="color: #66cc66;">-</span>engine<span style="color: #66cc66;">=</span>innodb</pre></div></div>

<p>To see the default is for your database execute:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SHOW</span> engines;</pre></div></div>

<p>To see the engine for a particular table, use &#8220;show create table&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">mysql<span style="color: #66cc66;">&gt;</span> <span style="color: #993333; font-weight: bold;">SHOW</span> <span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> book\G
<span style="color: #66cc66;">***************************</span> 1<span style="color: #66cc66;">.</span> row <span style="color: #66cc66;">***************************</span>
       <span style="color: #993333; font-weight: bold;">TABLE</span>: book
<span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span>: <span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #ff0000;">`book`</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #ff0000;">`id`</span> bigint<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`version`</span> bigint<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`edition`</span> int<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">11</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`isbn`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`title`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`id`</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> ENGINE<span style="color: #66cc66;">=</span>MyISAM <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">=</span><span style="color: #cc66cc;">84192</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> CHARSET<span style="color: #66cc66;">=</span>latin1
<span style="color: #cc66cc;">1</span> row <span style="color: #993333; font-weight: bold;">IN</span> <span style="color: #993333; font-weight: bold;">SET</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0.00</span> sec<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>If you need to alter the storage engine for an existing table, you can execute the alter table SQL statement:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">ALTER</span> <span style="color: #993333; font-weight: bold;">TABLE</span> book ENGINE <span style="color: #66cc66;">=</span> INNODB;</pre></div></div>

<h2>Grails Performance Tweaks</h2>
<p>Adding an index and modifying the storage engine of our example book table to InnoDB make our sample app 25-30% faster.  A nice boost from where we were originally, but things are still way too slow:</p>
<p><img src="http://naleid.com/blog/wp-content/uploads/2009/09/performance_with_index.png" alt="Performance with Index" /></p>
<p>Adding indexes to the database drops the database CPU utilization to almost nothing, but grails is still pegged and it still gets much slower over time.  </p>
<p>Something is amiss.</p>
<p>At this point, some people might be inclined to believe the myth that &#8220;grails is slow&#8221; and go through a painful rewrite in another &#8220;faster&#8221; language/technology.  </p>
<p>Don&#8217;t go there yet!  It&#8217;s only slow if you don&#8217;t understand what&#8217;s actually going on under the covers.</p>
<p>After reading through a couple of very <a href="http://burtbeckwith.com/blog/?p=73" onclick="pageTracker._trackPageview('/outgoing/burtbeckwith.com/blog/?p=73&amp;referer=');">helpful</a> <a href="http://burtbeckwith.com/blog/?p=169" onclick="pageTracker._trackPageview('/outgoing/burtbeckwith.com/blog/?p=169&amp;referer=');">posts</a> by Burt Beckwith, and reading through the <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/batch.html" onclick="pageTracker._trackPageview('/outgoing/docs.jboss.org/hibernate/stable/core/reference/en/html/batch.html?referer=');">Hibernate chapter on batch processing</a>, we have all of the information we need to speed things up significantly.</p>
<h4><small>Use a Monitoring Tool to Watch Memory/CPU usage Over Time</small></h4>
<p>Because the import gets significantly slower over time, even with the index applied, we know there is some sort of leak.  </p>
<p>If you don&#8217;t have your code instrumented with timing logic already in it, it&#8217;s easy to pop open <code>jconsole</code> or <code>jvisualvm</code> (both already installed and likely in your classpath if you have Java 1.6), connect to your grails instance and watch performance/cpu utilization over time.</p>
<h4><small>The Culprits: Hibernate First-Level Cache and Grails Validation Cache</small></h4>
<p>I <a href="http://burtbeckwith.com/blog/?p=73" onclick="pageTracker._trackPageview('/outgoing/burtbeckwith.com/blog/?p=73&amp;referer=');">found on Burt Beckwith&#8217;s blog</a>, that there are 2 separate leaks, one of them is in the hibernate first-level cache, the other is a map that Grails uses for domain object validation errors.  </p>
<p>Normally, a grails hibernate session executes something quickly and returns.  During importing, we do a ton of processing, all with the same hibernate session.  All of these objects that would normally be garbage collected when the session closed are piling up.</p>
<p>The easiest way to deal with this is to create a simple method to clear out these collections periodically.</p>
<p>We can modify our BookService to clean up GORM after every 100 books we insert:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> BookService <span style="color: #669966;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> sessionFactory
    <span style="color: #000000; font-weight: bold;">def</span> propertyInstanceMap <span style="color: #669966;">=</span> org.<span style="color: #006600;">codehaus</span>.<span style="color: #006600;">groovy</span>.<span style="color: #006600;">grails</span>.<span style="color: #006600;">plugins</span>.<span style="color: #006600;">DomainClassGrailsPlugin</span>.<span style="color: #006600;">PROPERTY_INSTANCE_MAP</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> importBooksInLibrary<span style="color: #669966;">&#40;</span>library<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        library.<span style="color: #663399;">eachWithIndex</span> <span style="color: #669966;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> bookValueMap, index <span style="color: #669966;">-&gt;</span>
            updateOrInsertBook<span style="color: #669966;">&#40;</span>bookValueMap<span style="color: #669966;">&#41;</span>
            <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>index <span style="color: #669966;">%</span> <span style="color: #cc66cc;">100</span> <span style="color: #669966;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #669966;">&#41;</span> cleanUpGorm<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>    
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> cleanUpGorm<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> session <span style="color: #669966;">=</span> sessionFactory.<span style="color: #006600;">currentSession</span>
        session.<span style="color: #006600;">flush</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        session.<span style="color: #006600;">clear</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        propertyInstanceMap.<span style="color: #663399;">get</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">clear</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> updateOrInsertBook<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">Map</span> bookValueMap<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #808080; font-style: italic;">// ... same as above</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>This change makes everything much better.  All 100,000 books get inserted in 3 minutes, the same time that it took the naive example to insert the last 1,000 books.</p>
<p><img src="http://naleid.com/blog/wp-content/uploads/2009/09/performance_with_index_and_cleanup.png" alt="Performance with Index and Cleanup" /></p>
<p>Also, because MySQL is now properly using indexes, the load on it is very light.  If we&#8217;re looking for even more speed improvement, this would allow us to split our work up into batches and to make multiple BookService calls (potentially on different web servers).  Because we&#8217;ve switched to using InnoDB, we&#8217;re now working with row-level locking, which isn&#8217;t hostile to this approach unlike MyISAM and it&#8217;s full table locking on Insert/Update.</p>
<h2>Conclusion</h2>
<p>This post is just some of what can be done to improve batch performance with Grails and MySQL.  Using these tips, I was able to speed up my own imports to a level that met the speed requirments for our problem space, but kept our code much more maintainable.  Our domain object remain the canonical code representation of our database model.</p>
<p>There are a number of other things that could be looked at to further speed up batch performance and that could be important to your particular application/infrastructure.</p>
<ul>
<li>connectivity between app server and DB</li>
<li>giving enough memory to your app and DB servers</li>
<li>other load into database and app servers</li>
<li>anemic hardware</li>
<li>poor database design</li>
</ul>
<p>Be sure to weigh the cost of making changes in each of these areas, and run benchmark tests before committing to them.  You&#8217;ll often find that what you think is the bottleneck, isn&#8217;t.   Speed is a feature, but you need to balance it with the costs to achieve it.</p>
<p><script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data plugin version 0.2.3 released</title>
		<link>http://naleid.com/blog/2009/08/25/grails-build-test-data-plugin-version-023-released/</link>
		<comments>http://naleid.com/blog/2009/08/25/grails-build-test-data-plugin-version-023-released/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 00:39:31 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[build-test-data]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[release]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=61</guid>
		<description><![CDATA[I&#8217;ve just released the latest version of the grails build-test-data plugin.  This version has a couple of bugfixes that were reported by users.  Including one with a nice patch including a test from Robert Fletcher (patches with tests are always appreciated).
For those that aren&#8217;t familiar with the plugin, it make creating testing data [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just released the latest version of the grails build-test-data plugin.  This version has a couple of bugfixes that were reported by users.  Including one with a nice patch including a test from <a href="http://adhockery.blogspot.com/" onclick="pageTracker._trackPageview('/outgoing/adhockery.blogspot.com/?referer=');">Robert Fletcher</a> (patches with tests are always appreciated).</p>
<p>For those that aren&#8217;t familiar with the plugin, it make creating testing data easy.</p>
<p>It automatically adapts to changes in your domain classes and makes your integration tests easier to write and much less fragile.</p>
<h4>Resources</h4>
<ul>
<li><a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">Documentation on BitBucket</a>
<li>
<li><a href="http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/">Build-Test-Data Presentation</a></li>
</ul>
<p>Overall, the plugin has been very stable for the past few releases and I&#8217;m thinking about just bumping the version up to 1.0 fairly soon.  The plugin seems pretty feature complete when balanced with it&#8217;s ease of use.  Most of the other features I&#8217;ve thought of would explode the complexity level of the plugin and defeat it&#8217;s purpose.  Might be best to leave well enough alone for now :).</p>
<p>I had a hell of a time with the current grails release-plugin cycle (6 attempts before it finally went through).  The grails release-plugin command uses an old version of svnkit that&#8217;s only compatible with svn 1.5.  I&#8217;ve long since upgraded to 1.6 on my mac, though luckily I did it through macports and still had the old version available to activate (sudo port deactivate subversion &#038;&#038; sudo port activate subversion @1.5.6_0).  </p>
<p>I did some searching around to find out how to install an old version of subversion, but didn&#8217;t come up with anything after a quick google so I might be screwed after my wipe/reinstall for snow leopard next week till Grails patches things with svnkit 1.3.</p>
<p>I did open up a <a href="http://jira.codehaus.org/browse/GRAILS-5033" onclick="pageTracker._trackPageview('/outgoing/jira.codehaus.org/browse/GRAILS-5033?referer=');">JIRA ticket for grails to upgrade to svnkit 1.3</a>, and I was surprised that there wasn&#8217;t already a ticket open on it (and that trunk still had svnkit 1.2 in it).</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/08/25/grails-build-test-data-plugin-version-023-released/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Modularizing Groovy Config Files With a Dash of Meta-Programming</title>
		<link>http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/</link>
		<comments>http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 04:56:07 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[config]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=60</guid>
		<description><![CDATA[This is a continuation of a sporadic set of blog posts about some practical uses for groovy metaprogramming.
Groovy Config DSL Overview
In Java, configuration is normally done with properties files.  They&#8217;re kind of a pain because they&#8217;re inflexible, don&#8217;t allow executable code, and don&#8217;t easily provide a heirarchy.
Groovy greatly improves on Java by building in [...]]]></description>
			<content:encoded><![CDATA[<p>This is a continuation of a sporadic <a href="http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/">set</a> <a href="http://naleid.com/blog/2008/05/07/what-methods-does-my-groovygrails-class-have/">of blog</a> <a href="http://naleid.com/blog/2009/06/01/groovy-metaclass-overriding-a-method-whilst-using-the-old-implementation/">posts</a> about some practical uses for groovy metaprogramming.</p>
<h2>Groovy Config DSL Overview</h2>
<p>In Java, configuration is normally done with properties files.  They&#8217;re kind of a pain because they&#8217;re inflexible, don&#8217;t allow executable code, and don&#8217;t easily provide a heirarchy.</p>
<p>Groovy greatly improves on Java by building in support for a simple configuration DSL using the <a href="http://groovy.codehaus.org/ConfigSlurper" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/ConfigSlurper?referer=');">ConfigSlurper</a>.<span id="more-60"></span></p>
<p>To use it, just instantiate a new ConfigSlurper and give it the name of a groovy script file that you&#8217;d like it to parse.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// SampleConfig.groovy, a simple groovy script</span>
person <span style="color: #669966;">&#123;</span>
    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted&quot;</span>
    address <span style="color: #669966;">&#123;</span>
        city <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Minneapolis&quot;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// TestConfiguration.groovy</span>
<span style="color: #000000; font-weight: bold;">def</span> configObject <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigSlurper<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">parse</span><span style="color: #669966;">&#40;</span>SampleConfig<span style="color: #669966;">&#41;</span></pre></div></div>

<p>This creates a ConfigObject, which is a subclass of a Map and can be similarly accessed using dot notation</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #663366;">println</span> configObject
<span style="color: #808080; font-style: italic;">// prints: [person:[firstName:Ted, address:[city:Minneapolis]]]</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;Minneapolis&quot;</span> <span style="color: #669966;">==</span> configObject.<span style="color: #006600;">person</span>.<span style="color: #006600;">address</span>.<span style="color: #006600;">city</span></pre></div></div>

<p>ConfigSlurper is built into groovy and is heavily used for <a href="http://www.grails.org/doc/1.1.x/guide/3.%20Configuration.html" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/doc/1.1.x/guide/3._20Configuration.html?referer=');">Grails configuration</a>.  Grails is a &#8220;convention over configuration&#8221; framework, but anytime you want to modify the conventions, you&#8217;re likely going to be touching a config file.  Grails plugin authors also often use config files to drive plugin behavior.</p>
<p>In larger projects, these config files can start to get quite large and unwieldy.  </p>
<h3>How ConfigSlurper Does It&#8217;s Thing</h3>
<p>DSLs in groovy, like the ConfigSlurper DSL, work by intercepting calls to methods and property setters.  If you look at the internals of the <a href="https://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/main/groovy/util/ConfigSlurper.groovy" onclick="pageTracker._trackPageview('/outgoing/svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/main/groovy/util/ConfigSlurper.groovy?referer=');">ConfigSlurper.parse(Script script, URL location) method</a> (the big one at the bottom), you&#8217;ll see that it heavily messes with the metaClass of the configuration script by creating custom versions of invokeMethod and getProperty.</p>
<p><b>Intercepting Methods</b></p>
<p>When you have a config script that says:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">person <span style="color: #669966;">&#123;</span>
    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;ted&quot;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>What you&#8217;re saying is call the &#8220;person&#8221; method and pass the <code>{ firstName = "ted" }</code> closure to it.  </p>
<p>Normally, this would blow up because you haven&#8217;t defined a &#8220;person&#8221; method.  With the modified metaClass, invokeMethod instead adds &#8220;person&#8221; as a key in the config map and then runs the closure associated with person.  Any subsequent method calls or properties in that closure are assigned as the value in the map to the &#8220;person&#8221; key.</p>
<p><b>Intercepting Property Assignments</b></p>
<p>Property assignment (like <code>firstName = "ted"</code>) works a little differently.  Every script has something associated with it called a <a href="http://groovy.codehaus.org/api/groovy/lang/Binding.html" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/api/groovy/lang/Binding.html?referer=');">binding</a>.  The binding holds script-wide variables that aren&#8217;t explicitly declared.  When parsed by ConfigSlurper, calls that would normally set variables in the script&#8217;s binding are monitored and inserted into the map at the appropriate place in the stack.</p>
<p>So with the modified metaClass and binding the config above turns into this when slurped:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span>person:<span style="color: #669966;">&#91;</span>firstName:ted<span style="color: #669966;">&#93;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>If we had explicitly declared the name property, it wouldn&#8217;t get in the binding, and wouldn&#8217;t be part of the resulting config map.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">person <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;ted&quot;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// result: [person:[:]]</span></pre></div></div>

<h2>Modularizing Config Scripts</h2>
<p>I got to thinking about how nice <a href="http://www.grails.org/doc/1.1.x/ref/Tags/render.html" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/doc/1.1.x/ref/Tags/render.html?referer=');">gsp files are to manage with the ability to include other gsp fragments</a>.  It would be great if we could do the same kind of thing with config files.  That would let us better manage large config files.  It would also let us define external config files that we pull in at run time, or config templates that we want to override just a piece or two out of.  All from inside the config file itself.</p>
<p>Something like:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// SecurityConfig.groovy</span>
security <span style="color: #669966;">&#123;</span>
    includeScript<span style="color: #669966;">&#40;</span> SecurityDefaults <span style="color: #669966;">&#41;</span>
    active <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// SecurityDefaults.groovy</span>
username <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;mysql&quot;</span>
password <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;sekr1t&quot;</span>	    
url <span style="color: #669966;">&#123;</span>
    port <span style="color: #669966;">=</span> <span style="color: #cc66cc;">2112</span>    
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Loading SecurityConfig would have everything in SecurityDefaults and also set active = true:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> configObject <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigSlurper<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">parse</span><span style="color: #669966;">&#40;</span> SecurityConfig <span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #663366;">println</span> configObject
<span style="color: #808080; font-style: italic;">// [security:[username:mysql, password:sekr1t, url:[port:2112], active:true]]</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> configObject.<span style="color: #006600;">security</span>.<span style="color: #006600;">active</span> <span style="color: #669966;">==</span> <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #000000; font-weight: bold;">assert</span> configObject.<span style="color: #006600;">security</span>.<span style="color: #006600;">url</span>.<span style="color: #006600;">port</span> <span style="color: #669966;">==</span> <span style="color: #cc66cc;">2112</span></pre></div></div>

<h3>A Solution</h3>
<p>Getting the same functionality in config files ended up being a bit more difficult a problem to solve than I first expected.  A big part of that was due to some misconceptions I had about how the ConfigSlurper was working as a DSL, as well as what exactly a groovy Script was and how it differed from a regular Groovy class.	</p>
<p>It turns out that when a groovy script is compiled, it&#8217;s contents are placed inside a concrete implementation of the abstract Script.run() method.   So this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// MyGroovyScript.groovy</span>
person <span style="color: #669966;">&#123;</span>
    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted&quot;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Is functionally equivalent to this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> MyGroovyScript <span style="color: #000000; font-weight: bold;">extends</span> Script <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> run<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
	person <span style="color: #669966;">&#123;</span>
     	    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted&quot;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>	    
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>So one way to solve the problem is to create an abstract subclass of script and implement the &#8220;includeScript&#8221; method.  All &#8220;includeScript&#8221; needs to do is override the metaClass and binding of the child script so that it uses <i>the same metaClass and binding as the parent script</i>.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> ComposedConfigScript <span style="color: #000000; font-weight: bold;">extends</span> Script <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> includeScript<span style="color: #669966;">&#40;</span>scriptClass<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> scriptInstance <span style="color: #669966;">=</span> scriptClass.<span style="color: #006600;">newInstance</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        scriptInstance.<span style="color: #006600;">metaClass</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">metaClass</span>
        scriptInstance.<span style="color: #006600;">binding</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigBinding<span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">getBinding</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">callable</span><span style="color: #669966;">&#41;</span>
        scriptInstance.<span style="color: #669966;">&amp;</span>run.<span style="color: #663366; font-weight: bold;">call</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>ConfigSlurper modifies the metaClass and binding before loading the parent class to keep track of things as the script executes, it doesn&#8217;t care who&#8217;s actually calling the methods.</p>
<p>This lets us do exactly what we want, the only limitation to this approach is that the parent script needs to explicitly state that it&#8217;s a class that extends ComposedConfigScript and implements the run() method:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// SecurityConfig.groovy</span>
<span style="color: #000000; font-weight: bold;">class</span> SecurityConfig <span style="color: #000000; font-weight: bold;">extends</span> ComposedConfigScript <span style="color: #669966;">&#123;</span>	        
    <span style="color: #000000; font-weight: bold;">def</span> run<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #808080; font-style: italic;">// normal contents of a config file go in here</span>
&nbsp;
        security <span style="color: #669966;">&#123;</span>
            includeScript<span style="color: #669966;">&#40;</span> SecurityDefaults <span style="color: #669966;">&#41;</span>
            active <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">true</span>
        <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// SecurityDefaults.groovy</span>
username <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;mysql&quot;</span>
password <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;sekr1t&quot;</span>	    
url <span style="color: #669966;">&#123;</span>
    host <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;example.com&quot;</span>
    port <span style="color: #669966;">=</span> <span style="color: #cc66cc;">2112</span>    
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// OtherClass.groovy</span>
<span style="color: #000000; font-weight: bold;">def</span> configObject <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigSlurper<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">parse</span><span style="color: #669966;">&#40;</span> SecurityConfig <span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #663366;">println</span> configObject
<span style="color: #808080; font-style: italic;">// prints: [security:[username:mysql, password:sekr1t, url:[host:example.com, port:2112], active:true]]</span></pre></div></div>

<p>Using this technique lets us modularize our config files.  This helps us both better organize things as well as decouple pieces of information that don&#8217;t necessarily belong together (like log4j info and website url information).  </p>
<p>I had tried a number of other techniques that would let me use includeScript without declaring an explict class (like using a <a href="http://groovy.codehaus.org/Using+the+Delegating+Meta+Class" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+the+Delegating+Meta+Class?referer=');">DelegatingMetaClass</a> for the Script class and <a href="http://groovy.codehaus.org/Static+Import+Usage" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Static+Import+Usage?referer=');">static import</a>) but wasn&#8217;t able to get them working to my satisfaction.  Those solutions are great for most cases, but break down with all the meta-magic that&#8217;s already happening with the ConfigSlurper. </p>
<p>Another option that could be considered, would be to patch the ConfigSlurper implementation to directly allow includeScript functionality.  I&#8217;d be happy to submit a patch that does this if people are interested in this functionality.<br />
<script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data presentation</title>
		<link>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/</link>
		<comments>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 03:28:56 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=59</guid>
		<description><![CDATA[I gave a presentation tonight on the build-test-data grails plugin at the Groovy Users of Minnesota (GUM) meeting that was well received.
Lots of good questions from the people in attendance.  Thanks to everyone for showing up.
Here&#8217;s a version of it on slideshow:
Grails build-test-data Plugin
View more documents from tednaleid.

I also released a new bugfix version [...]]]></description>
			<content:encoded><![CDATA[<p>I gave a presentation tonight on the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">build-test-data</a> grails plugin at the <a href="http://groovy.mn" onclick="pageTracker._trackPageview('/outgoing/groovy.mn?referer=');">Groovy Users of Minnesota (GUM)</a> meeting that was well received.</p>
<p>Lots of good questions from the people in attendance.  Thanks to everyone for showing up.</p>
<p>Here&#8217;s a version of it on slideshow:<span id="more-59"></span></p>
<div style="width:650px;text-align:left" id="__ss_1723277"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/tednaleid/grails-buildtestdata-plugin-1723277" title="Grails build-test-data Plugin" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/tednaleid/grails-buildtestdata-plugin-1723277?referer=');">Grails build-test-data Plugin</a><object style="margin:0px" width="650" height="547"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=build-test-datapresentation-090714222053-phpapp01&#038;stripped_title=grails-buildtestdata-plugin-1723277" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=build-test-datapresentation-090714222053-phpapp01&#038;stripped_title=grails-buildtestdata-plugin-1723277" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="650" height="547"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/?referer=');">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/tednaleid" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/tednaleid?referer=');">tednaleid</a>.</div>
</div>
<p>I also released a new bugfix version of build-test-data earlier today (0.2.2).  Mostly fixed bugs, but there&#8217;s also a new config setting that lets you disable the plugin in specified environments (suggested by Scott Vlaminck @ <a href="http://refactr.com"/>refactr</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Groovy closures make unit testing with &#8220;soft asserts&#8221; simple</title>
		<link>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/</link>
		<comments>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 04:25:45 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[closures]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=58</guid>
		<description><![CDATA[A recent blog post, Cedric Beust asks about how to cleanly implement &#8220;soft asserts&#8221;.  Soft asserts are test assertions that don&#8217;t &#8220;fail fast&#8221;.  Instead, all of the assertion failures in the test method are collected and reported at the end of the test.
So far, the proposals in the comments look fairly clunky to [...]]]></description>
			<content:encoded><![CDATA[<p>A recent blog post, <a href="http://beust.com/weblog/archives/000514.html" onclick="pageTracker._trackPageview('/outgoing/beust.com/weblog/archives/000514.html?referer=');">Cedric Beust asks about how to cleanly implement &#8220;soft asserts&#8221;</a>.  Soft asserts are test assertions that don&#8217;t &#8220;fail fast&#8221;.  Instead, all of the assertion failures in the test method are collected and reported at the end of the test.</p>
<p>So far, the proposals in the comments look fairly clunky to me and include defining whole sets of new methods like &#8220;assertEqualsButContinue(&#8220;foo&#8221;, &#8220;foo&#8221;)&#8221;, chaning assertions together jQuery-style, or using lists to hold all of our assertions.</p>
<p>Wouldn&#8217;t it be a lot nicer if we could continue to use the same methods that we&#8217;re already using?</p>
<p>In groovy, enabling soft assertions is easy with a little closure magic.<span id="more-58"></span></p>
<p>Closures have a property called the &#8220;resolveStrategy&#8221; that determines where the code inside the closure should look to resolve method names.  The default resolve strategy is OWNER_FIRST.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Closure closure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;foo&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #000000; font-weight: bold;">assert</span> closure.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> Closure.<span style="color: #006600;">OWNER_FIRST</span></pre></div></div>

<p>OWNER_FIRST means that if something isn&#8217;t defined inside the closure (local scope), it should check the owner of the closure to see if it can resolve it.  The owner of the closure is the declaring class or another closure that contains our closure.</p>
<p>Closures also have a property called the &#8220;delegate&#8221;.  By default, the delegate is equal to the owner, but we have the ability to change the delegate to something else.  We can also change the resolveStrategy for the closure so when something isn&#8217;t defined, the delegate is the first place that is checked.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Original <span style="color: #669966;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">def</span> closure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#125;</span>   
&nbsp;
   <span style="color: #000000; font-weight: bold;">def</span> value <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> SomethingElse <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> value <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;value from delegate&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> obj <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Original<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// the owner is the enclosing class, and its the same as the delegate by default</span>
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">owner</span>.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #669966;">==</span> Original
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">owner</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">delegate</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// but we can change the closure's delegate to something else if we want</span>
obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SomethingElse<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// by default, the closure looks at the owner before the delegate, value is unchanged</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> 
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> Closure.<span style="color: #006600;">OWNER_FIRST</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// changing the closure's resolve strategy switches who gets to handle value()</span>
obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_FIRST</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from delegate&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Groovy also has a <a href="http://groovy.codehaus.org/Using+invokeMethod+and+getProperty" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+invokeMethod+and+getProperty?referer=');">special metaClass method called invokeMethod</a> that allows you to manipulate any method calls that are invoked on that metaClass.</p>
<p>Using these two things in conjunction, we can write a small class that lets us collect JUnit assertion errors thrown by any method starting with &#8220;assert&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SoftAsserts <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> oldDelegate
    <span style="color: #000000; font-weight: bold;">def</span> failedAssertions <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> softAsserts<span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> SoftAsserts<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">bundleAsserts</span><span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> bundleAsserts <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> closure <span style="color: #669966;">-&gt;</span>
        closure.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_ONLY</span>
        oldDelegate <span style="color: #669966;">=</span> closure.<span style="color: #006600;">delegate</span>
        closure.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>
        closure<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>   
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>failedAssertions<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Exception</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;${failedAssertions.size()} failed assertions found:<span style="color: #000099; font-weight: bold;">\n</span>${failedAssertions.message.join('<span style="color: #000099; font-weight: bold;">\n</span>')}&quot;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> <span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, args<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>name.<span style="color: #006600;">startsWith</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;assert&quot;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #669966;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> oldDelegate.<span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>
            <span style="color: #669966;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #669966;">&#40;</span>junit.<span style="color: #006600;">framework</span>.<span style="color: #006600;">AssertionFailedError</span> e<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
                failedAssertions <span style="color: #669966;">&lt;&lt;</span> e
            <span style="color: #669966;">&#125;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> oldDelegate.<span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>         
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>This test class does a static import of the SoftAsserts.softAsserts closure so it can use it in a natural way.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">grails.test.*</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">static</span> SoftAsserts.<span style="color: #006600;">softAsserts</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> BookTests <span style="color: #000000; font-weight: bold;">extends</span> GroovyTestCase <span style="color: #669966;">&#123;</span>
    <span style="color: #993333;">void</span> testBookTrueAssertsPasses<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>title: <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span><span style="color: #669966;">&#93;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// all 4 assertions pass and we are able to refer to local variables </span>
        <span style="color: #808080; font-style: italic;">// like book and local methods like trueMethod() </span>
        softAsserts <span style="color: #669966;">&#123;</span> 
            assertTrue <span style="color: #000000; font-weight: bold;">true</span>
            assertTrue trueMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
            assertNotNull book
            assertEquals <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span>, book.<span style="color: #006600;">title</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> testBookFalseAssertsCollectsFailures<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>title: <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span><span style="color: #669966;">&#93;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// all 4 assertions throw errors, but all are collected before </span>
        <span style="color: #808080; font-style: italic;">// an exception is actually thrown</span>
        softAsserts <span style="color: #669966;">&#123;</span> 
            assertTrue <span style="color: #aa0000;">&quot;False is not true&quot;</span>, <span style="color: #000000; font-weight: bold;">false</span>
            assertTrue <span style="color: #aa0000;">&quot;falseMethod() is not true&quot;</span>, falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
            assertNull <span style="color: #aa0000;">&quot;Book is not null&quot;</span>, book
            assertEquals <span style="color: #aa0000;">&quot;House of Leaves&quot;</span>, book.<span style="color: #006600;">title</span>
        <span style="color: #669966;">&#125;</span>   
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> trueMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">true</span> <span style="color: #669966;">&#125;</span>   
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">false</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>The first test shows how a passing test can successfully refer to other variables and methods defined inside the test class.  The second test fails, but it doesn&#8217;t fail till all 4 of the assertions are tried and collected.  It then throws an error with the assertion failure count and the individual error messages:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Testcase: testBookFalseAssertsCollectsFailures took <span style="color: #cc66cc;">0.371</span> sec
	Caused an ERROR
<span style="color: #cc66cc;">4</span> failed assertions found:
<span style="color: #000000; font-weight: bold;">False</span> is not <span style="color: #000000; font-weight: bold;">true</span>
falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> is not <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #aaaadd; font-weight: bold;">Book</span> is not <span style="color: #000000; font-weight: bold;">null</span>
expected:<span style="color: #669966;">&lt;</span><span style="color: #669966;">&#91;</span>House of Leaves<span style="color: #669966;">&#93;</span><span style="color: #669966;">&gt;</span> but was:<span style="color: #669966;">&lt;</span><span style="color: #669966;">&#91;</span>Infinite Jest<span style="color: #669966;">&#93;</span><span style="color: #669966;">&gt;</span></pre></div></div>

<p>It might be useful to also print out the individual stack traces for each assertion error, but this is left as an exercise for the reader.</p>
<p>In most situations, I like the fail fast behavior and limiting tests to exercising one feature at a time, but there have been a few test cases where something like this would&#8217;ve been nice.<br />
<script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
