<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.2" -->
<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/"
	>

<channel>
	<title>dangertree techblog</title>
	<link>http://weblog.dangertree.net</link>
	<description>sweaty programming and disconnected gibberish</description>
	<pubDate>Fri, 18 Apr 2008 03:10:58 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.2</generator>
	<language>en</language>
			<item>
		<title>Groovy vs. Google Collections: Round #2</title>
		<link>http://weblog.dangertree.net/2008/04/08/groovy-vs-google-collections-round-2/</link>
		<comments>http://weblog.dangertree.net/2008/04/08/groovy-vs-google-collections-round-2/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:25:12 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[groovy]]></category>

		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2008/04/08/groovy-vs-google-collections-round-2/</guid>
		<description><![CDATA[For Round #2 of our code challenge, Dan has responded to my initial provocation in spades with a efficient example of Google Collections&#8216; MultiMap utilities.  His model involves car makes and models, their associations, and the easiest way to travel between them.  At the core of the problem is the fact that a [...]]]></description>
			<content:encoded><![CDATA[<p>For Round #2 of our code challenge, Dan has responded to my <a href="http://weblog.dangertree.net/2008/04/04/groovy-vs-google-collections-round-1/">initial provocation</a> <a href="http://www.answers.com/topic/in-spades">in spades</a> with a efficient example of <a href="http://code.google.com/p/google-collections/">Google Collections</a>&#8216; <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html">MultiMap</a> utilities.  His model involves car makes and models, their associations, and the easiest way to travel between them.  At the core of the problem is the fact that a make can have many models, and we want an easy collection that will have utilities to get the data from both ends.  Touché, my good man, because groovy doesn&#8217;t have a utility that matches the <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html">MultiMap</a> functionality.</p>
<p>In order to quickly emulate the same data structure, I was forced to push a bunch of single-element maps into a list!  Yuck!</p>
<div class="codeHeader">Setting up my collection</div>
<div class="code">
<pre>def cars = []
cars << ['Ford':'Taurus'] << ['Ford':'Focus'] << ['Ford':'Mustang']
cars << ['Chevrolet':'Malibu'] << ['Chevrolet':'Impala'] << ['Chevrolet':'Corvette']
cars << ['Dodge':'Charger'] << ['Dodge':'Avenger'] << ['Dodge':'Viper']</pre>
</div>
<p>But at least I have something I can work with now, albeit not the optimal collection that MultiMap would have provided in this case.</p>
<div class="codeHeader">The real logic</div>
<div class="code">
<pre>def printModels = { make, pair ->
    if (pair.any{it.key == make})
        println "$make makes ${(pair.values() as List)[0]}"
    make
}
def printMake = { model, pair ->
    if (pair.any{it.value == model})
        println "$model is made by ${(pair.keySet() as List)[0]}"
    model
}
cars.inject('Ford', printModels)
cars.inject('Chevrolet', printModels)
cars.inject('Dodge', printModels)
cars.inject('Impala', printMake)</pre>
</div>
<p>All the work is done in the closures.  If I had the MultiMap&#8217;s capabilities, I could have created a map that would store multiple values for each key (see Dan&#8217;s <a href="http://observationandcomment.blogspot.com/2008/04/firing-my-own-volley.html">initial volley</a>), and I could have just called <span class="c">get()</span> to retrieve a set of those values.  But my groovy closures are looking specifically for either the key or value in the list of single-element maps.  The closures are meant to be used with the <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#inject(java.lang.Object%20value,%20groovy.lang.Closure%20closure)">inject</a> method of groovy collections.  The first <span class="c">printModels</span> closure expects the make to be injected into it, and then compares it to each map key to find whether the current pair should be printed out.  The <span class="c">printMakes</span> closure expects the model to be passed, comparing it to the pair values.</p>
<p>I was disappointed to find out that groovy&#8217;s map implementation had no <em>inverse</em> operation.  In java, this is not possible, because a key can have only one value, and if you try to inverse, you might possibly have a key with many values, breaking java into tiny pieces.  Because the MultiMap allows keys to have multiple values, there is no danger in inversing the positions of keys and values, which is very handy (again, see how Dan <a href="http://observationandcomment.blogspot.com/2008/04/firing-my-own-volley.html">used it</a>)</p>
<p>The calls to <span class="c">inject</span> actually execute the closures that print out the strings.  The first three print out the models for each make injected into the closure, and the last one injects a model and prints out its make.  </p>
<p>So there are some pluses, some minuses to using groovy for this sort of problem.  On one hand, my total lines of code are still under 20, which is less than Dan&#8217;s example.  However, I&#8217;m using a Frankensteined collection (a list of single-element maps).  Can we get the best of both worlds somehow?</p>
<div class="strongpoint">You can add <strong>any</strong> java library to your groovy project, just like it was a java project.</div>
<p>So let&#8217;s add Google&#8217;s Collections package as see if we can use it <em>with</em> groovy to make our code nicer!</p>
<div class="codeHeader">Groovy and Google&#8217;s collections hand-in-hand</div>
<div class="code">
<pre>import com.google.common.collect.*

def cars = Multimaps.newHashMultimap()
cars.put('Ford','Taurus')</pre>
</div>
<p>Ok&#8230; let&#8217;s stop right there.  The groovy programmer in me <em><strong>really</strong></em> wanted to add to the map using <nobr><span class="c">cars.&#8217;Ford&#8217; = &#8216;Taurus&#8217;</span></nobr>, but no dice.  This isn&#8217;t a <em>groovy</em> map, it is a <em>google</em> map, so I&#8217;ve lost all my groovy functionality, which isn&#8217;t very groovy.  And my script from this point on is going to look suspiciously like <a href="http://pastie.caboo.se/177017">Dan&#8217;s java program</a>.  So what is the point of this experiment?  Well, it lets me know that if I run into a situation where I&#8217;ll need the functionality of a MultiMap, I can easily import the google jar and whip out an inverse-able MultiMap collection.  Only, I won&#8217;t be able to use all the sugary groovy syntax with it.  It is still better to have the option.</p>
<p>In summary, I think the google java collections package is downright cool.  Anything that makes programming simpler and easier is good for our business.  Groovy is great, but if I were working in java today, I would love this package.  Hell, I might even want to use  it with groovy someday.  Thanks to <a href="http://observationandcomment.blogspot.com/">Dan Lewis</a> for participating in my challenge and being a good sport.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2008/04/08/groovy-vs-google-collections-round-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Groovy vs. Google Collections: Round #1</title>
		<link>http://weblog.dangertree.net/2008/04/04/groovy-vs-google-collections-round-1/</link>
		<comments>http://weblog.dangertree.net/2008/04/04/groovy-vs-google-collections-round-1/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 02:15:40 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[groovy]]></category>

		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2008/04/04/groovy-vs-google-collections-round-1/</guid>
		<description><![CDATA[In my last post, Dan Lewis (my friend and former coworker) responded with some counter-code from Google&#8217;s collections package.  Instead of attempting to snap back with some witty technical retort, I challenged Dan to a code-off.  Groovy collections vs. Google collections (in Java).  Here is round one, and I&#8217;m going first with [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://weblog.dangertree.net/2008/03/29/using-collect-on-groovy-collections">last post</a>, Dan Lewis (my friend and former coworker) responded with some <a href="http://weblog.dangertree.net/2008/03/29/using-collect-on-groovy-collections/#comment-8480">counter-code</a> from <a href="http://code.google.com/p/google-collections/">Google&#8217;s collections package</a>.  Instead of attempting to snap back with some witty technical retort, I challenged Dan to a <em>code-off</em>.  Groovy collections vs. Google collections (in Java).  Here is round one, and I&#8217;m going first with an example of finding combinations of collections.  Hopefully, you can soon find Dan&#8217;s response in Google collection code-style on <a href="http://observationandcomment.blogspot.com/2008/04/groovy-vs-google-collections-round-1.html">his blog</a>.</p>
<div class="codeHeader">Create the lists</div>
<div class="code">
<pre>def boys = ['Paco', 'Sven', 'Roger', 'Emelio']
def girls = ['Julia', 'Prudence', 'Lucy']</pre>
</div>
<p>Now we have two simple lists, one of boys and one of girls.  So what if these are all dancers, and we&#8217;d like to know all the <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#combinations()">combinations</a> of dancers there could be?  With groovy, this is extremely easy.</p>
<div class="codeHeader">Find the combinations of dancers</div>
<div class="code">
<pre>def combos = [boys, girls].combinations()</pre>
</div>
<p>Could it be any easier?  This creates a list of lists, each inner list containing a possible combination:</p>
<div class="windows-cmd">[[&#8221;Paco&#8221;, &#8220;Julia&#8221;], [&#8221;Sven&#8221;, &#8220;Julia&#8221;], [&#8221;Roger&#8221;, &#8220;Julia&#8221;], [&#8221;Emelio&#8221;, &#8220;Julia&#8221;], [&#8221;Paco&#8221;, &#8220;Prudence&#8221;], [&#8221;Sven&#8221;, &#8220;Prudence&#8221;], [&#8221;Roger&#8221;, &#8220;Prudence&#8221;], [&#8221;Emelio&#8221;, &#8220;Prudence&#8221;], [&#8221;Paco&#8221;, &#8220;Lucy&#8221;], [&#8221;Sven&#8221;, &#8220;Lucy&#8221;], [&#8221;Roger&#8221;, &#8220;Lucy&#8221;], [&#8221;Emelio&#8221;, &#8220;Lucy&#8221;]]</div>
<p>Now it would be nice if i could split the list up in some way, maybe keying by male or female.  Groovy&#8217;s <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#groupBy(groovy.lang.Closure%20closure)">groupBy</a> collection method is an easy way to do this.  In the closure you provide, you simple return the key that you want to group the collection by, and it will return a map with that key pointing to a list of values.  In the following example, because I know the first element of each combination is the <em>boy</em> and the second is the <em>girl</em>, I just specify a key by element position.</p>
<div class="codeHeader">Grouping the combinations</div>
<div class="code">
<pre>def groupedByBoys = combos.groupBy { it[0] }
def groupedByGirls = combos.groupBy { it[1] }</pre>
</div>
<p>Which returns these two groupings:</p>
<div class="codeHeader">Grouped by boys</div>
<div class="windows-cmd">[&#8221;Emelio&#8221;:[[&#8221;Emelio&#8221;, &#8220;Julia&#8221;], [&#8221;Emelio&#8221;, &#8220;Prudence&#8221;], [&#8221;Emelio&#8221;, &#8220;Lucy&#8221;]], &#8220;Roger&#8221;:[[&#8221;Roger&#8221;, &#8220;Julia&#8221;], [&#8221;Roger&#8221;, &#8220;Prudence&#8221;], [&#8221;Roger&#8221;, &#8220;Lucy&#8221;]], &#8220;Sven&#8221;:[[&#8221;Sven&#8221;, &#8220;Julia&#8221;], [&#8221;Sven&#8221;, &#8220;Prudence&#8221;], [&#8221;Sven&#8221;, &#8220;Lucy&#8221;]], &#8220;Paco&#8221;:[[&#8221;Paco&#8221;, &#8220;Julia&#8221;], [&#8221;Paco&#8221;, &#8220;Prudence&#8221;], [&#8221;Paco&#8221;, &#8220;Lucy&#8221;]]]</div>
<div class="codeHeader">Grouped by girls</div>
<div class="windows-cmd">[&#8221;Lucy&#8221;:[[&#8221;Paco&#8221;, &#8220;Lucy&#8221;], [&#8221;Sven&#8221;, &#8220;Lucy&#8221;], [&#8221;Roger&#8221;, &#8220;Lucy&#8221;], [&#8221;Emelio&#8221;, &#8220;Lucy&#8221;]], &#8220;Prudence&#8221;:[[&#8221;Paco&#8221;, &#8220;Prudence&#8221;], [&#8221;Sven&#8221;, &#8220;Prudence&#8221;], [&#8221;Roger&#8221;, &#8220;Prudence&#8221;], [&#8221;Emelio&#8221;, &#8220;Prudence&#8221;]], &#8220;Julia&#8221;:[[&#8221;Paco&#8221;, &#8220;Julia&#8221;], [&#8221;Sven&#8221;, &#8220;Julia&#8221;], [&#8221;Roger&#8221;, &#8220;Julia&#8221;], [&#8221;Emelio&#8221;, &#8220;Julia&#8221;]]]</div>
<p><em><strong>Beat that, Google Collections!</strong></em></p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2008/04/04/groovy-vs-google-collections-round-1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using collect on Groovy collections</title>
		<link>http://weblog.dangertree.net/2008/03/29/using-collect-on-groovy-collections/</link>
		<comments>http://weblog.dangertree.net/2008/03/29/using-collect-on-groovy-collections/#comments</comments>
		<pubDate>Sun, 30 Mar 2008 03:22:27 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2008/03/29/using-collect-on-groovy-collections/</guid>
		<description><![CDATA[When you find something you like, you want to share it with the world.  Here are some more tricks when working with collections in Groovy that makes programming fun again!  ;)
Let&#8217;s get a sample model and some data first, then we&#8217;ll get to the fun and easy Grooviness&#8230;
Let&#8217;s create some rock stars!

class RockStar [...]]]></description>
			<content:encoded><![CDATA[<p>When you find something you like, you want to share it with the world.  Here are some more tricks when working with collections in Groovy that makes programming fun again!  ;)</p>
<p>Let&#8217;s get a sample model and some data first, then we&#8217;ll get to the fun and easy Grooviness&#8230;</p>
<div class="codeHeader">Let&#8217;s create some rock stars!</div>
<div class="code">
<pre>class RockStar {
    def name
    def bands
    def numberOfGroupies
}

def mike = new RockStar(name:"Mike Patton",
                bands:["Faith No More","Mr. Bungle"],
                numberOfGroupies:2214)
def bono = new RockStar(name:"Bono",
                bands:["U2"],
                numberOfGroupies:543582)
def slash = new RockStar(name:"Saul Hudson",
                bands:["Guns N Roses", "Velvet Revolver"],
                numberOfGroupies:32544)
def scott = new RockStar(name:"Scott Weiland",
                bands:["Stone Temple Pilots", "Velvet Revolver"],
                numberOfGroupies:41880)

def rockStarList = [mike, bono, slash, scott]</pre>
</div>
<p>As you can see, I have created a simple <a href="http://weblog.dangertree.net/2008/03/27/i-heart-pojos-pogos/">POGO</a> class, loaded some beans, then tossed them into a simple list.</p>
<p>Now what?  Well, maybe we need to make a list of all the bands our rock stars are a part of, or better yet, a set.  We don&#8217;t want the same band listed twice now!  So what is the easiest way to make this happen?  Let me introduce you to a very useful method in your Groovy toolbox, <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#collect(groovy.lang.Closure%20closure)">collect</a>.</p>
<div class="codeHeader">Collect all the bands from the rock stars</div>
<div class="code">
<pre>Set allBands = rockStarList.collect { rockStar ->
    rockStar.bands
}</pre>
</div>
<p>The closure you pass to the collect method is used to transform that list item into whatever you want.  In this case, I&#8217;m taking a list of <span class="c">RockStars</span> and transforming it into a set of string lists, containing band names.  When you run this, you will get a Set that contains the Lists within the objects.  This is really useful when you have a list of domain classes that you don&#8217;t really need, but you need to get at some information inside each of them.</p>
<div class="windows-cmd">
[[&#8221;Faith No More&#8221;, &#8220;Mr. Bungle&#8221;], [&#8221;Stone Temple Pilots&#8221;, &#8220;Velvet Revolver&#8221;], [&#8221;Guns N Roses&#8221;, &#8220;Velvet Revolver&#8221;], [&#8221;U2&#8243;]]
</div>
<p>But this is still no good!  We want a List of Strings that contain band names, not a List of Lists!  <strong>But wait!</strong>  Groovy makes this dead-easy to fix:</p>
<div class="codeHeader">Flatten the bands</div>
<div class="code">
<pre>Set allBands = rockStarList.collect { rockStar ->
    rockStar.bands
}.flatten()</pre>
</div>
<p>Using the <a href="http://groovy.codehaus.org/groovy-jdk/java/util/List.html#flatten()">flatten</a> list method does exactly what we want.  It takes all the collections within the top-level collection and adds them recursively to the top-level collection, effectively <em>flattening</em> them all out into one collection.</p>
<div class="windows-cmd">
[&#8221;Velvet Revolver&#8221;, &#8220;Stone Temple Pilots&#8221;, &#8220;U2&#8243;, &#8220;Faith No More&#8221;, &#8220;Guns N Roses&#8221;, &#8220;Mr. Bungle&#8221;]
</div>
<p>Perfect.  But you want to know the total number of groupies for every rock star?  No problem.</p>
<div class="codeHeader">Count up the groupies!</div>
<div class="code">
<pre>def totalGroupies = rockStarList.collect {
    it.numberOfGroupies
}.sum()</pre>
</div>
<div class="sidenote">If you don&#8217;t want to explicitly define the closure parameter for a closure, groovy will default to &#8220;it&#8221;.  This makes it easy to keep the characters you type down to a minimum.</div>
<p>Before we call the <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#sum()">sum()</a> method, our closure returns a List containing Integer objects.  If you call sum() on a list of any objects, this effectively calls the &#8220;plus()&#8221; method on each of the objects.  Because the list is loaded with Integer objects, these all add up nicely.</p>
<div class="sidenote">Try runnig <span class="c">1.plus(2)</span> in groovy.  Then run <span class="c">1 + 2</span>.  Same answer.  The &#8220;+&#8221; operator is resolved to the &#8220;plus()&#8221; method on whatever operand it operates on (which is an Integer object, in this case).  This happens anywhere in groovy, and with more than just &#8220;+&#8221;.</div>
<p>And there you go:</p>
<div class="windows-cmd">
620220
</div>
<p>There will be 620,220 groupies at the show.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2008/03/29/using-collect-on-groovy-collections/feed/</wfw:commentRss>
		</item>
		<item>
		<title>I *heart* POJOs POGOs</title>
		<link>http://weblog.dangertree.net/2008/03/27/i-heart-pojos-pogos/</link>
		<comments>http://weblog.dangertree.net/2008/03/27/i-heart-pojos-pogos/#comments</comments>
		<pubDate>Fri, 28 Mar 2008 02:15:04 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[groovy]]></category>

		<category><![CDATA[fun]]></category>

		<category><![CDATA[off topic]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2008/03/27/i-heart-pojos-pogos/</guid>
		<description><![CDATA[To celebrate my new position as a groovy and grails programmer at G2One Inc, I had to update my bumper sticker!





]]></description>
			<content:encoded><![CDATA[<p>To celebrate my new position as a <a href="http://groovy.codehaus.org">groovy</a> and <a href="http://grails.org">grails</a> programmer at <a href="http://www.g2one.com">G2One Inc</a>, I had to update my <a href="http://weblog.dangertree.net/2007/07/29/i-heart-winning-i-heart-pojos-stickers/">bumper sticker</a>!</p>
<div align="center">
<div class="img-without-border">
<a href='http://weblog.dangertree.net/wp-content/uploads/2008/03/dsc04798.jpg' title='I heart POGOs'><img width="600px" src='http://weblog.dangertree.net/wp-content/uploads/2008/03/dsc04798.jpg' alt='I heart POGOs' /></a>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2008/03/27/i-heart-pojos-pogos/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Groovy collection comparison is easy</title>
		<link>http://weblog.dangertree.net/2008/03/26/groovy-collection-comparison-is-easy/</link>
		<comments>http://weblog.dangertree.net/2008/03/26/groovy-collection-comparison-is-easy/#comments</comments>
		<pubDate>Thu, 27 Mar 2008 02:58:14 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2008/03/26/groovy-collection-comparison-is-easy/</guid>
		<description><![CDATA[One thing I found myself doing more than I wanted with java was collection comparison.  Many times, you might have a large list of all available items, and a smaller list of selected items.  Commonly, you might want to find all the items that exist in the large collection, but have not been [...]]]></description>
			<content:encoded><![CDATA[<p>One thing I found myself doing more than I wanted with java was collection comparison.  Many times, you might have a large list of all available items, and a smaller list of selected items.  Commonly, you might want to find all the items that exist in the large collection, but have not been &#8217;selected&#8217; in the smaller collection.  Invariably in java, this means nested loops.  </p>
<p>Not so much with groovy.</p>
<div class="codeHeader">List subtraction</div>
<div class="code">
<pre>def smallList = [1,3,5]
def bigList = [1,1,1,2,3,4,4,4,5,6,7,7,8,9]

def result = bigList - smallList
println result.class
println result</pre>
</div>
<p>The result is: </p>
<div class="windows-cmd">
<pre>class java.util.ArrayList
[2, 4, 4, 4, 6, 7, 7, 8, 9]</pre>
</div>
<p>Groovy correctly made the assumption that I was making a <span class="c">List</span> in my snippet above.  And it removed any element within the first list where <span class="c">equals()</span> was true for an element in the first list.  That means it took away three 1&#8217;s and one 3.  Keep in mind the original collections are untouched.</p>
<p>But what if I want to compare a <span class="c">List</span> and a <span class="c">Set</span>?</p>
<div class="codeHeader">Set/List addition</div>
<div class="code">
<pre>Set mySet = [1,3,5]

List myList = [0,1,2,3,4,0,1,2,3,4,5,6,7,8,9]

def addition = myList + mySet
println addition.class
println addition

addition = mySet + myList
println addition.class
println addition</pre>
</div>
<p>Now we&#8217;re adding a <span class="c">List</span> and a <span class="c">Set</span> together, and the result is different depending on which is the first operand:</p>
<div class="windows-cmd">
<pre>class java.util.ArrayList
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5]
class java.util.HashSet
[2, 4, 9, 8, 6, 1, 3, 7, 5, 0]</pre>
</div>
<p>If the <span class="c">List</span> is the first operand, groovy assumes you want to treat the following operand as a <span class="c">List</span> as well, and it just tacks the values onto the end.  But when the <span class="c">Set</span> is first, groovy first converts the second argument into a <span class="c">Set</span> as well before doing its addition.  This removes all but unique elements from it before performing the addition.</p>
<div class="codeHeader">Set/List subtraction</div>
<div class="code">
<pre>Set mySet = [1,3,5]

List myList = [0,1,2,3,4,0,1,2,3,4,5,6,7,8,9]

def subtraction = myList - mySet
println subtraction.class
println subtraction

subtraction = mySet - myList
println subtraction.class
println subtraction</pre>
</div>
<p>We should again see the automatic type conversion as in the above examples depending on which type is the first operand.  In the results below, you can see that all elements within the set were removed from the list (there are no 1&#8217;s, 3&#8217;s, or 5&#8217;s).  The second subtraction results in 0 elements, because the <span="c">List</span> (which is converted to a <span="c">Set</span>) being subtracted contains 1, 3, and 5, so all are removed from the original <span="c">Set</span>.</p>
<div class="windows-cmd">
<pre>class java.util.ArrayList
[0, 2, 4, 0, 2, 4, 6, 7, 8, 9]
class java.util.HashSet
[]</pre>
</div>
<p>Good stuff.  This is just another example of how groovy does away with a lot of the annoying things you have to do with java.</p>
<div class="sidenote">When groovy comes across an operator like &#8220;-&#8221; or &#8220;+&#8221;, it looks for a method on the left operand called either &#8220;plus&#8221; or &#8220;minus&#8221;.  So in the above examples, <span class="c">mySet - myList</span> is the same as <span class="c">mySet.minus(myList)</span>.</div>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2008/03/26/groovy-collection-comparison-is-easy/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Philosophical ramblings on reverse engineering the human brain</title>
		<link>http://weblog.dangertree.net/2008/01/07/philosophical-ramblings-on-reverse-engineering-the-human-brain/</link>
		<comments>http://weblog.dangertree.net/2008/01/07/philosophical-ramblings-on-reverse-engineering-the-human-brain/#comments</comments>
		<pubDate>Mon, 07 Jan 2008 15:16:05 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[rambling]]></category>

		<category><![CDATA[intelligence]]></category>

		<category><![CDATA[brain]]></category>

		<category><![CDATA[singularity]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2008/01/07/philosophical-ramblings-on-reverse-engineering-the-human-brain/</guid>
		<description><![CDATA[I was going through my bedstand last night, and I found a yellow notebook.  It contained the following:

As patterns from all Focal Points are received, save them and emit a random prediction pattern along action pathways.  Search for reaction pattern changes in response to predictions and adjust predictions to better fit incoming patterns.
The [...]]]></description>
			<content:encoded><![CDATA[<p>I was going through my bedstand last night, and I found a yellow notebook.  It contained the following:</p>
<div class="quote">
As patterns from all <em>Focal Points</em> are received, save them and emit a random prediction pattern along action pathways.  Search for reaction pattern changes in response to predictions and adjust predictions to better fit incoming patterns.</p>
<p>The <em><u>unconscious</u></em> is a background service that is constantly on, even when asleep.  It is extremely fast and can pull up millions of memories very quickly.</p>
<p>The <em><u>conscious mind</u></em> is an enormous engine that predicts the incoming input patterns by always keeping the most similar patterns within memory to compare to incoming patterns.</p>
<p>The <em><u>Driver</u></em> is an entity that can take control of the conscious and unconscious processes.  It can command the conscious to predict incoming memory patterns in different ways, or even ignore processing the input patterns in order to pursue a train of predictions into a completely imaginary reality.</p>
<p>The filtered stack of memory patterns that the conscious mind processes would look like a landscape if visualized.
</p></div>
<p>I was thinking of <em>&#8220;Focal Points&#8221;</em> as any inputs into a system.  For humans, they would be our senses, but for a computer system, it could be any number of inputs.  My main point was that intelligence is all about near-instantaneous pattern recognition, and the way our neocortex stores our memories allows our unconscious mind to be touching millions of stored patterns at once.  Someday we&#8217;ll be able to replicate this storage/retrieval algorithm, enabling a processor to have data access to many data locations at once.  That is the way our brain works.  There are multiple parallel asynchronous retrievals occurring, yet slower than a computer processor retrieves data synchronously.  But this benefits pattern recognition greatly because of the breadth of incoming data.</p>
<p>This is what happens when you read <a href="http://www.amazon.com/Singularity-Near-Humans-Transcend-Biology/dp/0143037889/">The Singularity is Near</a> and <a href="http://www.amazon.com/Singularity-Near-Humans-Transcend-Biology/dp/0143037889/">On Intelligence</a> simultaneously.  I continue to have a deep fascination for the human brain and software, and I believe that we will eventually crack the intelligence algorithm.  I just wish I had more time to pursue such <em>trivial</em> pursuits.  But the individual development of my children&#8217;s brains is more important than working toward the singularity at this point in my life.  </p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2008/01/07/philosophical-ramblings-on-reverse-engineering-the-human-brain/feed/</wfw:commentRss>
		</item>
		<item>
		<title>TDD Training</title>
		<link>http://weblog.dangertree.net/2007/10/30/tfd-training/</link>
		<comments>http://weblog.dangertree.net/2007/10/30/tfd-training/#comments</comments>
		<pubDate>Tue, 30 Oct 2007 17:22:47 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[agile]]></category>

		<category><![CDATA[design]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2007/10/30/tfd-training/</guid>
		<description><![CDATA[

This week I&#8217;m attending Brian Button&#8217;s course on Test Driven Development.  As someone who has considered himself an agile programmer for a while now, I&#8217;m finding myself more and more enlightened by the core techniques of Martin Fowler&#8217;s book, Refactoring.  It is one of the texts of this course, and I can&#8217;t believe [...]]]></description>
			<content:encoded><![CDATA[<div class="img-float-right">
<img src='http://weblog.dangertree.net/wp-content/uploads/2007/10/refactoringbook.gif' alt='Refactoring - Martin Fowler' /></div>
<p>This week I&#8217;m attending <a href="http://www.agileprogrammer.com/oneagilecoder/">Brian Button&#8217;s</a> course on <strong>Test Driven Development</strong>.  As someone who has considered himself an agile programmer for a while now, I&#8217;m finding myself more and more enlightened by the core techniques of Martin Fowler&#8217;s book, <u><strong>Refactoring</strong></u>.  It is one of the texts of this course, and I can&#8217;t believe I&#8217;ve been coding without this book for so long.</p>
<p>At almost every job I&#8217;ve worked here in St. Louis, I&#8217;ve seen this book on someone&#8217;s desk or in a library area, but I&#8217;ve never bothered to pick it up.  But after this course, it will be a staple of my (annoyingly ostentatious) desktop bookshelf.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2007/10/30/tfd-training/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Create a new email in MS Outlook with Launchy</title>
		<link>http://weblog.dangertree.net/2007/09/26/create-a-new-email-in-ms-outlook-with-launchy/</link>
		<comments>http://weblog.dangertree.net/2007/09/26/create-a-new-email-in-ms-outlook-with-launchy/#comments</comments>
		<pubDate>Wed, 26 Sep 2007 18:23:31 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[launchy]]></category>

		<category><![CDATA[cool]]></category>

		<category><![CDATA[windows]]></category>

		<category><![CDATA[productivity]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2007/09/26/create-a-new-email-in-ms-outlook-with-launchy/</guid>
		<description><![CDATA[I realized recently that I was never looking at my Outlook application when I wanted to start a new email to someone, and I had no quick-and-easy way to launch a new email message.  So after a quick search Google search, I found this site with instructions on how to do many things in [...]]]></description>
			<content:encoded><![CDATA[<p>I realized recently that I was never looking at my Outlook application when I wanted to start a new email to someone, and I had no quick-and-easy way to launch a new email message.  So after a quick search Google <a href="http://www.google.com/search?q=outlook+new+email+from+command+line&#038;hl=en">search</a>, I found <a href="http://www.outlook-tips.net/howto/commandlines.htm">this site</a> with instructions on how to do many things in Outlook from the command line.  And it was super easy to whip up a quick batch script that could do exactly what I wanted, then put it in my &#8216;bin&#8217; directory where I keep all my other Launchy scripts (<a href="http://weblog.dangertree.net/2007/06/12/using-launchy-and-batch-shortcuts-for-navigation/">as described in this post</a>).</p>
<div class="codeHeader">newMail.bat</div>
<div class="code">
&#8220;c:\Program Files\Microsoft Office\Office10\Outlook.exe&#8221; /c ipm.note
</div>
<p>Now to pop up a new Outlook email message, it&#8217;s as easy as typing &#8220;Alt-Space newmail&#8221;.  </p>
<p>Finding new uses for Launchy is wonderful.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2007/09/26/create-a-new-email-in-ms-outlook-with-launchy/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Mapping Java 5 enums with Hibernate</title>
		<link>http://weblog.dangertree.net/2007/09/23/mapping-java-5-enums-with-hibernate/</link>
		<comments>http://weblog.dangertree.net/2007/09/23/mapping-java-5-enums-with-hibernate/#comments</comments>
		<pubDate>Mon, 24 Sep 2007 03:13:45 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[hibernate]]></category>

		<category><![CDATA[data]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[java 5]]></category>

		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2007/09/23/mapping-java-5-enums-with-hibernate/</guid>
		<description><![CDATA[Hibernate is used to map java objects to a relational database.  Ideally, you would like your java object model to be as object-oriented as possible.  It is also nice to be able to use features like java 5 enums while coding the object model.  In this tutorial, I&#8217;ll share with you how [...]]]></description>
			<content:encoded><![CDATA[<p>Hibernate is used to map java objects to a relational database.  Ideally, you would like your java object model to be as object-oriented as possible.  It is also nice to be able to use features like <em>java 5 enums</em> while coding the object model.  In this tutorial, I&#8217;ll share with you how I ended up mapping a simple object model using java 5 enums into Hibernate.</p>
<div class="sidenote">I&#8217;ve found the best way to jumpstart yourself into using Hibernate is to go through the official <a href="http://www.hibernate.org/hib_docs/reference/en/html/tutorial.html">tutorial</a> on the Hibernate site.</div>
<h3>A Simple Example</h3>
<p>I have a Beer object that corresponds directly to a BEER table in a database.  The Beer object can wither be an &#8220;Ale&#8221; or a &#8220;Lager&#8221;, and there may be more types in the future.  So the database schema looks like this:</p>
<div class="codeHeader">Simple Beer schema</div>
<div class="code">
<pre>
+--------------------+
| BEER               |
+--------------------+           +----------------+
| NUMBER  | ID       |           | BEER_TYPE      |
| VARCHAR | BRAND    |           +----------------+
| NUMBER  | TYPE     | FK------- | NUMBER  | ID   |
| NUMBER  | VOLUME   |           | VARCHAR | NAME |
+--------------------+           +----------------+
</pre>
</div>
<p>It is pretty straightforward how to create a java class to represent this data.  Ideally, I would like to use a java 5 enum object to keep track of the beer type, so I use it within my data object to specify type:</p>
<div class="codeHeader">Beer Data Object</div>
<div class="code">
<pre>
public class Beer {
&nbsp;&nbsp;&nbsp;&nbsp;private BeerType type;
&nbsp;&nbsp;&nbsp;&nbsp;private String brand;
&nbsp;&nbsp;&nbsp;&nbsp;private double volume;

&nbsp;&nbsp;&nbsp;&nbsp;public BeerType getType() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return type;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public void setType(BeerType type) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.type = type;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public String getBrand() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return brand;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public void setBrand(String brand) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.brand = brand;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public double getVolume() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return volume;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public void setVolume(double volume) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.volume = volume;
&nbsp;&nbsp;&nbsp;&nbsp;}
}
</pre>
</div>
<p>The <span class="c">BeerType</span> enum will simply specify the type of beer for each <span class="c">Beer</span> object.  This enum is going to map directly to the <em>BEER_TYPE</em> table.  So I&#8217;ve given each beer type its own id through the private internal enum constructor.  There is an accessor method for hibernate to retrieve the id when it needs to do the mapping.</p>
<div class="codeHeader">BeerType enum</div>
<div class="code">
public enum BeerType {<br />
&nbsp;&nbsp;&nbsp;&nbsp;UNKNOWN(0), ALE(1), LAGER(2);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private int id;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private BeerType(int id) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.id = id;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public int getId() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return id;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>}
</p></div>
<p>One of the first things I found when I started searching the internet for ways to map Java 5 enums to a database using Hibernate was <a href="http://www.hibernate.org/272.html">this article</a> on the Hibernate page.  It shows an implementation of the Hibernate <span class="c"><a href="http://simoes.org/docs/hibernate-2.1/api/net/sf/hibernate/UserType.html">UserType</a></span> in a way that will allow an enum to be used within a hibernate key mapping.  So if I create a custom type definition in the key-mapping that uses the <span class="c">GenericEnumUserType</span> class as the <em>class</em>, and passes in the actual <span class="c">BeerType</span> enum classpath as a parameter, I can do the work to break out the enum details in the <span class="c">GenericEnumUserType</span> implementation.</p>
<div class="codeHeader">Hibernate key-mapping for Beer</div>
<div class="code">
<pre>&lt;hibernate-mapping&gt;
    &lt;typedef class=&quot;net.dangertree.GenericEnumUserType&quot; name=&quot;beerType&quot;&gt;
        &lt;param name=&quot;enumClassName&quot;&gt;net.dangertree.BeerType&lt;/param&gt;
        &lt;param name=&quot;identifierMethod&quot;&gt;getId&lt;/param&gt;
    &lt;/typedef&gt;

    &lt;class name=&quot;net.dangertree.Beer&quot; table=&quot;BEER&quot;&gt;
        &lt;id name=&quot;id&quot; type=&quot;int&quot; column=&quot;ID&quot;&gt;
            &lt;generator class=&quot;native&quot;/&gt;
        &lt;/id&gt;
        &lt;property name=&quot;type&quot; type=&quot;beerType&quot; column=&quot;TYPE&quot;/&gt;
        &lt;property name=&quot;brand&quot; type=&quot;string&quot; column=&quot;BRAND&quot;/&gt;
        &lt;property name=&quot;volumn&quot; type=&quot;double&quot; column=&quot;VOLUME&quot;/&gt;
    &lt;/class&gt;
&lt;/hibernate-mapping&gt;</pre>
</div>
<p>Here is the full code for the <span class="c">GenericEnumUserType</span> class that I used to help map my enums into Hibernate.  Reflection is used to find an &#8220;identifier&#8221; method in the enum that will get the id for each value.  I have specified in the type-def in my key mapping that I&#8217;m going to use the <span class="c">getId()</span> method of my enum to get an identifying attribute.  By default, the class will look for the inherent <span class="c">name</span> method of enum, but I&#8217;m using ids as my identifier.</p>
<p>The two method objects are grabbed and saved, then called in the null-safe setter and getter deeper within the Hibernate workings.</p>
<div class="strongpoint">This class implementation of <span class="c">UserType</span> is not exactly the same as any of those listings on the <a href="http://www.hibernate.org/272.html">hibernate article</a> I mentioned earlier.  I had to make several minor changes to get it working with this code.</div>
<div class="codeHeader"><a name="genericEnumUserType"></a>Generic Enum <span class="c">UserType</span> implementation</div>
<div class="code">
import org.hibernate.HibernateException;<br />
import org.hibernate.type.NullableType;<br />
import org.hibernate.type.TypeFactory;<br />
import org.hibernate.usertype.ParameterizedType;<br />
import org.hibernate.usertype.UserType;</p>
<p>import java.io.Serializable;<br />
import java.lang.reflect.Method;<br />
import java.sql.PreparedStatement;<br />
import java.sql.ResultSet;<br />
import java.sql.SQLException;<br />
import java.util.Properties;</p>
<p>public class GenericEnumUserType implements UserType, ParameterizedType {<br />
&nbsp;&nbsp;&nbsp;&nbsp;private static final String DEFAULT_IDENTIFIER_METHOD_NAME = “name”;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private static final String DEFAULT_VALUE_OF_METHOD_NAME = “valueOf”;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private Class enumClass;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private Class identifierType;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private Method identifierMethod;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private Method valueOfMethod;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private NullableType type;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private int[] sqlTypes;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public void setParameterValues(Properties parameters) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String enumClassName = parameters.getProperty(”enumClassName”);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;enumClass = Class.forName(enumClassName).asSubclass(Enum.class);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (ClassNotFoundException cfne) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new HibernateException(”Enum class not found”, cfne);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String identifierMethodName = parameters.getProperty(”identifierMethod”,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;DEFAULT_IDENTIFIER_METHOD_NAME);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;identifierMethod = enumClass.getMethod(identifierMethodName,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new Class[0]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;identifierType = identifierMethod.getReturnType();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new HibernateException(”Failed to obtain identifier method”,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;e);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type = (NullableType) TypeFactory.basic(identifierType.getName());</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (type == null)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new HibernateException(”Unsupported identifier type ”<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ identifierType.getName());</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sqlTypes = new int[] { type.sqlType() };</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String valueOfMethodName = parameters.getProperty(”valueOfMethod”,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;DEFAULT_VALUE_OF_METHOD_NAME);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;valueOfMethod = enumClass.getMethod(valueOfMethodName,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new Class[] { identifierType });<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new HibernateException(”Failed to obtain valueOf method”, e);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public Class returnedClass() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return enumClass;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public Object nullSafeGet(ResultSet rs, String[] names, Object owner)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throws HibernateException, SQLException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Object identifier = type.get(rs, names[0]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (rs.wasNull()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return valueOfMethod.invoke(enumClass, new Object[] { identifier });<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new HibernateException(”Exception while invoking ”<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ “valueOf method ‘” + valueOfMethod.getName() + “‘ of ”<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ ”enumeration class ‘” + enumClass + “‘”, e);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public void nullSafeSet(PreparedStatement st, Object value, int index)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throws HibernateException, SQLException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (value == null) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;st.setNull(index, type.sqlType());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Object identifier = identifierMethod.invoke(value,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new Object[0]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;type.set(st, identifier, index);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (Exception e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw new HibernateException(”Exception while invoking ”<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ “identifierMethod ‘” + identifierMethod.getName() + “‘ of ”<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+ ”enumeration class ‘” + enumClass + “‘”, e);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public int[] sqlTypes() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return sqlTypes;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public Object assemble(Serializable cached, Object owner)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throws HibernateException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return cached;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public Object deepCopy(Object value) throws HibernateException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return value;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public Serializable disassemble(Object value) throws HibernateException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return (Serializable) value;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public boolean equals(Object x, Object y) throws HibernateException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return x == y;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public int hashCode(Object x) throws HibernateException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return x.hashCode();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public boolean isMutable() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return false;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public Object replace(Object original, Object target, Object owner)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throws HibernateException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return original;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}
</p></div>
<p>Ok, there is only one problem now.  The <em>DEFAULT_VALUE_OF_METHOD_NAME</em> method is specified by default to be <em>valueOf</em>, and I have not provided a parameter to override that in the type-def.  So in order for my enum to match this, I need to add a <em>valueOf</em> method to my enum.  And when the <span class="c">nullSafeGet</span> method calls the &#8220;<em>valueOfMethod</em>&#8220;, it sends it an identifier as a parameter, so our <span class="c">valueOf</span> method needs to take an int id as a parameter.</p>
<div class="codeHeader">Modified BeerType enum</div>
<div class="code">
public enum BeerType {<br />
&nbsp;&nbsp;&nbsp;&nbsp;UNKNOWN(0), ALE(1), LAGER(2);</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private int id;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private BeerType(int id) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.id = id;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public int getId() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return id;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;public static BeerType valueOf(int id) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;switch (id) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 1: return ALE;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 2: return LAGER;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default: return UNKNOWN;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;<br />
}
</p></div>
<p>Now I have my data object, the enum it is using, my key-mapping, and an implementation of <span class="c">UserType</span> that provides a way to access the enum through a type-def element in the key-mapping.</p>
<p>It&#8217;s all working for me now!  Does anyone have any questions or comments?  This is the very first time that I have interacted with hibernate, so I&#8217;m a little bit shaky with the details (especially the <span class="c">UserType</span> implementation).</p>
<p><em>Edit: correction of mapping file pointed out by commenters.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2007/09/23/mapping-java-5-enums-with-hibernate/feed/</wfw:commentRss>
		</item>
		<item>
		<title>What I&#8217;m doing instead of blogging</title>
		<link>http://weblog.dangertree.net/2007/09/16/what-im-doing-instead-of-blogging/</link>
		<comments>http://weblog.dangertree.net/2007/09/16/what-im-doing-instead-of-blogging/#comments</comments>
		<pubDate>Sun, 16 Sep 2007 12:57:18 +0000</pubDate>
		<dc:creator>Matthew Taylor</dc:creator>
		
		<category><![CDATA[off topic]]></category>

		<guid isPermaLink="false">http://weblog.dangertree.net/2007/09/16/what-im-doing-instead-of-blogging/</guid>
		<description><![CDATA[I have not posted in awhile, and for good reason.  So here is a quick update on what is going on with me.
Changing jobs
I like the feeling of being an independent in this field right now, so I haven&#8217;t attached myself solely to one employment agency.  In fact, of the three jobs I [...]]]></description>
			<content:encoded><![CDATA[<p>I have not posted in awhile, and for good reason.  So here is a quick update on what is going on with me.</p>
<h3>Changing jobs</h3>
<p>I like the feeling of being an independent in this field right now, so I haven&#8217;t attached myself solely to one employment agency.  In fact, of the three jobs I have taken in the St. Louis area, they have all been through different agencies.  I&#8217;m sure that this has frustrated some of the recruiters in ways, but I&#8217;m still fulfilling my part of the deal and making them money.</p>
<p>My last position was really nice, but I was not in a place to get the experience I needed to further my career.  So I started another job at Monsanto about a month ago.  This job is very, very different than the previous one.  I can&#8217;t say &#8220;better&#8221; or &#8220;worse&#8221; at this point, but definitely different.  It will be harder, that&#8217;s for sure.</p>
<h3>Having kids</h3>
<p>My wife and I recently had our 2nd child, and I am have just finished two weeks of vacation to stay home and help out around the house while we adjust to this change.  It has been really nice, and I&#8217;ve been spending a lot of my free time helping to take care of our new baby girl.  Everything is going great with the baby, and our family feels like it&#8217;s filling out.</p>
<h3>Moonlighting</h3>
<p>Tripos, the first company I worked for in St. Louis after leaving the defense industry, recently contacted me to moonlight with them in my off-hours.  So I have been working directly for them under a 1099, providing around 10 hours a week to support the same project I was working on there before.  So far, it has been a really nice experience, although my time management skills are in constant need of sharpening.</p>
<p>So you might not expect me to update my blog very regularly for a little while.  I just have a lot of stuff going on in different areas of my life right now.  Thanks to all of you who are keeping up with me.</p>
]]></content:encoded>
			<wfw:commentRss>http://weblog.dangertree.net/2007/09/16/what-im-doing-instead-of-blogging/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
