<?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; metaprogramming</title>
	<atom:link href="http://naleid.com/blog/category/metaprogramming/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 May 2012 00:54:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Better Grails Batch Import Performance with Redis and Jesque</title>
		<link>http://naleid.com/blog/2011/10/13/better-grails-batch-import-performance-with-redis-and-jesque/</link>
		<comments>http://naleid.com/blog/2011/10/13/better-grails-batch-import-performance-with-redis-and-jesque/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 04:25:25 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[jesque]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[redis]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=451</guid>
		<description><![CDATA[A couple of years ago, I put up a well-received blog post on tuning Batch Import Performance with Grails an MySQL. I&#8217;ve recently needed to revisit some batch importing procedures and have acquired a few extra tools in my Grails utility belt since writing that post: Grails Redis and Grails Jesque. Redis is a very [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of years ago, I put up a well-received blog post on tuning <a href="http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql/">Batch Import Performance with Grails an MySQL</a>.</p>
<p>I&#8217;ve recently needed to revisit some batch importing procedures and have acquired a few extra tools in my Grails utility belt since writing that post: <a href="http://grails.org/plugin/redis" onclick="pageTracker._trackPageview('/outgoing/grails.org/plugin/redis?referer=');">Grails Redis</a> and <a href="http://grails.org/plugin/jesque" onclick="pageTracker._trackPageview('/outgoing/grails.org/plugin/jesque?referer=');">Grails Jesque</a>.</p>
<p><a href="http://redis.io" onclick="pageTracker._trackPageview('/outgoing/redis.io?referer=');">Redis</a> is a very fast key/value store, where the values are not just strings, but are data structures like lists, sets, and hash maps.  I&#8217;m the main author of the grails redis plugin, and it&#8217;s my favorite pragmatic technology of the past few years.  If you&#8217;re new to Redis, check out the <a href="http://naleid.com/blog/2011/06/27/redis-groovy-and-grails-presentation-at-gr8conf-2011-and-gum/">presentation slides I gave at this year&#8217;s gr8conf</a>.</p>
<p><a href="https://github.com/gresrun/jesque" onclick="pageTracker._trackPageview('/outgoing/github.com/gresrun/jesque?referer=');">Jesque</a> is a Java implementation of <a href="https://github.com/defunkt/resque" onclick="pageTracker._trackPageview('/outgoing/github.com/defunkt/resque?referer=');">Resque</a>.  A Redis-backed message queueing system for creating background jobs.  The Jesque plugin is fully integrated with Grails and allows you to create worker jobs that are spring injected and have an active hibernate session.  Resque was written in Ruby by the folks at GitHub.</p>
<p>This combination makes parallelizing work very easy, as most of the pain of trying to spin off threads in grails is handled for you by Jesque.  Yes, there&#8217;s GPars, but the threads that it creates aren&#8217;t spring injected and don&#8217;t have hibernate sessions.</p>
<p>Using Jesque is as simple as:</p>
<ol>
<li>create a <a href="https://bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/jobs/com/naleid/example/BookConsumerJob.groovy" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/jobs/com/naleid/example/BookConsumerJob.groovy?referer=');"><code>Job</code></a> class that implements a <code>perform</code> method.</li>
<li>tell Jesque to start up 1..n worker threads that monitor a queue and use your <code>Job</code> to process work</li>
<li><code>enqueue</code> work on the queue so workers can pick it up</li>
</ol>
<p>I&#8217;ve created a <a href="https://bitbucket.org/tednaleid/example-jesque-batch/src" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src?referer=');">bitbucket repository with all of the source code</a> from the original Batch Import post, as well as with the enhancements below.</p>
<p>The example problem is that there is a <a href="https://bitbucket.org/tednaleid/example-jesque-batch/src/tip/src/groovy/com/naleid/example/Library.groovy" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src/tip/src/groovy/com/naleid/example/Library.groovy?referer=');">Library</a> class that produces metadata for 100,000 books that we want to persist in the database as <a href="https://bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/domain/com/naleid/example/Book.groovy" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/domain/com/naleid/example/Book.groovy?referer=');">Book</a> domain objects.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #a1a100;">com.naleid.example</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #aaaadd; font-weight: bold;">Book</span> <span style="color: #66cc66;">&#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
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> constraints <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> mapping <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span>
        isbn column:<span style="color: #ff0000;">'isbn'</span>, index:<span style="color: #ff0000;">'book_isbn_idx'</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>The naive way of doing this takes Grails ~3 hours to do the inserts.  The <a href="http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql/">original batch performance post</a> showed how to improve this time from 3 hours to 3 minutes with a few Grails and MySQL tweaks.  </p>
<p>Using Redis + Jesque to parallelize the task, I&#8217;m able to cut that time in half again to a little over 90 seconds on my MacBook Air.</p>
<p>On real-world imports, where there is quite a bit more data and potentially other linked domain objects that can be memoized with the redis-plugin, I&#8217;ve seen a >100x speed improvement over the original serial import, even with the tuning tips from my original post.</p>
<p>Install <a href="http://redis.io/download" onclick="pageTracker._trackPageview('/outgoing/redis.io/download?referer=');">redis</a> and <a href="https://bitbucket.org/tednaleid/example-jesque-batch/overview" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/overview?referer=');">clone the test project from bitbucket</a> to try it yourself.  Just <code>grails-run app</code>, go to <a href="http://localhost:8080/example-jesque-batch/" onclick="pageTracker._trackPageview('/outgoing/localhost_8080/example-jesque-batch/?referer=');">the running app on localhost</a> and click on the link to the <a href="http://localhost:8080/example-jesque-batch/serialBook/index" onclick="pageTracker._trackPageview('/outgoing/localhost_8080/example-jesque-batch/serialBook/index?referer=');">SerialBookController</a> to see the original version, or the <a href="http://localhost:8080/example-jesque-batch/parallelBook/index" onclick="pageTracker._trackPageview('/outgoing/localhost_8080/example-jesque-batch/parallelBook/index?referer=');">ParallelBookController</a> to see the faster Redis+Jesque version.  Each will display the length of time they took to do the insert after they&#8217;re done.</p>
<p>The ParallelBookController calls <code><a href="https://bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/services/com/naleid/example/BookService.groovy" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/services/com/naleid/example/BookService.groovy?referer=');">bookService</a>.parallelImportBooksInLibrary()</code>.  That method spins up a number of worker threads, iterates through the books in the <code>Library</code> and enqueues each one on a Jesque queue.  When it&#8217;s done iterating through the <code>Library</code>, it tells all the threads to end when they&#8217;re done processing all the work:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">    <span style="color: #000000; font-weight: bold;">def</span> parallelImportBooksInLibrary<span style="color: #66cc66;">&#40;</span>library<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #aaaadd; font-weight: bold;">Integer</span> workerCount <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">10</span>
        <span style="color: #aaaadd; font-weight: bold;">String</span> queueName <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;import:book&quot;</span>
        withWorkers<span style="color: #66cc66;">&#40;</span>queueName, BookConsumerJob, workerCount<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            library.<span style="color: #663399;">each</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> bookValueMap <span style="color: #66cc66;">-&gt;</span>
                <span style="color: #aaaadd; font-weight: bold;">String</span> bookValueMapJson <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#40;</span>bookValueMap <span style="color: #000000; font-weight: bold;">as</span> JSON<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toString</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
                jesqueService.<span style="color: #006600;">enqueue</span><span style="color: #66cc66;">&#40;</span>queueName, BookConsumerJob.<span style="color: #006600;">simpleName</span>, bookValueMapJson<span style="color: #66cc66;">&#41;</span>
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> withWorkers<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> queueName, <span style="color: #000000; font-weight: bold;">Class</span> jobClass, <span style="color: #aaaadd; font-weight: bold;">Integer</span> workerCount <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">5</span>, Closure closure<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> workers <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
        <span style="color: #000000; font-weight: bold;">def</span> fullQueueName <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;resque:queue:$queueName&quot;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
            workers <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>..<span style="color: #006600;">workerCount</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #663399;">collect</span> <span style="color: #66cc66;">&#123;</span> jesqueService.<span style="color: #006600;">startWorker</span><span style="color: #66cc66;">&#40;</span>queueName, jobClass.<span style="color: #006600;">simpleName</span>, jobClass<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span>
            closure<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
            <span style="color: #808080; font-style: italic;">// wait for all the work we've generated to be pulled off the queue</span>
            <span style="color: #b1b100;">while</span> <span style="color: #66cc66;">&#40;</span>redisService.<span style="color: #006600;">exists</span><span style="color: #66cc66;">&#40;</span>fullQueueName<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> sleep<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">500</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #808080; font-style: italic;">// all work is off the queue, tell each worker to kill themselves when they're finished</span>
            workers<span style="color: #66cc66;">*</span>.<span style="color: #006600;">end</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>The work queue that persist the <code>Book</code> domain objects in the database are very simple Jesque Job artefacts that are spring injected and have an active hibernate session.  They can be of any class type.  The only requirement is that they have a method named <code>perform</code> that is called and passed an item of work from the queue.</p>
<p>Here&#8217;s the example <a href="https://bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/jobs/com/naleid/example/BookConsumerJob.groovy" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/jobs/com/naleid/example/BookConsumerJob.groovy?referer=');"><code>BookConsumerJob</code></a> class that persists a <code>Book</code> to the database:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #a1a100;">com.naleid.example</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #a1a100;">grails.converters.JSON</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> BookConsumerJob <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> bookService
&nbsp;
    <span style="color: #993333;">void</span> perform<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> bookJson<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        bookService.<span style="color: #006600;">updateOrInsertBook</span><span style="color: #66cc66;">&#40;</span>JSON.<span style="color: #006600;">parse</span><span style="color: #66cc66;">&#40;</span>bookJson<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>You can see how simple the <code>BookConsumerJob</code> class is.  It also calls out to the same <a href="https://bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/services/com/naleid/example/BookService.groovy" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/example-jesque-batch/src/tip/grails-app/services/com/naleid/example/BookService.groovy?referer=');">bookService</a> method that the serial batch import calls to import a <code>Book</code>.</p>
<p>One other neat thing about using Jesque is that it adheres to the Resque conventions for what gets stored in Redis.  This means that you can <code>gem install resque-web</code> and then launch <code>resque-web</code> to get a nice monitoring platform for your Jobs and to see errors, or how much work is left in the queue.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2011/10/13/better-grails-batch-import-performance-with-redis-and-jesque/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dynamically setting Grails Log4J levels with the Console Plugin</title>
		<link>http://naleid.com/blog/2011/09/23/dynamically-setting-grails-log4j-levels-with-the-console-plugin/</link>
		<comments>http://naleid.com/blog/2011/09/23/dynamically-setting-grails-log4j-levels-with-the-console-plugin/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 18:41:59 +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=414</guid>
		<description><![CDATA[If you&#8217;ve got Burt Beckwith&#8217;s great Grails Console Plugin installed, it&#8217;s easy to tweak the logging levels dynamically in your grails application. The quick and dirty way to switch your logging level dynamically, if you know the name of the logger is just to do this in your console window: import org.apache.log4j.* Logger.getLogger&#40;&#34;org.springframework&#34;&#41;.level = Level.DEBUG [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve got Burt Beckwith&#8217;s great <a href="http://grails.org/plugin/console" onclick="pageTracker._trackPageview('/outgoing/grails.org/plugin/console?referer=');">Grails Console Plugin</a> installed, it&#8217;s easy to tweak the logging levels dynamically in your grails application.</p>
<p>The quick and dirty way to switch your logging level dynamically, if you know the name of the logger is just to do this in your console window:</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: #a1a100;">org.apache.log4j.*</span>
Logger.<span style="color: #006600;">getLogger</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;org.springframework&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">level</span> <span style="color: #66cc66;">=</span> Level.<span style="color: #006600;">DEBUG</span></pre></div></div>

<p>Sometimes, a few helper methods can help you see what the current config is (especially if you&#8217;ve changed some things), as well as figure out what the right loggers are to tweak.  This sample script can be used in a grails console to make it easy to view and change the logging level to whatever you want, just cut and paste it into your application&#8217;s console window (in dev it defaults to: http://localhost:8080/yourAppName/console):</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: #a1a100;">org.apache.log4j.Logger</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #a1a100;">org.apache.log4j.Level</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #a1a100;">static</span> org.<span style="color: #006600;">apache</span>.<span style="color: #006600;">log4j</span>.<span style="color: #006600;">Level</span>.<span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> getRootLogger<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> Logger.<span style="color: #006600;">rootLogger</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">def</span> getAllLoggers<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> rootLogger.<span style="color: #006600;">loggerRepository</span>.<span style="color: #006600;">currentLoggers</span>.<span style="color: #663399;">toList</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #663399;">sort</span> <span style="color: #66cc66;">&#123;</span> it.<span style="color: #006600;">name</span> <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">def</span> getActiveLoggers<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> allLoggers.<span style="color: #663399;">findAll</span> <span style="color: #66cc66;">&#123;</span> it.<span style="color: #006600;">level</span> <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">def</span> getLogger<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> logName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> rootLogger.<span style="color: #006600;">getLogger</span><span style="color: #66cc66;">&#40;</span>logName<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">def</span> setLevel<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> logName, Level level<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> rootLogger.<span style="color: #006600;">getLogger</span><span style="color: #66cc66;">&#40;</span>logName<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">level</span> <span style="color: #66cc66;">=</span> level <span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> printLogger<span style="color: #66cc66;">&#40;</span>logger<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #993399;">println</span> <span style="color: #ff0000;">&quot;${logger.name} -&gt; ${logger.level}&quot;</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">def</span> printAllLoggers<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> allLoggers.<span style="color: #663399;">each</span> <span style="color: #66cc66;">&#123;</span> printLogger<span style="color: #66cc66;">&#40;</span>it<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">def</span> printActiveLoggers<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> activeLoggers.<span style="color: #663399;">each</span> <span style="color: #66cc66;">&#123;</span> printLogger<span style="color: #66cc66;">&#40;</span>it<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>This makes it easy to see what logs are currently active (those with a log level set):</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">printActiveLoggers<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>prints something like:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">filters</span>.<span style="color: #006600;">LoggingFilters</span> <span style="color: #66cc66;">-&gt;</span> DEBUG
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">filters</span>.<span style="color: #006600;">SecurityFilters</span> <span style="color: #66cc66;">-&gt;</span> DEBUG
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">service</span>.<span style="color: #006600;">grails</span>.<span style="color: #006600;">plugin</span>.<span style="color: #006600;">redis</span>.<span style="color: #006600;">RedisService</span> <span style="color: #66cc66;">-&gt;</span> WARN
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">task</span> <span style="color: #66cc66;">-&gt;</span> DEBUG
org.<span style="color: #006600;">apache</span>.<span style="color: #006600;">cxf</span> <span style="color: #66cc66;">-&gt;</span> DEBUG
...</pre></div></div>

<p>You can also list all loggers, which also adds in those loggers who&#8217;s log level is currently `null`:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">printAllLoggers<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>prints:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">grails.<span style="color: #006600;">app</span> <span style="color: #66cc66;">-&gt;</span> DEBUG
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">bootstrap</span>.<span style="color: #006600;">BootStrap</span> <span style="color: #66cc66;">-&gt;</span> <span style="color: #000000; font-weight: bold;">null</span>
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">bootstrap</span>.<span style="color: #006600;">QuartzBootStrap</span> <span style="color: #66cc66;">-&gt;</span> <span style="color: #000000; font-weight: bold;">null</span>
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">codec</span>.<span style="color: #006600;">org</span>.<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;">codecs</span>.<span style="color: #006600;">Base64Codec</span> <span style="color: #66cc66;">-&gt;</span> <span style="color: #000000; font-weight: bold;">null</span>
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">codec</span>.<span style="color: #006600;">org</span>.<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;">codecs</span>.<span style="color: #006600;">HTMLCodec</span> <span style="color: #66cc66;">-&gt;</span> <span style="color: #000000; font-weight: bold;">null</span>
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">codec</span>.<span style="color: #006600;">org</span>.<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;">codecs</span>.<span style="color: #006600;">HexCodec</span> <span style="color: #66cc66;">-&gt;</span> <span style="color: #000000; font-weight: bold;">null</span>
...</pre></div></div>

<p>You can also dynamically grab/create a logger and set it&#8217;s logging level to something more or less verbose than it&#8217;s current value:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> logger <span style="color: #66cc66;">=</span> getLogger<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;grails.app.service.grails.plugin.redis.RedisService&quot;</span><span style="color: #66cc66;">&#41;</span>
printLogger<span style="color: #66cc66;">&#40;</span>logger<span style="color: #66cc66;">&#41;</span>   <span style="color: #808080; font-style: italic;">// initially WARN</span>
logger.<span style="color: #006600;">level</span> <span style="color: #66cc66;">=</span> INFO  
printLogger<span style="color: #66cc66;">&#40;</span>logger<span style="color: #66cc66;">&#41;</span>   <span style="color: #808080; font-style: italic;">// prints INFO</span></pre></div></div>

<p>prints:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">service</span>.<span style="color: #006600;">grails</span>.<span style="color: #006600;">plugin</span>.<span style="color: #006600;">redis</span>.<span style="color: #006600;">RedisService</span> <span style="color: #66cc66;">-&gt;</span> WARN
grails.<span style="color: #006600;">app</span>.<span style="color: #006600;">service</span>.<span style="color: #006600;">grails</span>.<span style="color: #006600;">plugin</span>.<span style="color: #006600;">redis</span>.<span style="color: #006600;">RedisService</span> <span style="color: #66cc66;">-&gt;</span> INFO</pre></div></div>

<p>It&#8217;d be easy to turn this into a simple gsp/controller that accepts changes and can list things out.  There are also a number of other plugins out there that let you view/change logging levels (including another one of Burt&#8217;s plugins, <a href="http://grails.org/plugin/app-info" onclick="pageTracker._trackPageview('/outgoing/grails.org/plugin/app-info?referer=');">app info</a>), but if you don&#8217;t have those installed, this is a quick way to see what&#8217;s going on with your application.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2011/09/23/dynamically-setting-grails-log4j-levels-with-the-console-plugin/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating New Instances of Spring &#8220;Singleton&#8221; Beans with Grails BeanBuilder</title>
		<link>http://naleid.com/blog/2011/03/07/creating-new-instances-of-spring-singleton-beans-with-grails-beanbuilder/</link>
		<comments>http://naleid.com/blog/2011/03/07/creating-new-instances-of-spring-singleton-beans-with-grails-beanbuilder/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 05:11:41 +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=301</guid>
		<description><![CDATA[When I&#8217;m integration testing Grails service classes, I often want to mock off a part of the class so that a complicated code branch isn&#8217;t followed that I&#8217;m not trying to test. Grails will helpfully inject fully autowired Spring service beans into my test if I ask for them. Unfortunately, if I change the metaClass [...]]]></description>
			<content:encoded><![CDATA[<p>When I&#8217;m integration testing Grails service classes, I often want to mock off a part of the class so that a complicated code branch isn&#8217;t followed that I&#8217;m not trying to test.</p>
<p>Grails will helpfully inject fully autowired Spring service beans into my test if I ask for them.  Unfortunately, if I change the metaClass of the injected service, that change persists beyond where we want it to:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> MyService <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #ff0000;">&quot;unmodified&quot;</span> <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> MyServiceTests <span style="color: #000000; font-weight: bold;">extends</span> GroovyTestCase <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myService  <span style="color: #808080; font-style: italic;">// injected automatically by spring/grails</span>
&nbsp;
    <span style="color: #993333;">void</span> testOne<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        myService.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">myMethod</span> <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">-&gt;</span> <span style="color: #ff0000;">&quot;modified&quot;</span> <span style="color: #66cc66;">&#125;</span>
        assertEquals <span style="color: #ff0000;">&quot;modified&quot;</span>, myService.<span style="color: #006600;">myMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span> 
&nbsp;
    <span style="color: #993333;">void</span> testTwo<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        assertEquals  <span style="color: #ff0000;">&quot;unmodified&quot;</span>, myService.<span style="color: #006600;">myMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// WTF!  Returns &quot;modified&quot;, pollution from first test</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Grails services are Spring &#8220;singleton&#8221; objects.  They&#8217;re not true singletons though, singleton&#8217;s are just cached in the application context and returned whenever <code>getBean</code> is called.  </p>
<p>Historically, if I wanted to mock part of my service manually, I&#8217;d need to &#8220;new&#8221; up my own instance of the service and manually inject any dependencies that the service might need to function.   This is both painful and fragile, if the service adds or removes dependencies, chances are that the tests are going to break.</p>
<p>I realized that if I could ask Grails/Spring for a new instance of the &#8220;singleton&#8221; service that I could muck with it all I wanted in my test without worrying about polluting other tests with my changes.   After some digging into the grails spring support, I came up with the following method that could be added to an integration test (or integration test base class):</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// spring &quot;singleton&quot; objects really aren't they're just cached by their application context</span>
<span style="color: #000000; font-weight: bold;">def</span> getNewSingletonInstanceOf<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> clazz<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #aaaadd; font-weight: bold;">String</span> beanName <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;prototype${clazz.name}&quot;</span>
    BeanBuilder beanBuilder <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BeanBuilder<span style="color: #66cc66;">&#40;</span>ApplicationHolder.<span style="color: #006600;">application</span>.<span style="color: #006600;">mainContext</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
    beanBuilder.<span style="color: #006600;">beans</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #ff0000;">&quot;$beanName&quot;</span><span style="color: #66cc66;">&#40;</span>clazz<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> bean <span style="color: #66cc66;">-&gt;</span>
            bean.<span style="color: #006600;">autowire</span> <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'byName'</span>
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    beanBuilder.<span style="color: #006600;">createApplicationContext</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getBean</span><span style="color: #66cc66;">&#40;</span>beanName<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>This method uses the BeanBuilder to construct a temporary ApplicationContext with the Grails mainContext as a parent so that other dependencies can be resolved.   This method won&#8217;t work if your service has changes to how it&#8217;s wired up and configured by spring, but the majority of Grails service classes are simply autowired <code>byName</code>.</p>
<p>Here&#8217;s a more detailed example of use.  Given this service:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #a1a100;">com.example</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> MyService <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> injectedService
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> serviceMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> otherMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> otherMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #ff0000;">&quot;original value&quot;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>I&#8217;m able to generate per-test autowired instances of my service and mock out <code>otherMethod</code> without polluting other tests (or the Spring injected version of the bean):</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #a1a100;">com.example</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #a1a100;">grails.spring.BeanBuilder</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #a1a100;">org.codehaus.groovy.grails.commons.ApplicationHolder</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> MyServiceTests <span style="color: #000000; font-weight: bold;">extends</span> GroovyTestCase <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> myServiceInstance  <span style="color: #808080; font-style: italic;">// our new</span>
    <span style="color: #000000; font-weight: bold;">def</span> myService <span style="color: #808080; font-style: italic;">// spring injected version</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> setUp<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">setUp</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        myServiceInstance <span style="color: #66cc66;">=</span> getNewSingletonInstanceOf<span style="color: #66cc66;">&#40;</span>MyService<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #993333;">void</span> tearDown<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">tearDown</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">// spring &quot;singleton&quot; objects really aren't they're just cached by their application context</span>
    <span style="color: #000000; font-weight: bold;">def</span> getNewSingletonInstanceOf<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> clazz<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #aaaadd; font-weight: bold;">String</span> beanName <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;prototype${clazz.name}&quot;</span>
        BeanBuilder beanBuilder <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BeanBuilder<span style="color: #66cc66;">&#40;</span>ApplicationHolder.<span style="color: #006600;">application</span>.<span style="color: #006600;">mainContext</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
        beanBuilder.<span style="color: #006600;">beans</span> <span style="color: #66cc66;">&#123;</span>
            <span style="color: #ff0000;">&quot;$beanName&quot;</span><span style="color: #66cc66;">&#40;</span>clazz<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span> bean <span style="color: #66cc66;">-&gt;</span>
                bean.<span style="color: #006600;">autowire</span> <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'byName'</span>
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
&nbsp;
        beanBuilder.<span style="color: #006600;">createApplicationContext</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getBean</span><span style="color: #66cc66;">&#40;</span>beanName<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> testNewSingletonInstance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        assertNotNull myServiceInstance <span style="color: #808080; font-style: italic;">// created uniquely for this test in setUp</span>
        assertNotNull myService         <span style="color: #808080; font-style: italic;">// spring injected into integration test</span>
&nbsp;
        assertNotSame myService, myServiceInstance
&nbsp;
        <span style="color: #808080; font-style: italic;">// we've got unique instances of MyService, but both are injected with the same singleton dependencies</span>
        assertSame myService.<span style="color: #006600;">injectedService</span>, myServiceInstance.<span style="color: #006600;">injectedService</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> testMessingWithMetaClassDoesNotAffectOriginalSingleton<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        myServiceInstance.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">otherMethod</span> <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">-&gt;</span> <span style="color: #ff0000;">&quot;new value&quot;</span> <span style="color: #66cc66;">&#125;</span>
&nbsp;
        assertEquals <span style="color: #ff0000;">&quot;new value&quot;</span>, myServiceInstance.<span style="color: #006600;">serviceMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        assertEquals <span style="color: #ff0000;">&quot;original value&quot;</span>, myService.<span style="color: #006600;">serviceMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">def</span> anotherInstance <span style="color: #66cc66;">=</span> getNewSingletonInstanceOf<span style="color: #66cc66;">&#40;</span>MyService<span style="color: #66cc66;">&#41;</span>
&nbsp;
        assertEquals <span style="color: #ff0000;">&quot;original value&quot;</span>, anotherInstance.<span style="color: #006600;">serviceMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Using this technique lets you leverage Spring&#8217;s autowiring in your tests, but also gives you the flexibility to override areas not under test to improve test readability and maintainability.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2011/03/07/creating-new-instances-of-spring-singleton-beans-with-grails-beanbuilder/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using the Grails BeanBuilder to Set Arbitrary Properties From an External Config</title>
		<link>http://naleid.com/blog/2011/02/25/using-the-grails-beanbuilder-to-set-arbitrary-properties-from-an-external-config/</link>
		<comments>http://naleid.com/blog/2011/02/25/using-the-grails-beanbuilder-to-set-arbitrary-properties-from-an-external-config/#comments</comments>
		<pubDate>Sat, 26 Feb 2011 04:42:39 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[redis]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=285</guid>
		<description><![CDATA[I&#8217;m working with an existing library (Jedis a Redis client library) that has a fairly complicated connection pool config file with a large variety of potential properties that could be worth setting depending on the environment that my Grails app is running in. I wanted the ability to define the set of properties that I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working with an existing library (<a href="https://github.com/xetorthio/jedis" onclick="pageTracker._trackPageview('/outgoing/github.com/xetorthio/jedis?referer=');">Jedis</a> a <a href="http://redis.io" onclick="pageTracker._trackPageview('/outgoing/redis.io?referer=');">Redis</a> client library) that has a <a href="https://github.com/xetorthio/jedis/blob/master/src/main/java/redis/clients/jedis/JedisPoolConfig.java" onclick="pageTracker._trackPageview('/outgoing/github.com/xetorthio/jedis/blob/master/src/main/java/redis/clients/jedis/JedisPoolConfig.java?referer=');">fairly complicated connection pool config file with a large variety of potential properties</a> that could be worth setting depending on the environment that my Grails app is running in.</p>
<p>I wanted the ability to define the set of properties that I wanted to override in the config file without having to call them all out explicitly in the Spring resources.groovy file.   If I missed one, or if the client library that I&#8217;m using added a new one that I don&#8217;t notice, I don&#8217;t want to have to release a new version of the code just to set it.</p>
<p>Grails allows you to load external config files simply by defining a reference to them in Config.groovy (this code is even commented out in the default Config.groovy file that gets generated automatically with a new grails app):</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">grails.<span style="color: #006600;">config</span>.<span style="color: #006600;">locations</span> <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;file:${userHome}/.grails/${appName}-config.groovy&quot;</span><span style="color: #66cc66;">&#93;</span></pre></div></div>

<p>After a little playing around with the BeanBuilder syntax, I was able to come up with a solution that lets me set whatever values I want in the Config file and have them set on the bean that I have Spring/Grails build.</p>
<p>If you have a config like this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">foo <span style="color: #66cc66;">&#123;</span>
    foo <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;bar&quot;</span>
    baz <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">4</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>You can populate your resources.groovy with something like this to set whatever<br />
values are set in your config file:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">beans <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> fooMap <span style="color: #66cc66;">=</span> application.<span style="color: #006600;">config</span><span style="color: #66cc66;">?</span>.<span style="color: #006600;">foo</span>
&nbsp;
    fooBean<span style="color: #66cc66;">&#40;</span>Foo<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        fooMap<span style="color: #66cc66;">?</span>.<span style="color: #663399;">each</span> <span style="color: #66cc66;">&#123;</span> key, value <span style="color: #66cc66;">-&gt;</span>
            delegate.<span style="color: #006600;">setProperty</span><span style="color: #66cc66;">&#40;</span>key, value<span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>This will make a bean that has it&#8217;s `foo` set to &#8220;bar&#8221; and it&#8217;s `baz` set to 4.   </p>
<p>Later, if I find that I need to set the `baz` property on the fooBean in production, I just add that in my config file and everything works without any code changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2011/02/25/using-the-grails-beanbuilder-to-set-arbitrary-properties-from-an-external-config/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Introduction to Using Redis with Groovy</title>
		<link>http://naleid.com/blog/2010/12/28/intro-to-using-redis-with-groovy/</link>
		<comments>http://naleid.com/blog/2010/12/28/intro-to-using-redis-with-groovy/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 07:34:42 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[redis]]></category>
		<category><![CDATA[cache]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=248</guid>
		<description><![CDATA[I&#8217;m more excited about Redis than just about any other technology right now. Redis is an insanely fast key/value store, in some ways similar to memcached, but the values it stores aren&#8217;t just dumb blobs of data, but can also be hashes, lists, sets and sorted sets. It provides a number of atomic operations on [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m more excited about <a href="http://redis.io" onclick="pageTracker._trackPageview('/outgoing/redis.io?referer=');">Redis</a> than just about any other technology right now.    </p>
<p>Redis is an <a href="http://redis.io/topics/benchmarks" onclick="pageTracker._trackPageview('/outgoing/redis.io/topics/benchmarks?referer=');">insanely fast</a> key/value store, in some ways similar to <a href="http://memcached.org/" onclick="pageTracker._trackPageview('/outgoing/memcached.org/?referer=');">memcached</a>, but the values it stores aren&#8217;t just dumb blobs of data, but can also be hashes, lists, sets and sorted sets.  It provides a number of atomic operations on each of those data types (ex: union and intersection methods on sets) and it has been called a &#8220;data structure server&#8221;.  </p>
<p>It&#8217;s used in production today by <a href="http://redis.io/topics/whos-using-redis" onclick="pageTracker._trackPageview('/outgoing/redis.io/topics/whos-using-redis?referer=');">a number of very popular websites</a> including <a href="http://craigslist.org" onclick="pageTracker._trackPageview('/outgoing/craigslist.org?referer=');">Craigslist</a>, <a href="http://github.com" onclick="pageTracker._trackPageview('/outgoing/github.com?referer=');">GitHub</a>, <a href="http://guardian.co.uk" onclick="pageTracker._trackPageview('/outgoing/guardian.co.uk?referer=');">The Guardian</a>, and <a href="http://digg.com" onclick="pageTracker._trackPageview('/outgoing/digg.com?referer=');">Digg</a>.</p>
<p>Redis is of particular note for Groovy/Grails developers because it&#8217;s development is <a href="http://blogs.vmware.com/console/2010/03/vmware-hires-key-developer-for-redis.html" onclick="pageTracker._trackPageview('/outgoing/blogs.vmware.com/console/2010/03/vmware-hires-key-developer-for-redis.html?referer=');">financially supported by VMWare/SpringSource</a>.  Redis was also the first non-relational data store to be <a href="http://www.grails.org/plugin/redis" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/plugin/redis?referer=');">officially supported by core Grails developers</a>.</p>
<p>It has <a href="http://redis.io/commands" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands?referer=');">excellent documentation</a> and a <a href="http://redis.io/topics/protocol" onclick="pageTracker._trackPageview('/outgoing/redis.io/topics/protocol?referer=');">super simple wire protocol</a> that has made it easy for a <a href="http://redis.io/clients" onclick="pageTracker._trackPageview('/outgoing/redis.io/clients?referer=');">ton of client libraries for just about every language</a> to pop up.  You could probably write a simple client library in a day.  Once you know the commands, you can even interact with it through telnet (though you don&#8217;t have to :).</p>
<h2>Installing Redis</h2>
<p><span id="more-248"></span><br />
There are a number of ways to <a href="http://redis.io/download" onclick="pageTracker._trackPageview('/outgoing/redis.io/download?referer=');">install redis</a>.  For testing, I like to grab the source and play with that:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">%</span> <span style="color: #c20cb9; font-weight: bold;">git</span> clone <span style="color: #c20cb9; font-weight: bold;">git</span>:<span style="color: #000000; font-weight: bold;">//</span>github.com<span style="color: #000000; font-weight: bold;">/</span>antirez<span style="color: #000000; font-weight: bold;">/</span>redis.git
<span style="color: #000000; font-weight: bold;">%</span> <span style="color: #c20cb9; font-weight: bold;">make</span></pre></div></div>

<p>Just in case, you might want to run the tests to ensure the master branch you just grabbed is working (they take about 5 minutes to run).</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">%</span> <span style="color: #c20cb9; font-weight: bold;">make</span> <span style="color: #7a0874; font-weight: bold;">test</span></pre></div></div>

<p>Starting up a server is as easy as</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">%</span> src<span style="color: #000000; font-weight: bold;">/</span>redis-server</pre></div></div>

<p>You can then benchmark it on your system to see the performance:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">%</span> src<span style="color: #000000; font-weight: bold;">/</span>redis-benchmark 
====== PING ======
  <span style="color: #000000;">10000</span> requests completed <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000;">0.19</span> seconds
  <span style="color: #000000;">50</span> parallel clients
  <span style="color: #000000;">3</span> bytes payload
  keep alive: <span style="color: #000000;">1</span>
&nbsp;
<span style="color: #000000;">70.03</span><span style="color: #000000; font-weight: bold;">%</span> <span style="color: #000000; font-weight: bold;">&lt;</span>= <span style="color: #000000;">1</span> milliseconds
<span style="color: #000000;">100.00</span><span style="color: #000000; font-weight: bold;">%</span> <span style="color: #000000; font-weight: bold;">&lt;</span>= <span style="color: #000000;">1</span> milliseconds
<span style="color: #000000;">51546.39</span> requests per second
...</pre></div></div>

<p>By default, it runs on port 6379 though you can override defaults with a configuration file.</p>
<p>It has a simple REPL built in where you can issue commands and see the results.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">%</span> src<span style="color: #000000; font-weight: bold;">/</span>redis-cli
redis<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">set</span> tick <span style="color: #ff0000;">&quot;SPOOOON!!!&quot;</span>
OK
redis<span style="color: #000000; font-weight: bold;">&gt;</span> get tick
<span style="color: #ff0000;">&quot;SPOOOON!!!&quot;</span></pre></div></div>

<p>You can use the <a href="http://redis.io/commands/monitor" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/monitor?referer=');">monitor</a> command to watch all of the requests that redis processes.  If we had a monitoring session running while issuing the commands above, this is what it would look like:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">%</span> src<span style="color: #000000; font-weight: bold;">/</span>redis-cli
redis<span style="color: #000000; font-weight: bold;">&gt;</span> monitor
OK
<span style="color: #000000;">1293518654.694160</span> <span style="color: #ff0000;">&quot;monitor&quot;</span>
<span style="color: #000000;">1293518700.558202</span> <span style="color: #ff0000;">&quot;set&quot;</span> <span style="color: #ff0000;">&quot;tick&quot;</span> <span style="color: #ff0000;">&quot;SPOOOON!!!&quot;</span>
<span style="color: #000000;">1293518702.69875</span> <span style="color: #ff0000;">&quot;get&quot;</span> <span style="color: #ff0000;">&quot;tick&quot;</span></pre></div></div>

<h2>Using Groovy&#8217;s Grape Annotation to Grab the Jedis Java client library</h2>
<p>The <a href="https://github.com/xetorthio/jedis" onclick="pageTracker._trackPageview('/outgoing/github.com/xetorthio/jedis?referer=');">jedis</a> java library provides a thin layer over the wire protocol.  <a href="http://redis.io/commands" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands?referer=');">Redis Commands</a> are simply turned into method names so the redis documentation also works well as jedis documentation.  </p>
<p>If you&#8217;re using a recent version of groovy, you can leverage the grape dependency system to automatically download the jedis jar and include it in our classpath.  Connecting to our Redis localhost server running on the default port (6379) is as simple as this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env groovy</span>
@Grapes<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>
    @Grab<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'redis.clients:jedis:1.5.1'</span><span style="color: #66cc66;">&#41;</span>,
    @GrabConfig<span style="color: #66cc66;">&#40;</span>systemClassLoader<span style="color: #66cc66;">=</span><span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #a1a100;">redis.clients.jedis.*</span>
&nbsp;
Jedis jedis <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Jedis<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;localhost&quot;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<h2>Strings</h2>
<p><a href="http://redis.io/commands#string" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands_string?referer=');">Strings</a> are the simplest data type in Redis.  We can use <code>set</code> to save them and <code>get</code> to retrieve a saved value.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">jedis.<span style="color: #006600;">set</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;foo&quot;</span>, <span style="color: #ff0000;">&quot;bar&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #663399;">get</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;foo&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;bar&quot;</span></pre></div></div>

<p>We can add a little groovy meta-programming to make working with simple strings (<a href="http://redis.io/commands/get" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/get?referer=');">GET</a>/<a href="http://redis.io/commands/set" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/set?referer=');">SET</a>) a little easier through property accessors.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// let's make Jedis a little more groovy and call get/set through property accessors</span>
Jedis.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">getProperty</span> <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">String</span> name <span style="color: #66cc66;">-&gt;</span>
    delegate.<span style="color: #663399;">get</span><span style="color: #66cc66;">&#40;</span>name<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
Jedis.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">setProperty</span> <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">String</span> name, value <span style="color: #66cc66;">-&gt;</span>
    delegate.<span style="color: #006600;">set</span><span style="color: #66cc66;">&#40;</span>name, value<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
Jedis jedis <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Jedis<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;localhost&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// get/set basic String values</span>
jedis.<span style="color: #006600;">name</span> <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;Ted Naleid&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">name</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;Ted Naleid&quot;</span></pre></div></div>

<h2>Integers/Counters</h2>
<p>Redis stores all numeric String values internally as integers that can be atomically incremented and decremented.  If the value doesn&#8217;t exist, incrementing it sets it to 1.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">jedis.<span style="color: #006600;">beanCounter</span> <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;4&quot;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">incr</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;beanCounter&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">5</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">incr</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;beanCounter&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">6</span>
jedis.<span style="color: #006600;">del</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;beanCounter&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">incr</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;beanCounter&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">1</span></pre></div></div>

<p>If the value we&#8217;re incrementing isn&#8217;t an integer, redis it&#8217;ll throw an execption when we try to increment it.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">jedis.<span style="color: #006600;">notAnInteger</span> <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;foo&quot;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
    jedis.<span style="color: #006600;">incr</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;notAnInteger&quot;</span><span style="color: #66cc66;">&#41;</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: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;shouldn't get here, need an integer to increment&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #66cc66;">&#40;</span>redis.<span style="color: #006600;">clients</span>.<span style="color: #006600;">jedis</span>.<span style="color: #006600;">JedisException</span> e<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> e.<span style="color: #006600;">message</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;ERR value is not an integer or out of range&quot;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h2>Expire and TTL (Time To Live)</h2>
<p>Redis has a number of useful <a href="http://redis.io/commands#generic" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands_generic?referer=');">generic functions</a> including the ability to act as a cache.  Just tell Redis when the key should expire (in seconds).</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">jedis.<span style="color: #ff0000;">&quot;expire:me&quot;</span> <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;value to expire&quot;</span>
jedis.<span style="color: #006600;">expire</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;expire:me&quot;</span>, <span style="color: #cc66cc;">60</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">ttl</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;expire:me&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">50</span> 
&nbsp;
<span style="color: #808080; font-style: italic;">// -1 means &quot;never expire&quot;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">ttl</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;brand new value&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">1</span></pre></div></div>

<h2>Lists</h2>
<p>The <a href="http://redis.io/commands#list" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands_list?referer=');">list</a> data structure works very much like it does in groovy/java.</p>
<p>You can push items onto the end of the list:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// if the list doesn't exist, it'll create it and add the initial element</span>
jedis.<span style="color: #006600;">rpush</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #ff0000;">&quot;Bravo&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">rpush</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #ff0000;">&quot;Charlie&quot;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Or the start of the list:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">jedis.<span style="color: #006600;">lpush</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #ff0000;">&quot;Alpha&quot;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>To see the contents of a list, you need to ask it for a range of elements.  <code>lrange</code> shows a slice of a 0-based list.  The last parameter can use negative indexes to refer to an offset from the end of the list.  </p>
<p><code>-1</code> means the last element, <code>-2</code> is the 2nd to last element, etc.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;Alpha&quot;</span>, <span style="color: #ff0000;">&quot;Bravo&quot;</span>, <span style="color: #ff0000;">&quot;Charlie&quot;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #808080; font-style: italic;">// whole list</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;Alpha&quot;</span>, <span style="color: #ff0000;">&quot;Bravo&quot;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #808080; font-style: italic;">// all but last item</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #cc66cc;">0</span>,  <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;Alpha&quot;</span>, <span style="color: #ff0000;">&quot;Bravo&quot;</span><span style="color: #66cc66;">&#93;</span>  <span style="color: #808080; font-style: italic;">// first and 2nd items</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #cc66cc;">1</span>,  <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;Bravo&quot;</span>, <span style="color: #ff0000;">&quot;Charlie&quot;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #808080; font-style: italic;">// 2nd and 3rd items</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">llen</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">3</span></pre></div></div>

<p>You can also pop elements off of the start or the end of the list.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// pop the first item off the list</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lpop</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;Alpha&quot;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// pop the last item off the list</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">rpop</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #ff0000;">&quot;Charlie&quot;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// only one thing left</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">llen</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">1</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;Bravo&quot;</span><span style="color: #66cc66;">&#93;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// del deletes the value associated with the key (no matter the type)</span>
jedis.<span style="color: #006600;">del</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #808080; font-style: italic;">// geting the whole range for a key that doesn't exist safely returns an empty list</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">lrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;alphabet&quot;</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span></pre></div></div>

<p>Lists also have blocking versions of pop.  If the list is empty it will wait till something gets pushed onto the list (<a href="http://redis.io/commands/blpop" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/blpop?referer=');">left</a> and <a href="http://redis.io/commands/brpop" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/brpop?referer=');">right</a> versions).   This allows you to use redis as a system-wide blocking queue and have a bunch of producer jobs feed work to a number of waiting worker jobs.</p>
<h2>Sets</h2>
<p>Redis <a href="">sets</a> have a number of powerful atomic set operations such as <a href="http://redis.io/commands/sunion" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/sunion?referer=');">union</a>, <a href="http://redis.io/commands/sinter" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/sinter?referer=');">intersection</a>, and <a href="http://redis.io/commands/sdiff" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/sdiff?referer=');">difference</a></p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// add a bunch of items to the palindromes set</span>
jedis.<span style="color: #006600;">sadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;radar&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">sadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;noon&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">sadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;kayak&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">smembers</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">containsAll</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;radar&quot;</span>, <span style="color: #ff0000;">&quot;noon&quot;</span>, <span style="color: #ff0000;">&quot;kayak&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// check to see if an item is a member of a set</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">sismember</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;kayak&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #000000; font-weight: bold;">true</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// remove a member from the set</span>
jedis.<span style="color: #006600;">srem</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;kayak&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">sismember</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;kayak&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #000000; font-weight: bold;">false</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// set size (cardinality)</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">scard</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">2</span>
&nbsp;
jedis.<span style="color: #006600;">sadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;acronyms&quot;</span>, <span style="color: #ff0000;">&quot;scuba&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">sadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;acronyms&quot;</span>, <span style="color: #ff0000;">&quot;radar&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// set union</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">sunion</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;acronyms&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">containsAll</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;scuba&quot;</span>, <span style="color: #ff0000;">&quot;noon&quot;</span>, <span style="color: #ff0000;">&quot;radar&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// set intersection</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">sinter</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;acronyms&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">containsAll</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;radar&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// set difference</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">sdiff</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;palindromes&quot;</span>, <span style="color: #ff0000;">&quot;acronyms&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">containsAll</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;noon&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">sdiff</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;acronyms&quot;</span>, <span style="color: #ff0000;">&quot;palindromes&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">containsAll</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;scuba&quot;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>Each of these methods also has a &#8220;store&#8221; version (<a href="http://redis.io/commands/sunionstore" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/sunionstore?referer=');">SUNIONSTORE</a>, <a href="http://redis.io/commands/sinterstore" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/sinterstore?referer=');">SINTERSTORE</a>, <a href="http://redis.io/commands/sdiffstore" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/sdiffstore?referer=');">SDIFFSTORE</a>) that allows you to atomically save the results of the set operation to another key as a new set.</p>
<h2>Sorted Sets</h2>
<p><a href="http://redis.io/commands#sorted_set" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands_sorted_set?referer=');">Sorted Sets</a> combine the functionality of sets and lists by adding a &#8220;score&#8221; associated with each element of the set that determines it&#8217;s position.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// add months to a sorted set in random order</span>
jedis.<span style="color: #006600;">zadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">1</span>,  <span style="color: #ff0000;">&quot;January&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">zadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">12</span>, <span style="color: #ff0000;">&quot;December&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">zadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">5</span>,  <span style="color: #ff0000;">&quot;May&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">zadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">9</span>,  <span style="color: #ff0000;">&quot;September&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">zadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">3</span>,  <span style="color: #ff0000;">&quot;March&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">zadd</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">10</span>, <span style="color: #ff0000;">&quot;October&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// the sorted set returns them in sorted order and can be sliced similarly to lists</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">zrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toArray</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;January&quot;</span>, <span style="color: #ff0000;">&quot;March&quot;</span>, <span style="color: #ff0000;">&quot;May&quot;</span>, <span style="color: #ff0000;">&quot;September&quot;</span>, <span style="color: #ff0000;">&quot;October&quot;</span>, <span style="color: #ff0000;">&quot;December&quot;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">zrange</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;months&quot;</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #66cc66;">-</span><span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">toArray</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;September&quot;</span>, <span style="color: #ff0000;">&quot;October&quot;</span><span style="color: #66cc66;">&#93;</span></pre></div></div>

<h2>Hashes</h2>
<p><a href="http://redis.io/commands#hash" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands_hash?referer=');">Hashes</a> are what the <a href="http://www.grails.org/plugin/redis" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/plugin/redis?referer=');">grails redis plugin</a> uses to store domain objects.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">jedis.<span style="color: #006600;">hset</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;book:1&quot;</span>, <span style="color: #ff0000;">&quot;title&quot;</span>, <span style="color: #ff0000;">&quot;Dune&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">hset</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;book:1&quot;</span>, <span style="color: #ff0000;">&quot;author&quot;</span>, <span style="color: #ff0000;">&quot;Frank Herbert&quot;</span><span style="color: #66cc66;">&#41;</span>
jedis.<span style="color: #006600;">hset</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;book:1&quot;</span>, <span style="color: #ff0000;">&quot;yearPublished&quot;</span>, <span style="color: #ff0000;">&quot;1965&quot;</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> jedis.<span style="color: #006600;">hgetAll</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;book:1&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span>author: <span style="color: #ff0000;">&quot;Frank Herbert&quot;</span>, title: <span style="color: #ff0000;">&quot;Dune&quot;</span>, yearPublished: <span style="color: #ff0000;">&quot;1965&quot;</span><span style="color: #66cc66;">&#93;</span></pre></div></div>

<p>There are also commands to pull out <a href="http://redis.io/commands/hkeys" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/hkeys?referer=');">just the keys</a>, <a href="http://redis.io/commands/hvals" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/hvals?referer=');">just the values</a>, subset of <a href="http://redis.io/commands/hmget" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/hmget?referer=');">values for particular keys</a> or to check the <a href="http://redis.io/commands/hexists" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands/hexists?referer=');">existence of a key</a>.</p>
<h2>Publish/Subscribe</h2>
<p>Redis also has some powerful <a href="http://redis.io/commands#pubsub" onclick="pageTracker._trackPageview('/outgoing/redis.io/commands_pubsub?referer=');">Publish/Subscribe</a> commands that allow the subscriber to listen for new messages on a channel.   This allows <a href="http://rediscookbook.org/pubsub_for_synchronous_communication.html" onclick="pageTracker._trackPageview('/outgoing/rediscookbook.org/pubsub_for_synchronous_communication.html?referer=');">broadcast messages to be sent out by a publisher to any subscribers</a> of a topic.   It&#8217;s the compliment to the lists&#8217; ability to act as a blocking queue.</p>
<h2>Summary</h2>
<p>Redis is a utility belt of functionality and I&#8217;ve only scratched the surface of what you can do with it in this post.  </p>
<p>At my current startup, we&#8217;re looking at using Redis for caching and paginating through some very expensive ad-hoc calculations that are unique to each user of the website.  Being able to do this quickly is critical to the user experience, and Redis looks like it has what we need to make this work.  The sorted set operations also allow us to easily slice through the data in a way that would normally require something like temp tables in a relational database.</p>
<p>While it can be used as the only data store for an application, I think it&#8217;s a perfect compliment for an application with a traditional relational database.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/12/28/intro-to-using-redis-with-groovy/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Grails issue &#8216;not processed by flush()&#8217; root causes</title>
		<link>http://naleid.com/blog/2010/11/21/grails-issue-not-processed-by-flush-root-causes/</link>
		<comments>http://naleid.com/blog/2010/11/21/grails-issue-not-processed-by-flush-root-causes/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 04:04:42 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[session]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=234</guid>
		<description><![CDATA[I&#8217;ve learned some painful lessons recently around hibernate sessions in grails that are pretty obvious in retrospect. I wanted to get some quick notes down as there&#8217;s not a lot of good information out there around this in grails that I could find. Here are some quick bullet points about what I&#8217;ve learned around grails [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve learned some painful lessons recently around hibernate sessions in grails that are pretty obvious in retrospect.  I wanted to get some quick notes down as there&#8217;s not a lot of good information out there around this in grails that I could find.  Here are some quick bullet points about what I&#8217;ve learned around grails management of the hibernate session and when it gets flushed.</p>
<ul>
<li>
Grails normally manages when the session gets flushed, sometimes this happens when you might not be expecting it and isn&#8217;t always caused by a save/delete.  It can be caused by doing a read only command too.
</li>
<li>
If you have an object that you&#8217;ve made changes to (it&#8217;s dirty), if you make  any calls to the database involving that object (such as a findBy using the object), grails will automatically flush the session so that the query that you make is consistent.
</li>
<li>
if it didn&#8217;t do this, your query wouldn&#8217;t have the dirty information available to it and your query would return results inconsistent with reality in the session you&#8217;re using.  So if you have a parent object that&#8217;s dirty because you added a child object, but before saving it, you called Children.findAllByParent(parent).  The parent object gets flushed to the database so the findAll is correct.
</li>
<li>
If that&#8217;s not a big deal to you (you&#8217;re querying something that doesn&#8217;t have anything to do with the dirty fields), you can use Foo.withNewSession { } closure to make the database call without flushing the current session
</li>
<li>
if it <i>is</i> a big deal to you, then let the session flush and let the object get persisted.
</li>
<li>
<strong>but</strong> if in the process of flushing (before the findBy/query gets run) additional objects are brought into the session, you&#8217;ll hit the dreaded &#8216;collection [com.foo.bar.Baz.quxs] was not processed by flush()&#8217;
</li>
<li>
One place where this could happen is if you have a custom validator that does a query to the database and pulls any related objects back that aren&#8217;t already in the session  (ex: a validator on Parent that asserts that all children are younger than the parent).
</li>
<li>
You can use Foo.withNewSession in your custom validators to try to get around this.  But beware a StackOverflow error (or a red zone memory exception on OSX because of a JVM bug) where it gets into a loop of flushing out sessions
</li>
<li>
If you do use Foo.withNewSession, make sure you understand that the database calls that you make will be completely unaware of any changes to the current object.  Also that you won&#8217;t be able to use the instance of the object passed to the custom validator, but will instead have to do Foo.load(object.id) and then use the result of that to query the DB.  The performance of all of this probably sucks (but that might not matter for your use case).
</li>
<li>
Chances are that what you should really be doing though is using a service/transaction and actually saving the object first before calling the dynamic finder on the dirty object.  Then, when it&#8217;s persisted, you can safely use the clean object in your finder.
</li>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/11/21/grails-issue-not-processed-by-flush-root-causes/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Adding Logging around all of the Methods of a Class with Groovy</title>
		<link>http://naleid.com/blog/2010/09/11/adding-logging-around-all-of-the-methods-of-a-class-with-groovy/</link>
		<comments>http://naleid.com/blog/2010/09/11/adding-logging-around-all-of-the-methods-of-a-class-with-groovy/#comments</comments>
		<pubDate>Sat, 11 Sep 2010 19:09:12 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=213</guid>
		<description><![CDATA[An interesting question came up on stack overflow, &#8220;In Groovy Is there a way to decorate every class to add tracing&#8221;. I came up with the following solution using groovy&#8217;s invokeMethod. The invokeMethod method gets called by groovy&#8217;s MOP for every method call that happens on an object. If we add our own version, we [...]]]></description>
			<content:encoded><![CDATA[<p>An interesting question came up on stack overflow, <a href="http://stackoverflow.com/questions/3691933/in-groovy-is-there-a-way-to-decorate-every-class-to-add-tracing/3692250" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/questions/3691933/in-groovy-is-there-a-way-to-decorate-every-class-to-add-tracing/3692250?referer=');">&#8220;In Groovy Is there a way to decorate every class to add tracing&#8221;</a>.  I came up with the following solution using groovy&#8217;s invokeMethod.</p>
<p>The invokeMethod method gets called by groovy&#8217;s MOP for every method call that happens on an object.  If we add our own version, we need to make sure we keep a reference to the original metaClass so that within our invokeMethod, we can still get access to the other methods that we want to delegate to.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Foo <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> bar<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #993399;">println</span> <span style="color: #ff0000;">&quot;in bar&quot;</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> baz<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #993399;">println</span> <span style="color: #ff0000;">&quot;in baz with $name&quot;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> decorateMethodsWithLogging<span style="color: #66cc66;">&#40;</span>clazz<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> mc <span style="color: #66cc66;">=</span> clazz.<span style="color: #006600;">metaClass</span>
&nbsp;
    mc.<span style="color: #993399;">invokeMethod</span> <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">String</span> name, args <span style="color: #66cc66;">-&gt;</span>
        <span style="color: #993399;">println</span> <span style="color: #ff0000;">&quot;before $name, args = $args&quot;</span>
        <span style="color: #000000; font-weight: bold;">def</span> result <span style="color: #66cc66;">=</span> mc.<span style="color: #006600;">getMetaMethod</span><span style="color: #66cc66;">&#40;</span>name, args<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">invoke</span><span style="color: #66cc66;">&#40;</span>delegate, args<span style="color: #66cc66;">&#41;</span>
        <span style="color: #993399;">println</span> <span style="color: #ff0000;">&quot;after $name&quot;</span>
        <span style="color: #000000; font-weight: bold;">return</span> result
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
&nbsp;
decorateMethodsWithLogging<span style="color: #66cc66;">&#40;</span>Foo.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> f <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Foo<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
f.<span style="color: #006600;">bar</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
f.<span style="color: #006600;">baz</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;qux&quot;</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>prints</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">before bar, args <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #b1b100;">in</span> bar
after bar
before baz, args <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span>qux<span style="color: #66cc66;">&#93;</span>
<span style="color: #b1b100;">in</span> baz with qux
after baz</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/09/11/adding-logging-around-all-of-the-methods-of-a-class-with-groovy/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<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: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span> collection, closure <span style="color: #66cc66;">-&gt;</span>
    <span style="color: #b1b100;">for</span> <span style="color: #66cc66;">&#40;</span> value <span style="color: #b1b100;">in</span> collection <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> value  <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">5</span> <span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">break</span>
        closure<span style="color: #66cc66;">&#40;</span>value<span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> a <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#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: #66cc66;">&#93;</span>
&nbsp;
eachUntilGreaterThanFive<span style="color: #66cc66;">&#40;</span>a<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #993399;">println</span> it
<span style="color: #66cc66;">&#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: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span> closure <span style="color: #66cc66;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">def</span> last <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">null</span>
    delegate<span style="color: #66cc66;">?</span>.<span style="color: #663399;">each</span> <span style="color: #66cc66;">&#123;</span> current <span style="color: #66cc66;">-&gt;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>last<span style="color: #66cc66;">&#41;</span> closure<span style="color: #66cc66;">&#40;</span>last, current<span style="color: #66cc66;">&#41;</span>
        last <span style="color: #66cc66;">=</span> current
    <span style="color: #66cc66;">&#125;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>last<span style="color: #66cc66;">&#41;</span> closure<span style="color: #66cc66;">&#40;</span>last, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#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: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #66cc66;">&#123;</span> current, peek <span style="color: #66cc66;">-&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: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #66cc66;">&#123;</span> current, peek <span style="color: #66cc66;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> current <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">1</span>
    <span style="color: #000000; font-weight: bold;">assert</span> peek <span style="color: #66cc66;">==</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: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> results <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
<span style="color: #66cc66;">&#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: #66cc66;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #66cc66;">&#123;</span> current, peek <span style="color: #66cc66;">-&gt;</span>
    results <span style="color: #66cc66;">&lt;&lt;</span> <span style="color: #66cc66;">&#91;</span>current, peek<span style="color: #66cc66;">&#93;</span>
<span style="color: #66cc66;">&#125;</span>
<span style="color: #000000; font-weight: bold;">assert</span> results <span style="color: #66cc66;">==</span> <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#93;</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">5</span>, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#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 also [...]]]></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: #66cc66;">=</span> Author.<span style="color: #006600;">findByName</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Edgar Allan Poe&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #aaaadd; font-weight: bold;">Book</span> b <span style="color: #66cc66;">=</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">build</span><span style="color: #66cc66;">&#40;</span>author: eap, title: <span style="color: #ff0000;">&quot;The Tell-Tale Heart&quot;</span><span style="color: #66cc66;">&#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: #66cc66;">&#40;</span><span style="color: #66cc66;">&#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: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> closureValueMap <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#91;</span>:<span style="color: #66cc66;">&#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: #66cc66;">&#40;</span>Closure closure<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> interrogator <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClosureInterrogator<span style="color: #66cc66;">&#40;</span>closure<span style="color: #66cc66;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">return</span> interrogator.<span style="color: #006600;">closureValueMap</span>
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> ClosureInterrogator<span style="color: #66cc66;">&#40;</span>Closure closure<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> oldResolveStrategy <span style="color: #66cc66;">=</span> closure.<span style="color: #006600;">getResolveStrategy</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">def</span> oldDelegate <span style="color: #66cc66;">=</span> closure.<span style="color: #006600;">getDelegate</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        closure.<span style="color: #006600;">delegate</span> <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">this</span>
        closure.<span style="color: #006600;">resolveStrategy</span> <span style="color: #66cc66;">=</span> Closure.<span style="color: #006600;">DELEGATE_FIRST</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
            closure<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #66cc66;">&#123;</span>        
            closure.<span style="color: #006600;">setDelegate</span><span style="color: #66cc66;">&#40;</span>oldDelegate<span style="color: #66cc66;">&#41;</span>
            closure.<span style="color: #006600;">setResolveStrategy</span><span style="color: #66cc66;">&#40;</span>oldResolveStrategy<span style="color: #66cc66;">&#41;</span>
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#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: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> closureValueMap<span style="color: #66cc66;">&#91;</span>name<span style="color: #66cc66;">&#93;</span>
    <span style="color: #66cc66;">&#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: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, value<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        closureValueMap<span style="color: #66cc66;">&#91;</span>name<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">=</span> value
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> methodMissing<span style="color: #66cc66;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, args<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>args.<span style="color: #663399;">size</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
            closureValueMap<span style="color: #66cc66;">&#91;</span>name<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">=</span> args<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#93;</span>
        <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
            closureValueMap<span style="color: #66cc66;">&#91;</span>name<span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">=</span> args
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#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: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">static</span> something <span style="color: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span>
        key1 <span style="color: #ff0000;">&quot;value1&quot;</span>              <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key1&quot;, [&quot;value1&quot;])</span>
        key2<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;value2&quot;</span><span style="color: #66cc66;">&#41;</span>             <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key2&quot;, [&quot;value2&quot;])</span>
        key3 <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;value3&quot;</span>            <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key3&quot;, &quot;value3&quot;)</span>
        key4 <span style="color: #ff0000;">&quot;foo&quot;</span>, <span style="color: #ff0000;">&quot;bar&quot;</span>, <span style="color: #ff0000;">&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: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#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: #66cc66;">=</span> ClosureInterrogator.<span style="color: #006600;">extractValuesFromClosure</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SomeClass<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">something</span><span style="color: #66cc66;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #ff0000;">&quot;value1&quot;</span> <span style="color: #66cc66;">==</span> closureValueMap.<span style="color: #ff0000;">&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: #ff0000;">&quot;value2&quot;</span> <span style="color: #66cc66;">==</span> closureValueMap.<span style="color: #ff0000;">&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: #ff0000;">&quot;value3&quot;</span> <span style="color: #66cc66;">==</span> closureValueMap.<span style="color: #ff0000;">&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: #66cc66;">&#91;</span><span style="color: #ff0000;">&quot;foo&quot;</span>, <span style="color: #ff0000;">&quot;bar&quot;</span>, <span style="color: #ff0000;">&quot;baz&quot;</span><span style="color: #66cc66;">&#93;</span> <span style="color: #66cc66;">==</span> closureValueMap.<span style="color: #ff0000;">&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: #66cc66;">=</span> <span style="color: #66cc66;">&#123;</span>
   to <span style="color: #ff0000;">&quot;fred@g2one.com&quot;</span>,<span style="color: #ff0000;">&quot;ginger@g2one.com&quot;</span>
   from <span style="color: #ff0000;">&quot;john@g2one.com&quot;</span>
   cc <span style="color: #ff0000;">&quot;marge@g2one.com&quot;</span>, <span style="color: #ff0000;">&quot;ed@g2one.com&quot;</span>
   bcc <span style="color: #ff0000;">&quot;joe@g2one.com&quot;</span>
   subject <span style="color: #ff0000;">&quot;Hello John&quot;</span>
   body <span style="color: #ff0000;">'this is some text'</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> results <span style="color: #66cc66;">=</span> ClosureInterrogator.<span style="color: #006600;">extractValuesFromClosure</span><span style="color: #66cc66;">&#40;</span>mailClosure<span style="color: #66cc66;">&#41;</span>
<span style="color: #993399;">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: #66cc66;">&#123;</span> it.<span style="color: #006600;">endsWith</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;g2one.com&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#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>
	</channel>
</rss>

