<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Stuff I&#039;ve learned recently...</title>
	<atom:link href="http://kousenit.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://kousenit.wordpress.com</link>
	<description>I teach this stuff.  I didn&#039;t say I could do it.</description>
	<lastBuildDate>Thu, 16 May 2013 18:52:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='kousenit.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Stuff I&#039;ve learned recently...</title>
		<link>http://kousenit.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://kousenit.wordpress.com/osd.xml" title="Stuff I&#039;ve learned recently..." />
	<atom:link rel='hub' href='http://kousenit.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Getting Insight from Data: Baseball</title>
		<link>http://kousenit.wordpress.com/2012/10/24/getting-insight-from-data-baseball/</link>
		<comments>http://kousenit.wordpress.com/2012/10/24/getting-insight-from-data-baseball/#comments</comments>
		<pubDate>Wed, 24 Oct 2012 22:21:36 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Baseball]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=373</guid>
		<description><![CDATA[Big Data is cited by many prognosticators as a major growth area in computer science over the next decade. While definitions of Big Data abound, the basic idea is that data is being collected as such a rate and with such volume now that traditional ways of saving and analyzing it no longer suffice. (Neal [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=373&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Big Data is cited by many prognosticators as a major growth area in computer science over the next decade. While definitions of Big Data abound, the basic idea is that data is being collected as such a rate and with such volume now that traditional ways of saving and analyzing it no longer suffice.</p>
<p>(Neal Ford once told me about a bioengineering project that collects roughly 5 exabytes of data every few days, and as scientists they never want to throw anything away. Their simplest solution for storing it all may be to build a dedicated hard drive factory next door.)</p>
<p>The real issue, though, is not how much data you have. It&#8217;s what you do with it. How do you understand your situation when the data is voluminous, but may contain errors, omissions, and other problems?</p>
<p>This is not a new problem, and fortunately we have a great field of examples to use as a model. If you want to understand how to get insight from large amounts of data, look at baseball.</p>
<p>Even a brief summary of the history of sabermetrics (a term coined by Bill James himself, based on SABR &#8212; the Society for American Baseball Research) would go well beyond the scope of a simple blog post. If you&#8217;ve seen the <a href="http://www.imdb.com/title/tt1210166/">Moneyball</a> movie or <a href="http://www.amazon.com/Moneyball-The-Winning-Unfair-Game/dp/0739317741">read the book</a>, you&#8217;ve got the general idea. Suffice it to say that sabermetrics is an attempt to understand how to win baseball games by focusing on the data, rather than on conventional wisdom.</p>
<p>Some of the interesting observations made by the stats community include ideas that seem blindingly obvious but were ignored for years:</p>
<p>1. Outs are everything, so don&#8217;t give them away unnecessarily. Baseball doesn&#8217;t have a time limit, and you can&#8217;t stall or play a prevent defense. You keep playing until 27 outs are recorded.</p>
<p>2. That means if you steal at less than about a 70% success rate, don&#8217;t run. It doesn&#8217;t matter how many bases you steal if you&#8217;re giving up too many by getting caught.</p>
<p>3. Similarly, bunting is done way, way too often. Moving a runner over from first to second (or sometimes from second to third) isn&#8217;t worth giving away an out. Or, as the stat guys say, if you play for one run, that&#8217;s likely all you&#8217;ll get, and most of the time not even that.</p>
<p>4. Pitcher wins are highly dependent on elements outside the pitcher&#8217;s control, like runs scored by his offense or errors made by the defense. Wins are a lousy measure of pitcher skill. Frankly, ERA (earned run average) isn&#8217;t that much better, because there are many subjective judgements in there, too (try looking at the difference between earned and unearned runs sometime and the arbitrariness of it all will make your head spin).</p>
<p>5. RBIs are so dependent on where you are in the batting order that they&#8217;re a lousy measure of hitting skill. If you are a major leaguer and you bat fourth, fifth, or sixth, you&#8217;re going to get a lot of RBIs no matter what you do. That&#8217;s why OBP (on base percentage, which measures how often you avoid giving up an out) is far better correlated with wins.</p>
<p>Incidentally, that was one of themes of the Moneyball movie. The idea was to get the players to get on base as much as possible, placing a higher than normal value on walks. Since OBP was much more important to wins than RBIs, the Oakland A&#8217;s could replace stars that left by filling in their on-base contributions rather than worrying about runs batted in.</p>
<p>As it turned out, they placed too little emphasis on defense. In the movie they moved Scott Hatteberg to first base where he had no defensive skills at all just to keep his bat in the lineup. Nowadays they would care more about the defense they gave up.</p>
<p>Actually, the real theme of Moneyball was to identify players that were undervalued based on traditional metrics and use them to build a successful team cheaply. At the time, OBP was a market inefficiency.</p>
<p>Rather than go on, I want to mention that there&#8217;s a reason I&#8217;m writing this post today. Tonight is the first game of the <a href="http://mlb.mlb.com/mlb/ps/y2012/index.jsp?sv=1">World Series</a> between the Detroit Tigers and the San Francisco Giants, and from a sabermetric point of view it has all the elements of a potential classic.</p>
<p>I want to mention a couple baseball writers and what they&#8217;ve said about the upcoming series. First, Jonah Keri (author of <a href="http://www.amazon.com/Extra-2%25-Street-Strategies-Baseball/dp/0345517652/">The Extra 2%</a>) wrote a <a href="http://www.grantland.com/story/_/id/8545158/san-francisco-take-home-second-title-three-years">great preview article today</a> at Grantland discussing the Giants. Rany Jazayerli (a medical doctor cursed by following the Kansas City Royals) wrote <a href="http://www.grantland.com/story/_/id/8545610/why-justin-verlander-detroit-tigers-outlast-giants-win-world-series">a similar article</a> on the Tigers. Both are well worth reading.</p>
<p>My favorite writer of all, however, is <a href="http://www.joesheehan.com/">Joe Sheehan</a>. He&#8217;s brilliant, and controversial, and fascinating to follow on Twitter. He writes a newsletter that I&#8217;m very happy to subscribe to, and his World Series preview came out today. I hope he won&#8217;t mind if I quote from it a bit, just to demonstrate the difference between mindlessly quoting statistics and drawing true insight from them.</p>
<blockquote><p>The Tigers beat you by striking you out and not letting you exploit their poor defense.</p></blockquote>
<p>He builds up to this by showing how the strike-out rate of the Detroit pitching staff is second in the league, and that they exceeded the league record in total strikeouts (coming in second to the Rays, actually). He also points out that their defense is so bad (they are the worst defense ever to reach the World Series) that the high strike out numbers are partly padded by having to face more batters than they should have had to, given the bad defense.</p>
<blockquote><p>The Giants beat you by putting the ball in play and making you chase it.</p></blockquote>
<p>The Giants were last in MLB in home runs. There were second in batting average and fourth on OBP. They have a park that suppresses homers and they play accordingly. On the other hand, they have a very low strike out rate. By the stat called equivalent average, they were the third best offense in baseball despite never hitting home runs.</p>
<blockquote><p>As it turned out, the Tigers &#8212; after winning a weak division &#8212; caught two postseason opponents ill-equipped to take advantage of their poor defense.</p></blockquote>
<p>The A&#8217;s struck out a lot and the Yankees were almost entirely driven by homers. The Giants will be completely opposite.</p>
<p>There&#8217;s plenty more, but this is the flavor of the observations. Note that none of the articles I mentioned are full of statistics. There are few choice stats presented with the goal of making a clear argument. That&#8217;s insight.</p>
<p>By the way, most organizations in baseball know this. The conflict between the scouts and the stats guys demonstrated in Moneyball is largely over (with the great exception being the Kansas City Royals, who not coincidentally keep coming in last). There&#8217;s one major group who still doesn&#8217;t &#8220;get it&#8221;, though, and that&#8217;s the media.</p>
<p>I cannot fathom why the networks continually put &#8220;analysts&#8221; in the broadcast booth who are completely unaware of the last twenty years of baseball research. In fact, they often disdain anything learned from studying the game as tricks with statistics. The greatest irony (as mentioned by Joe Sheehan many times) is that no stats guy is anywhere near as wedded to a particular metric as the so-called &#8220;traditionalists&#8221; care about RBIs or pitcher wins. If you watch the game broadcasts, you&#8217;ll see meaningless statistic after meaningless statistic based on small sample size (batter A is 2 for 7 against pitcher B) paraded out as though it meant anything, completely ignoring what&#8217;s now viewed as truly important. </p>
<p>For example, you&#8217;re guaranteed tonight to hear tons about the Giants&#8217; &#8220;momentum&#8221; (which demonstrably doesn&#8217;t exist) or the effects of the Tigers&#8217; long layoff since winning the ALCS, neither of which matter at all. Instead, the real story is whether the Giants can put enough balls in play to take advantage of the Tigers&#8217; poor defense, or whether the Tigers&#8217; great strike-out pitchers can keep them from doing it. It&#8217;s also whether the Tigers&#8217; line up, which is dominated by a few stars, will be able to beat the Giants&#8217; pitching, which has relatively weak starters but lots of bullpen depth, and the excellent San Francisco defense.</p>
<p>I have no vested interest in either team. Frankly, if it wasn&#8217;t for what I learn by reading those writers and others like them, I probably wouldn&#8217;t care at all. Now I&#8217;m excited to watch the interplay of two diametrically contrasting styles. Even better, I&#8217;m looking forward to the snarky comments by the great writers I follow on Twitter during the games (nobody does snark like a good baseball writer).</p>
<p>Do I have a prediction? Please. I&#8217;m just happy the Yankees got swept. That almost, but not quite, made up for the disaster that was the Red Sox season. Still, one of the Red Sox owners claims part of the team&#8217;s problem was that they didn&#8217;t listen to Bill James enough, so that gives me hope for next year.</p>
<p>Also, I&#8217;m really looking forward to the articles written after each game, which will be beautiful demonstrations of how to make decisions based on insight rather than just quoting statistics as though they were significant in themselves. I&#8217;ll just have the mute button ready whenever Tim McCarver starts talking.</p>
<p>&#8212;-</p>
<p>Joe Sheehan&#8217;s Newsletter is sent via email. An annual subscription is available at <a href="http://joesheehanbaseball.blogspot.com">http://joesheehanbaseball.blogspot.com</a>.</p>
<p>Twitter handles:<br />
Joe Sheehan (<a href="http://twitter.com/joe_sheehan">@joe_sheehan</a>)<br />
Rany Jazayerli (<a href="http://twitter.com/jazayerli">@jazayerli</a>)<br />
Johan Keri (<a href="http://twitter.com/jonahkeri">@jonahkeri</a>)<br />
Keith Law (<a href="http://twitter.com/keithlaw">@keithlaw</a>)<br />
Joe Posnanski (<a href="http://twitter.com/JPosnanski">@JPosnanski</a>)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/373/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/373/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=373&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/10/24/getting-insight-from-data-baseball/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>My Review of Programming Grails</title>
		<link>http://kousenit.wordpress.com/2012/09/26/my-review-of-programming-grails/</link>
		<comments>http://kousenit.wordpress.com/2012/09/26/my-review-of-programming-grails/#comments</comments>
		<pubDate>Wed, 26 Sep 2012 04:57:09 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=371</guid>
		<description><![CDATA[Originally submitted at O&#8217;Reilly Best Practices for Experienced Grails Developers Programming Grails Excellent look under the hood of Grails By Ken Kousen from Marlborough, CT on 9/25/2012 &#160; 5out of 5 Pros: Accurate, Helpful examples, Easy to understand Best Uses: Intermediate, Expert Describe Yourself: Developer, Educator Yes, this &#8220;early access&#8221; edition is very early, but [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=371&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<div class="hreview">
<div class="item">
<p><a href="http://oreilly.com/product/0636920024750.do">Originally submitted at O&#8217;Reilly</a></p>
<div><img src="http://images.powerreviews.com/images_products/02/43/16561585_100.jpg" class="photo" align="left" style="margin:0 .5em 0 0;">
<p style="margin-top:0;">Best Practices for Experienced Grails Developers</p>
</div>
<p><a href="http://shop.oreilly.com/product/0636920024750.do" style="display:none;" class="url fn"><span class="fn">Programming Grails</span></a></div>
<p>
<p><strong class="summary">Excellent look under the hood of Grails</strong></p>
<div>By <strong>Ken Kousen</strong> from <strong>Marlborough, CT</strong> on <strong><abbr title="2012925T1200-0800" class="dtreviewed">9/25/2012</abbr></strong></div>
<p>
<div style="margin:.5em 0;height:15px;width:83px;background-image:url('http://images.powerreviews.com/images/stars_small.gif');background-position:0 -180px;" class="prStars prStarsSmall">&nbsp;</div>
</p>
<div style="display:none;"><span class="rating">5</span>out of 5</div>
<p><strong>Pros: </strong>Accurate, Helpful examples, Easy to understand</p>
<p><strong>Best Uses: </strong>Intermediate, Expert</p>
<p><strong>Describe Yourself: </strong>Developer, Educator</p>
<p style="margin-top:1em;" class="description">Yes, this &#8220;early access&#8221; edition is very early, but the content so far is fantastic. The Hibernate chapter is the best discussion of how Grails handles Hibernate anywhere, and Burt clearly discusses how and when to use the second-level cache.</p>
<p>If the book consisted of that chapter alone it would be worth the price, but the other available chapters are also great. I have every reason to believe this will be an outstanding book for experienced Grails developers.</p>
<p style="margin-top:.5em;">(<a href="http://www.powerreviews.com/legal/terms_of_use.html" rel="license">legalese</a>)</p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/371/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=371&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/09/26/my-review-of-programming-grails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>

		<media:content url="http://images.powerreviews.com/images_products/02/43/16561585_100.jpg" medium="image" />
	</item>
		<item>
		<title>Adding a license to source files</title>
		<link>http://kousenit.wordpress.com/2012/07/06/adding-a-license-to-source-files/</link>
		<comments>http://kousenit.wordpress.com/2012/07/06/adding-a-license-to-source-files/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 21:40:37 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=367</guid>
		<description><![CDATA[A few years ago I remember seeing a blog post by a person interviewing potential new developers. He said that when the prospect featured Java prominently on their resume, he would make sure to give them a programming test that would be easy to solve in a different language but hard in Java, just to [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=367&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A few years ago I remember seeing a blog post by a person interviewing potential new developers. He said that when the prospect featured Java prominently on their resume, he would make sure to give them a programming test that would be easy to solve in a different language but hard in Java, just to see how they handled it. He normally used some sort of file manipulation as an example, because Java makes that particularly challenging while scripting languages often make those problems simple.</p>
<p>About a week ago, someone contacted me about the source code from my book, <a href="http://manning.com/kousen">Making Java Groovy</a>. The source code is located at my GitHub repository, <a href="https://github.com/kousen/Making-Java-Groovy">https://github.com/kousen/Making-Java-Groovy</a>. The requester noted that I didn&#8217;t have any sort of license file on my code and wondered what the terms were.</p>
<p>Leaving aside the wonder that (1) somebody found the book code useful (ack! <a href="http://www.urbandictionary.com/define.php?term=humblebrag">humblebrag</a> alert!) and (2) he actually asked permission to use it, it occurred to me I really ought to have something in place for that eventuality. I asked my editor at Manning about it and she didn&#8217;t answer right away, so I interpreted that as freedom to do whatever I wanted. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>A friend on a mailing list suggested that <a href="http://www.apache.org/licenses/LICENSE-2.0">the Apache 2 license</a> is appropriate if I don&#8217;t care too much how the code is used (and I don&#8217;t), so I decided to add that license to each source file. That brings me, at long last, to the original subject of this post: how do I add a license statement to the top of a large number of source files nested in many subdirectories?</p>
<p>I thought I would solve the problem with the <code>eachFileRecurse</code> method that Groovy adds to Java&#8217;s <code>java.io.File</code> class. I quickly realized, though, that there were directories I wanted to skip, and that lead me to the <code>traverse</code> method, which takes a <code>Map</code> of parameters.</p>
<p>Here&#8217;s the result:</p>
<pre class="brush: groovy; title: ; notranslate">
import static groovy.io.FileType.*
import static groovy.io.FileVisitResult.*
String license = '''/* ===================================================
 * Copyright 2012 Kousen IT, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */
'''
dir = '/Users/kousen/mjg'
new File(dir).traverse(
    type       : FILES, 
    nameFilter : ~/.*(java|groovy)$/,
    preDir     : { if (it.name == '.metadata') return SKIP_SUBTREE }) { file -&gt;
    // only add license if not already there
    if (!file.text.contains(license)) {
        def source = file.text
        file.text = &quot;$license$source&quot;
    }
    assert file.text.contains(license)
}
</pre>
<p>I used static imports for the <code>FileType</code> and <code>FileVisitResult</code> classes. The <code>FILES</code> constant comes from <code>FileType</code>, and the <code>SKIP_SUBTREE</code> constant comes from <code>FileVisitResult</code>. The parameters I used return only files whose name ends in either &#8216;java&#8217; or &#8216;groovy&#8217; and aren&#8217;t in any directory tree including &#8216;.metadata&#8217;.</p>
<p>Ultimately everything is based on the <code>getText</code> and <code>setText</code> methods that the Groovy JDK adds to the <code>java.io.File</code> class. Both are called using the <code>text</code> property. The <code>getText</code> method returns all the existing source code, and the <code>setText</code> method acts as an alias for the <code>write</code> method, which automatically closes (and therefore flushes) the file when finished. I used a multiline string for the license and included the training carriage return, so writing the license followed by the source did the trick.</p>
<p>The documentation for these methods is, shall we say, a little thin. I therefore did what I normally do in these situations: I found the test case in the Groovy source distribution. The test in question is called <code>FileTest</code> and can be viewed in the Groovy GitHub repository <a href="https://github.com/groovy/groovy-core/blob/master/src/test/groovy/FileTest.groovy">here</a>. The test cases showed how to use all of the methods, including <code>traverse</code>, so it was just a question of looking for the right example.</p>
<p>(Incidentally, one of the less publicized but really sweet features of GitHub is the code browser. Just find the project you want and dig into the directories until you find a file, and then GitHub provides syntax highlighting and everything. It&#8217;s a great, great feature, especially if you don&#8217;t want to clone the source of every project you care about onto your own local disk.)</p>
<p>Since I hadn&#8217;t known about the <code>traverse</code> method ahead of time, and I messed up the regular expressions for a while (sigh), solving the problem took longer than I expected. Still, it&#8217;s hard to beat a solution that takes less than a dozen lines. Hopefully someone else will find this helpful as well. And regarding the job interview situation described above, to paraphrase <a href="http://en.wikipedia.org/wiki/Let_It_Be_(film)">John Lennon in the rooftop concert at the end of <em>Let It Be</em></a>, on behalf of Groovy and myself, I hope I passed the audition.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/367/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/367/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=367&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/07/06/adding-a-license-to-source-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>(dc..bos): Train Stations as a Groovy Range</title>
		<link>http://kousenit.wordpress.com/2012/06/16/dc-bos-train-stations-as-a-groovy-range/</link>
		<comments>http://kousenit.wordpress.com/2012/06/16/dc-bos-train-stations-as-a-groovy-range/#comments</comments>
		<pubDate>Sat, 16 Jun 2012 18:16:35 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=357</guid>
		<description><![CDATA[I&#8217;ve been working on a presentation about interesting features in Groovy, and I came up with an example that I like but is probably too long to do in the available time, so I thought I&#8217;d show it here. The idea is to illustrate how any class can be made into a Groovy range by [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=357&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been working on a presentation about interesting features in Groovy, and I came up with an example that I like but is probably too long to do in the available time, so I thought I&#8217;d show it here. The idea is to illustrate how any class can be made into a Groovy range by implementing the right methods.</p>
<p>Actually, my larger theme is that understanding Groovy (and the Groovy JDK in particular) is helped considerably by thinking about operator overloading. I don&#8217;t do a lot of operator overloading in my own code (present example excepted), but it appears all over the place in the Groovy library. I find it helps Java developers understand Groovy better if they know that whenever they see any operator, they should mentally convert it to a method. For example, + is the <code>plus</code> method, &#8211; is <code>minus</code>, and, better yet, [...] is <code>getAt</code> or <code>putAt</code> and even <code>as</code> is really <code>asType</code>.</p>
<p>This helps Java devs understand that by reading the groovydocs for <code>String</code>, they realize they can do things like:</p>
<pre class="brush: groovy; title: ; notranslate">
String s = 'this is a string'
assert 'this' == s[0..3]
assert 'ing' == s[-3..-1]
assert 'gni' == s[-1..-3]
assert 'thisisastring' == s[0..3, 5..6, 8, -6..-1]
assert 'th is a string' == s - 'is'
</pre>
<p>and so on.</p>
<p>A groovy range is simply two values separated by a pair of dots, as shown in the previous example. Many classes can be used in a range, as in::</p>
<pre class="brush: groovy; title: ; notranslate">
assert [1, 2, 3, 4, 5] == 1..5
assert ['a', 'b', 'c'] == 'a'..'c'
Date now = new Date()
Date then = now + 2
assert ['Jun 16', 'Jun 17', 'Jun 18'] == (now..then)*.format('MMM dd')
</pre>
<p>(Adjust the last one based on when you run the script, of course. And how cool is it that the Groovy JDK adds a <code>format</code> method to the <code>Date</code> class?)</p>
<p>As the most excellent book <a href="http://manning.com/koenig2">Groovy in Action</a> points out (2nd edition available through the Manning Early Access Program), any class can be used in a range if it:</p>
<ul>
<li>implements the <code>java.util.Comparable</code> interface</li>
<li>has a <code>next</code> method</li>
<li>has a <code>previous</code> method</li>
</ul>
<p>That&#8217;s all you need. I wanted to show an example of this, and based on all my traveling I decided to use train stations. Here&#8217;s my first pass at it:</p>
<pre class="brush: groovy; title: ; notranslate">
class Station implements Comparable&lt;Station&gt; {
    String name
    Station next
    Station previous
    int position
    
    Station next() { next }
    Station previous() { previous }
    
    int compareTo(Station s) {
        this.position - s.position
    }
    String toString() { name }
}
</pre>
<p>My <code>Station</code> class is really a node in a doubly-linked list. It has a <code>name</code> and pointers to the next station and the previous station. To make the class implement <code>Comparable</code>, I decided to assign each station an integer position as I added it to a track.</p>
<p>My next step was to use put stations together. At first I was going to use an <code>addStation</code> method, and then I realized that&#8217;s really what the <code>plus</code> method was all about. So instead I did this:</p>
<pre class="brush: groovy; title: ; notranslate">
    Station plus(Station s) {
       s.position = ++position
       s.previous = this
       this.next = s
       return s 
    }
</pre>
<p>Here&#8217;s a script using the <code>Station</code> class:</p>
<pre class="brush: groovy; title: ; notranslate">
Station dc = new Station(name:'DC')
Station phl = new Station(name:'PHL')
Station nyc = new Station(name:'NYC')
Station bos = new Station(name:'BOS')

// operator overloading to make a route:
dc + phl + nyc + bos

// Stations are a range in each direction:
def northBound = (dc..bos)*.name
def southBound = (bos..dc)*.name

assert northBound == ['DC', 'PHL', 'NYC', 'BOS']
assert southBound == ['BOS', 'NYC', 'PHL', 'DC']
</pre>
<p>That&#8217;s all there is to it. I could easily add a <code>minus</code> method to <code>Station</code> in order to remove a node, and if I ever have to use this class in a real system I probably will. The <code>position</code> value is only used for comparison, so the actual number doesn&#8217;t matter, but I can imagine that if I have to add and remove lots of stations I&#8217;ll need some way to make that more rigorous. I also can&#8217;t escape the feeling that a better design would involve a <code>Track</code> class to hold the resulting route, but I didn&#8217;t need it for this simple demonstration.</p>
<p>Finally, those of us who occasionally travel the Acela route up and down the northeast corridor know that I left out a lot of stations, but I suppose I can dream that someday our trains will be in the same class (no pun intended) as their European or Asian counterparts. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>(Obligatory marketing: My book <a href="http://manning.com/kousen">Making Java Groovy</a>, also available through the Manning Early Access Program, just went out for its 2/3rds review. I hope to be &#8220;text complete&#8221; by the end of the summer, for a dead treeware release just in time for the holiday gift-giving season.)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/357/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/357/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=357&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/06/16/dc-bos-train-stations-as-a-groovy-range/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>Password authentication using Groovy</title>
		<link>http://kousenit.wordpress.com/2012/06/07/password-authentication-using-groovy/</link>
		<comments>http://kousenit.wordpress.com/2012/06/07/password-authentication-using-groovy/#comments</comments>
		<pubDate>Fri, 08 Jun 2012 02:29:10 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=352</guid>
		<description><![CDATA[This week I was at a client site that was about as locked down as any I&#8217;ve seen. Personally I find that incredibly short-sighted on the part of the company, but it&#8217;s always easier to say no, I suppose. While it was annoying enough to set up a browser to surf the web, that&#8217;s not [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=352&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>This week I was at a client site that was about as locked down as any I&#8217;ve seen. Personally I find that incredibly short-sighted on the part of the company, but it&#8217;s always easier to say no, I suppose.</p>
<p>While it was annoying enough to set up a browser to surf the web, that&#8217;s not sufficient to access remote sites programmatically. For example, the client does a daily download of exchange rate data from a central site, which they process and store in a local db. I wanted to demonstrate that using Groovy.</p>
<p>Normally, to use a proxy I set the host and port on the command line. I&#8217;ve done that in Java (and Groovy) many times:</p>
<p><code>groovy -DproxyHost=10.x.x.x -DproxyPort=8080 myscript.groovy</code></p>
<p>Most of the time, that&#8217;s all you need. In this particular case, however, I also needed to submit a username and a password for authentication on the proxy server.</p>
<p>There are several sites that show you how to do that in Java. <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-auth.html">Here&#8217;s one of them</a>, and it shows that you need to extend the <code>java.net.Authenticator</code> class and override the <code>getPasswordAuthentication</code> method. Here&#8217;s an example in Java:</p>
<pre class="brush: java; title: ; notranslate">
import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(&quot;username&quot;,&quot;password&quot;.toCharArray());
    }
}
</pre>
<p>Then, in your program, set the new authenticator as the default.</p>
<pre class="brush: java; title: ; notranslate">
Authenticator.setDefault(new MyAuthenticator());
</pre>
<p>and you&#8217;re good to go.</p>
<p>Of course, I couldn&#8217;t leave it at that. I was teaching a Groovy class anyway, so I wanted to make the solution groovier. Here&#8217;s what I ultimately used:</p>
<pre class="brush: groovy; title: ; notranslate">
Authenticator.default = {
    new PasswordAuthentication('username','password' as char[])
} as Authenticator
</pre>
<p>I switched from using the <code>setDefault</code> method to setting a property, and coerced a closure with the required method into the proper class. Since the authentication mechanism only calls the <code>getPasswordAuthentication</code> method, I can use the single closure as the implementation. Normally I use closure coercion for interfaces, and then generally if they only have a single method, but it was too easy in this case to ignore.</p>
<p>Besides, showing the simplicity of the Groovy solution made the demo a teachable moment, which at least tried to make some lemonade out of the paranoid security lemons. My favorite part was how I hard-wired both the username and password directly into the script, in clear text no less. I could have found a way around that, but I was on a guest account anyway and it felt nicely subversive to do so.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/352/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/352/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=352&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/06/07/password-authentication-using-groovy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>From now on, I&#8217;m calling it GroovyString</title>
		<link>http://kousenit.wordpress.com/2012/05/09/from-now-on-im-calling-it-groovystring/</link>
		<comments>http://kousenit.wordpress.com/2012/05/09/from-now-on-im-calling-it-groovystring/#comments</comments>
		<pubDate>Wed, 09 May 2012 05:18:30 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=346</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of introductory Groovy presentations lately, and an issue keeps coming up that I feel I have to address. I&#8217;ve had to think hard about how to do this, though, because I don&#8217;t want to be misunderstood. I&#8217;m probably going to fumble it a bit, so please forgive me if I [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=346&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of introductory Groovy presentations lately, and an issue keeps coming up that I feel I have to address. I&#8217;ve had to think hard about how to do this, though, because I don&#8217;t want to be misunderstood. I&#8217;m probably going to fumble it a bit, so please forgive me if I ramble.</p>
<p>Lately there have been several episodes in the IT industry of boys behaving badly. <a href="http://www.motherjones.com/media/2012/04/silicon-valley-brogrammer-culture-sexist-sxsw">A recent article in Mother Jones</a> has a good summary. In short, a few guys in this industry have had a tendency to do and say things that have been particularly insensitive to women, for a variety of reasons ranging from simple foolishness to (potentially) outright bias.</p>
<p>Maybe this isn&#8217;t terribly surprising. After all, geeks aren&#8217;t always the most agile of social butterflies, and one of the downsides of getting guys together in groups is that the collective IQ tends to be lower than the individual ones. Still, I don&#8217;t want to rant about that, especially since lamenting poor behavior is almost as much of a cliche as the behavior itself.</p>
<p>Instead, I want to focus on the Groovy programming language, and a decision made during its early formation that could easily have been avoided if more women developers had been available.</p>
<p>As anyone who works with Groovy knows, the language has two types of strings. One uses single-quotes (<code>'this is a string'</code>) and represents and instance of regular old <code>java.lang.String</code>. The other uses double-quotes (<code>"this is a string with a ${variable}"</code>), and allows for variables to be interpolated into it. The latter is a really useful class and comes up all the time.</p>
<p>By all the standard conventions, the class representing double-quoted strings should be called <code>GroovyString</code>. There are thirty or forty different classes in <a href="http://groovy.codehaus.org/gapi/">the Groovy API</a> that start with the word Groovy, including such common classes as <code>GroovyObject</code>, <code>GroovyShell</code>, <code>GroovyServlet</code>, and <code>GroovyTestCase</code>. A <code>GroovyString</code> class would feel right at home there.</p>
<p>Unfortunately, though, the original development team decided to call the class representing double-quoted strings <code>GString</code>, because they thought it was funny. Even worse, since you substitute values into it using a $, the inevitable follow-up joke is that you do string interpolation by &#8220;putting a dollar in a GString&#8221;.</p>
<p>Now, I&#8217;m sure no malice was intended at the time. It was a joke, and I chuckled the first time I heard it too.  So have many women I know when they first hear it. It&#8217;s actually a pretty clever joke.</p>
<p>But that doesn&#8217;t mean a name like that belongs in the standard library.</p>
<p>I think of it this way. The name of that class is yet one more reason why we need more women in this field. I&#8217;m sure that if a woman had been part of the core Groovy team at the time, she would have said something like, &#8220;ha ha, very funny, guys, but let&#8217;s not hard-wire that gag into the standard library, okay? You know, the same library that&#8217;s going to be used by every Groovy developer ever?&#8221; I fully expect that the rest of the team would have thought about it and almost certainly (if sheepishly) agreed. After all, it&#8217;s the kind of joke that&#8217;s funny once, and only for a few minutes. After that it&#8217;s mostly a nuisance. It&#8217;s hard enough to get a language named Groovy taken seriously by the Fortune 500 without going there, too.</p>
<p>Please don&#8217;t get me wrong, though. I&#8217;m not blaming or condemning anybody. That&#8217;s the sort of gag that comes up all the time. The mistake was making it part of the standard. Clearly there wasn&#8217;t a woman available at the time to provide some perspective.</p>
<p>I also draw a strong distinction between silly mistakes and outright bias. Everybody makes mistakes. I make them all the time. I try not to say anything offensive in class (or in life), partly because I really do try to respect people different from myself, and partly because I&#8217;m pretty much of a coward and don&#8217;t want to get in trouble. I certainly don&#8217;t want to make anyone uncomfortable for no good reason.</p>
<p>Oversensitivity leads to its own problems, too. I was an undergrad at MIT back in the 80&#8242;s. Despite the popular image of the place, the actual male/female ratio there was about 55%/45%, which wasn&#8217;t all that bad despite my complaints at the time. (The women there used to joke that the ratio of &#8220;acceptable&#8221; men to women was closer to 50/50.) The women at MIT tended to be pretty strong personalities, too, which I always thought was a good thing. I&#8217;ve always welcomed the company of women I could take seriously, or men too for that matter. The problem was that like so many academic environments, MIT had a marked tendency to overreact to any accusation of bias. Once someone complained of bias, rationality went out the window and any hope of getting to the actual truth was completely lost.</p>
<p>By the way, I believe this is partly what happened in the late 80&#8242;s and early 90&#8242;s, when oversensitivity to bias was labeled &#8220;political correctness&#8221; and summarily dismissed. I think we&#8217;re still paying the price for that.</p>
<p>That&#8217;s really unfortunate, too, because every woman I&#8217;ve ever met, without exception, has a story to tell that qualifies as bias or even harassment by any reasonable definition. Sometimes all you have to do is ask to hear stories that will make you shudder. Overreactions desensitize people against actual injustices that should cause outrage.</p>
<p>I don&#8217;t think the Groovy class in question qualifies on that scale. It&#8217;s a mistake, in my opinion, and a natural result of having too few women in the field. I&#8217;m not calling for a movement to rename the class or criticize anyone who uses the established name. But, then again, I&#8217;m not a woman. It&#8217;s entirely possible I don&#8217;t &#8220;get it&#8221;.</p>
<p>As a result, from now on I&#8217;m going to call double-quoted strings <code>GroovyString</code>s. It&#8217;s easy enough for me to do, and while it may not change anything, hopefully it will make some women developers feel slightly more welcome. If you want to join me, great, but if not, that&#8217;s fine too. I&#8217;ve made my decision, though, and hopefully this post will make my reasons clear.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/346/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=346&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/05/09/from-now-on-im-calling-it-groovystring/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing json output from a groovlet</title>
		<link>http://kousenit.wordpress.com/2012/03/06/writing-json-output-from-a-groovlet/</link>
		<comments>http://kousenit.wordpress.com/2012/03/06/writing-json-output-from-a-groovlet/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 07:08:40 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Baseball]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=341</guid>
		<description><![CDATA[I&#8217;ve been working with groovlets for years and recently had to dig into them in some detail, and that lead me to a situation I&#8217;m simultaneously very pleased and rather horrified about. The appeal of groovlets is both their simplicity and the environment in which they run. They&#8217;re simple because they&#8217;re just Groovy scripts. The [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=341&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><span id="more-341"></span>I&#8217;ve been working with groovlets for years and recently had to dig into them in some detail, and that lead me to a situation I&#8217;m simultaneously very pleased and rather horrified about. </p>
<p>The appeal of <a href="http://groovy.codehaus.org/Groovlets">groovlets</a> is both their simplicity and the environment in which they run. They&#8217;re simple because they&#8217;re just Groovy scripts. The convenience comes from the environment, which has a whole set of implicit variables available, like <code>params</code> for the request parameters, <code>headers</code> for the request headers, and the normal <code>request</code>, <code>response</code>, <code>session</code>, and <code>application</code> references.</p>
<p>The way groovlets work is from a combination of classes in Groovy called <code>groovy.servlet.GroovyServlet</code> and <code>groovy.lang.ServletBinding</code>. The <code>GroovyServlet</code> instantiates a <code>GroovyScriptEngine</code> and a <code>ServletBinding</code>, sets up the implicit variables, finds the groovlet, and then executes it. That&#8217;s why groovlets are deployed as simple scripts, in source code form, rather than as compiled classes. They&#8217;re loaded and executed by the <code>GroovyScriptEngine</code> inside the <code>GroovyServlet</code>.</p>
<p>Here&#8217;s my simple example, taken from my <a href="http://www.kousenit.com/groovybaseball">Groovy Baseball</a> application (less than 30 days to baseball season and counting). First I set up the <code>GroovyServlet</code> in the usual way.</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;servlet&gt;
      &lt;servlet-name&gt;GroovyServlet&lt;/servlet-name&gt;
      &lt;servlet-class&gt;groovy.servlet.GroovyServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;GroovyServlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;*.groovy&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
</pre>
<p>Here is the groovlet that I use in the application, called <code>GameService.groovy</code>:</p>
<pre class="brush: groovy; title: ; notranslate">
import beans.GameResult
import beans.Stadium
import service.GetGameData

def month = params.month
def day = params.day
def year = params.year

m = month.toInteger() &lt; 10 ? '0' + month : month
d = day.toInteger() &lt; 10 ? '0' + day : day
y = year

results = new GetGameData(month:m,day:d,year:y).games
response.contentType = 'text/xml'
html.games {
    results.each { g -&gt;
        game(
            outcome:&quot;$g.away $g.aScore, $g.home $g.hScore&quot;,
            lat:g.stadium.latitude,
            lng:g.stadium.longitude
        )
    }
}
</pre>
<p>The classes <code>GameResult</code>, <code>Stadium</code>, and <code>GetGameData</code> are internal to my application. For a given date, the application goes to <a href="http://gd2.mlb.com/components/game/mlb/">the corresponding games directory</a> maintained by Major League Baseball, determines which games were played that day, and downloads the box scores for each game in XML form. The main processor then extracts the results and creates a <code>GameResult</code>, which holds the home team name and score, the away team name and score, and a <code>Stadium</code> POGO that I use to hold the address and latitude and longitude.</p>
<p>The interesting part, or at least the part that lead to this blog post, is the last part of the script. The groovlet uses the built-in <code>MarkupBuilder</code>, called <code>html</code>, to write out the results in XML form.</p>
<p>Groovlets have had a built-in <code>MarkupBuilder</code> from the very beginning. The builder generates XML and writes the results directly to the output writer. Some of the early examples used the <code>MarkupBuilder</code> to write out a whole web page, but we&#8217;ve known that was a bad idea for years. The builder does have an excellent use case, though, which is to transform Java or Groovy objects into a format that can be read by other languages.</p>
<p>My web page builds a Google Map from the results which contains a dot, centered at the home stadium, for each game*.</p>
<p><em>*Real map geeks called this process &#8220;red dot fever&#8221;.</em></p>
<p>Here&#8217;s a picture from today, showing yesterday&#8217;s pre-season results.<br />
<a href="http://kousenit.files.wordpress.com/2012/03/groovy_baseball.png"><img src="http://kousenit.files.wordpress.com/2012/03/groovy_baseball.png?w=300&#038;h=278" alt="" title="groovy_baseball" width="300" height="278" class="aligncenter size-medium wp-image-342" /></a></p>
<p>Why write out my data in XML? The Google Maps API is written in JavaScript, and my result objects are in Groovy. JavaScript can&#8217;t read Groovy (or Java) objects, so I need a format to go between them, and hey, everybody can read and write strings. Even better, every language has an XML parsing and generation library. The <a href="http://www.w3.org/DOM/">Document Object Model</a> is a W3C specification, after all. The presence of the <code>MarkupBuilder</code> in groovlets makes the process of converting my Groovy objects into XML trivial, and the resulting XML elements are sufficiently simple that parsing them in the JavaScript code is very easy.</p>
<p>Still, if I was writing this application today, I&#8217;d probably prefer JavaScript Object Notation (JSON) instead. JSON objects are native JavaScript, so the JavaScript code can deal with them immediately without further parsing. The problem is that groovlets don&#8217;t have a built-in JSON builder.</p>
<p>At least, they didn&#8217;t used to. The <code>groovy.json.JsonBuilder</code> class was added in Groovy 1.8. That means I can just import the class into my groovlet, instantiate the builder, and write out the data in JSON format as easily as I currently do in XML format. I suddenly realized, however, that other people might like that capability, it might be easy to implement, and then &#8212; here&#8217;s the cool part &#8212; I could make my first actual commit to the Groovy code base.</p>
<p>I therefore dug into the implementation of <code>GroovyServlet</code> and <code>ServletBinding</code>, and discovered that all I would need to do is to modify about half a dozen lines of code in <code>ServletBinding.java</code> and update the corresponding test class.</p>
<p>The fact that the <code>ServletBinding</code> class is implemented in Java is significant (whoa, holy foreshadowing, Batman).</p>
<p>I was inspired by <a href="http://blog.bloidonia.com/post/17711808015/submitting-code-to-the-groovy-language">Tim Yates&#8217;s great blog post</a> showing exactly how to contribute to the language. I therefore forked the Groovy repository, created a local branch for my changes, added what I needed, and ran the test case. It took more work than I expected, but I finally got the tests to pass. As Tim suggested, I then <a href="https://jira.codehaus.org/browse/GROOVY-5341">raised a JIRA issue</a> and sent a pull request from my GitHub repository.</p>
<p>Today I got my reply, from Guillaume Laforge himself (the head of the Groovy project, and a very nice guy, as his comment will show). Here is what he said:</p>
<blockquote><p>&#8220;I had to modify the pull request a bit, as JsonBuilder being a Groovy class, it&#8217;s compiled after ServletBinding.<br />
So on a clean build, the build was broken because of that.<br />
I used a trick of &#8220;loading&#8221; the class lazily with this.getClass().getClassLoader().loadClass(&#8220;groovy.json.JsonBuilder&#8221;) which is not ideal – ideally, the Groovy build should compile with the joint compiler for the core sources.&#8221;</p></blockquote>
<p>In other words, two things happened:<br />
1. My cool addition of an implicit object called <code>json</code> of type <code>JsonBuilder</code> was accepted. (Whoo hoo!)<br />
2. I broke the freakin&#8217; build. Yup, the whole groovy core build failed, because of me. (Hangs head in shame)</p>
<p>Okay, I didn&#8217;t realize the Groovy core was built by compiling the Java sources first, and then the Groovy sources. I always use the joint compiler for my combined projects and never have an issue like that. So it&#8217;s not really my fault.</p>
<p>(Except I should have run the full build and discovered this. Sigh.)</p>
<p>In the end, though, Guillaume just fixed it, <em>thanked me for my contribution</em> (whoo hoo! again), and moved on. Hey, I&#8217;m now a contributor to the Groovy language! Combined with my one commit to Grails (thanks to Jeff Brown for that one), I now have contributed to the two open source projects I care most about. And this one I did all by myself (obviously, or I wouldn&#8217;t broken the stupid build &#8212; see what a mixed result this is?).</p>
<p>For the record, here&#8217;s what my groovlet would look like with the new <code>json</code> object available:</p>
<pre class="brush: groovy; title: ; notranslate">
// ...stuff from before...
response.contentType = 'application/json'
json.games {
    results.each { g -&gt;
        game(
            outcome:&quot;$g.away $g.aScore, $g.home $g.hScore&quot;,
            lat:g.stadium.latitude,
            lng:g.stadium.longitude
        )
    }
}
out &lt;&lt; json
</pre>
<p>Unlike the <code>MarkupBuilder</code>, <code>JsonBuilder</code> doesn&#8217;t automatically output its results, so I have to send it to the output writer myself.</p>
<p>I have some cool integration tests in the project, run by Gradle, but that&#8217;s another blog post. If you want to see the source code for the Groovy Baseball application, it&#8217;s part of the <a href="https://github.com/kousen/Making-Java-Groovy">GitHub repository for my book</a>. The application is in the ch02 directory (called &#8220;Groovy by Example&#8221; in <a href="http://manning.com/kousen">the book</a>) in the groovybaseball directory.</p>
<p>I&#8217;m not exactly sure which version of Groovy will have the <code>json</code> implicit object in groovlets. It&#8217;s part of the current build, which I suppose means Groovy 2.0. Anyway, feel free to use it, and if you do you can both thank me and laugh at me at the same time.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/341/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/341/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=341&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/03/06/writing-json-output-from-a-groovlet/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>

		<media:content url="http://kousenit.files.wordpress.com/2012/03/groovy_baseball.png?w=300" medium="image">
			<media:title type="html">groovy_baseball</media:title>
		</media:content>
	</item>
		<item>
		<title>Elvis carried away by spaceships</title>
		<link>http://kousenit.wordpress.com/2012/01/13/elvis-carried-away-by-spaceships/</link>
		<comments>http://kousenit.wordpress.com/2012/01/13/elvis-carried-away-by-spaceships/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 06:25:02 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=335</guid>
		<description><![CDATA[I love teaching Groovy to existing Java developers, because they have such a hard time holding back Tears Of Joy when they see how much easier life can be. Today, though, I did a quick demo that resulted in a line of Groovy that was so amusing I had to post it here. Consider a [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=335&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I love teaching Groovy to existing Java developers, because they have such a hard time holding back Tears Of Joy when they see how much easier life can be. Today, though, I did a quick demo that resulted in a line of Groovy that was so amusing I had to post it here.</p>
<p>Consider a trivial POGO (Plain Old Groovy Object) called <code>Course</code>:</p>
<pre class="brush: plain; title: ; notranslate">
class Course
    String name
    int days
    String toString() { &quot;($name,$days)&quot; }
}
</pre>
<p>The goal was to take a collection of courses and sort it by the number of days. That&#8217;s really easy in Groovy:</p>
<pre class="brush: groovy; title: ; notranslate">
def courses = [
    new Course(name:'Groovy',days:4),
    new Course(name:'Grails',days:3),
    new Course(name:'Spring',days:4),
    new Course(name:'Hibernate',days:3)
]

assert courses.toString() == '[(Groovy,4), (Grails,3), (Spring,4), (Hibernate,3)]'

courses.sort { it.days }

assert courses*.days == [3, 3, 4, 4]
</pre>
<p>The <code>sort</code> method in the <code>java.util.Collection</code> class is part of the Groovy JDK, meaning it&#8217;s one of the methods Groovy adds to the standard Java libraries. It takes a closure of either one or two arguments. In this case, I&#8217;m using the one-argument closure, which is used to select a property on which to base the sort. By specifying <code>it.days</code> in the closure, I&#8217;m telling the <code>sort</code> method to sort the courses based on their <code>days</code> property. Then I verify that the sort worked by checking that the courses are the right order, using the spread-dot operator to just look at the number of days.</p>
<p>In class the question that always comes up is, can I sort by days and then by name? In other words, if two courses have the same number of days, can I then sort by the <code>name</code> property?</p>
<p>That&#8217;s what the two-argument closure on the <code>sort</code> method is for. The two arguments are references to any pair of courses, and the closure should return a negative number, zero, or positive number according to whether the first course is less than, equal to, or greater than the second.</p>
<p>Here&#8217;s where things get amusing. The sort I want is:</p>
<pre class="brush: groovy; title: ; notranslate">
courses.sort { a,b -&gt;
    a.days &lt;=&gt; b.days ?: a.name &lt;=&gt; b.name
}

assert courses.toString() == '[(Grails,3), (Hibernate,3), (Groovy,4), (Spring,4)]'
</pre>
<p>The body of the closure on <code>sort</code> uses the spaceship operator &lt;=&gt;, which returns -1, 0, or 1 depending on whether the left side is less than, equal to, or greater than the right side. I use spaceship to compare the <code>days</code> properties. Then I add the Elvis operator ?: which means if the days comparison is not zero, use it, but otherwise use the following comparison, which uses another spaceship to compare by name.</p>
<p>It&#8217;s only after writing the code in class that one of the students pointed out that I had Elvis in between two spaceships, leading to the following observations:</p>
<ol>
<li>The spaceships are there to return Elvis to his home planet</li>
<li>It takes two <a href="http://www.smallartworks.ca/Gallery/J2/jupiter2.JPG">spaceships</a>, working in tandem, to carry Elvis away, in much the same way <a href="http://www.youtube.com/watch?v=rzcLQRXW6B0">two swallows can carry a coconut in tandem</a></li>
<li>Therefore, the Elvis being carried away must be the <a href="http://www.antisteez.com/wp-content/uploads/2009/10/fat-elvis.jpg">fat Elvis</a> from the 70s, rather than the <a href="http://hairstylesarea.com/hair-pic/HLIC/11fc6966ee56903bf40fee5c8f462800.jpg">thin, cool Elvis</a> from the 50s
</ol>
<p>Either way, after the sort is finished, Elvis has left the building.</p>
<p>Thank you, thank you very much.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/335/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=335&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/01/13/elvis-carried-away-by-spaceships/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy StubFor magic</title>
		<link>http://kousenit.wordpress.com/2012/01/02/groovy-stubfor-magic/</link>
		<comments>http://kousenit.wordpress.com/2012/01/02/groovy-stubfor-magic/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 20:17:30 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Baseball]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=331</guid>
		<description><![CDATA[I finished revising the testing chapter in Making Java Groovy (the MEAP should be updated this week), but before I leave it entirely, I want to mention a Groovy capability that is both cool and easy to use. Cool isn&#8217;t the right word, actually. I have to say that even after years of working with [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=331&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I finished revising the testing chapter in <a href="http://manning.com/kousen">Making Java Groovy</a> (the MEAP should be updated this week), but before I leave it entirely, I want to mention a Groovy capability that is both cool and easy to use. Cool isn&#8217;t the right word, actually. I have to say that even after years of working with Groovy, what I&#8217;m about to describe still feels like magic.</p>
<p>Here&#8217;s the issue: I have a class that uses one of Google&#8217;s web services, and I want to test my class even when I&#8217;m not online. That means I need to mock the dependency, which isn&#8217;t all that hard. The problem is that there&#8217;s no explicit way to get my mock object into my own service. Yet, with Groovy&#8217;s <code>MockFor</code> and <code>StubFor</code> classes, I can mock a dependency, even when it&#8217;s instantiated as a local variable inside my class.</p>
<p>Let me show you the code. I&#8217;ll start with a simple POGO called <code>Stadium</code>:</p>
<pre class="brush: groovy; title: ; notranslate">
class Stadium {
    String street
    String city
    String state
    double latitude
    double longitude
    
    String toString() {
        &quot;($street,$city,$state,$latitude,$longitude)&quot;
    }
}
</pre>
<p>I use this in my <a href="http://www.kousenit.com/groovybaseball">Groovy Baseball</a> application, which accesses MLB box scores online and displays the daily results on a Google Map. The <code>Stadium</code> class holds location data for an individual baseball stadium. When I use it, I set the street, city, and state and have the service compute latitude and longitude for me.</p>
<p>My <code>Geocoder</code> class is based on <a href="http://code.google.com/apis/maps/documentation/geocoding/">Google&#8217;s restful geocoding service</a>.</p>
<pre class="brush: groovy; title: ; notranslate">
class Geocoder {
    String base = 'http://maps.google.com/maps/api/geocode/xml?'
   
    void fillInLatLng(Stadium stadium) {
        String urlEncodedAddress =
                [stadium.street, stadium.city, stadium.state].collect {
                    URLEncoder.encode(it,'UTF-8')
                }.join(',+')
        String url = base + [sensor:false, address:urlEncodedAddress].collect { it }.join('&amp;')
        def response = new XmlSlurper().parse(url)
        String latitude = response.result.geometry.location.lat[0] ?: &quot;0.0&quot;
        String longitude = response.result.geometry.location.lng[0] ?: &quot;0.0&quot;
        stadium.latitude = latitude.toDouble()
        stadium.longitude = longitude.toDouble()
    }
}
</pre>
<p>First I take the stadium&#8217;s street, city, and state and add them to a list. Then the <code>collect</code> method is used to apply a closure to each element of the list, returning the transformed list. The closure runs each value through Java&#8217;s <code>URLEncoder</code>. In looking at <a href="http://code.google.com/apis/maps/documentation/geocoding/">the Google geocoder example</a>, I see that they separate the encoded street from the city and the city from the state using &#8220;<code>,+</code>&#8220;, so I do the same using the <code>join</code> method.</p>
<p>The Google geocoding service requires a parameter called <code>sensor</code>, which is true if the request is coming from a GPS-enabled device and false otherwise. In the Groovy map, I set its value to false, and set the value of the <code>address</code> parameter to the string from the previous line. The <code>collect</code> method on the map converts each entry to &#8220;<code>key=value</code>&#8220;, so joining with an ampersand and appending to the base value gives me the complete URL for the stadium.</p>
<p>Most restful web services try to provide their data in a format requested by the user. The content negotiation is usually done through an &#8220;Accept&#8221; header in the HTTP request, but in this case Google does something different. They support only XML and JSON output data, and let the user select which one they want through separate URLs. The base URL in the service above ends in <code>xml</code>. Google lists the JSON version as preferred, but that&#8217;s no doubt because they expect the requests to come through their own JavaScript API. I&#8217;m making the request using Groovy, and the <code>XmlSlurper</code> class makes parsing the result trivial.</p>
<p>(Since Groovy 1.8, the <code>JsonSlurper</code> class also makes parsing JSON trivial, and I have a version that does that, too, but the difference really isn&#8217;t significant here.)</p>
<p>The resulting block of XML that is returned by the service is fairly elaborate, but as you can see from my code, the data is nested through the elements <code>GeocodeResponse/result/geometry/location/lat</code> and <code>GeocodeResponse/result/geometry/location/lng</code>. After invoking the <code>parse</code> method (which returns the root element, <code>GeocodeResponse</code>), I just walk the tree to get the values I want.</p>
<p>I do have to protect myself somewhat. The Google service isn&#8217;t nearly as deterministic as I would have expected. Sometimes I get multiple locations when I search, so I added the zero index to make sure I always get the first one. Also, some time during the last year Google decided to start throttling their service. I have a script that uses the Geocoder for all 30 MLB stadiums, and unfortunately it runs too fast (!) for the Google limits. I know this because I start getting back null results if I don&#8217;t artificially introduce a delay. That&#8217;s why I put in the Elvis operator with the value 0.0 if I don&#8217;t get a good answer.</p>
<p>So much for the service; now I need a test. If I know I&#8217;m going to be online, I can write a simple integration test as follows:</p>
<pre class="brush: groovy; title: ; notranslate">
import static org.junit.Assert.*;
import org.junit.Test;

class GeocoderIntegrationTest {
    Geocoder geocoder = new Geocoder()
    
    @Test
    public void testFillInLatLng() {
        Stadium google = new Stadium(street:'1600 Ampitheatre Parkway',
            city:'Mountain View',state:'CA')
        geocoder.fillInLatLng(google)
        assertEquals(37.422, google.latitude, 0.01)
        assertEquals(-122.083, google.longitude, 0.01)
    }
}
</pre>
<p>I&#8217;m using Google headquarters, because that&#8217;s the example in the documentation. I invoke my Geocoder&#8217;s <code>fillInLatLng</code> method and check the results within a hundredth of a degree.</p>
<p>(The fact that the Google geocoder returns answers to seven decimal places is evidence that their developers have a sense of humor.)</p>
<p>Now, finally, after all that introduction, I reach the subject of this post. What happens if I&#8217;m not online? More to the point, how do I test the business logic in the <code>fillInLatLng</code> method without requiring access to Google?</p>
<p>What I need is a mock object, or, more precisely, a stub.</p>
<p>(A stub stands in for the external dependency, called a collaborator. A mock does the same, but also validates that the caller accesses the collaborator&#8217;s methods the right number of times in the right order. A stub helps test the caller, and a mock tests the interaction of the caller with the collaborator, sometimes called the protocol. Insert obligatory link to Martin Fowler&#8217;s &#8220;<a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks Aren&#8217;t Stubs</a>&#8221; post here.)</p>
<p>In my <code>Geocoder</code> class, the Google service is accessed through the <code>parse</code> method of the <code>XmlSlurper</code>. Even worse (from a testing point of view), the slurper is instantiated as a local variable inside my <code>fillInLatLng</code> method. There&#8217;s no way to isolate the dependency and set it from outside, either as an argument to the method, a setter in the class, a constructor argument, or whatever.</p>
<p>That&#8217;s where Groovy&#8217;s <code>StubFor</code> (or <code>MockFor</code>) class comes in. Let me show it in action. First, I&#8217;ll set up the answer I want.</p>
<pre class="brush: groovy; title: ; notranslate">
String xml = '''
    &lt;root&gt;&lt;result&gt;&lt;geometry&gt;
        &lt;location&gt;
            &lt;lat&gt;37.422&lt;/lat&gt;
            &lt;lng&gt;-122.083&lt;/lng&gt;
        &lt;/location&gt;
    &lt;/geometry&gt;&lt;/result&gt;&lt;/root&gt;'''
    
def correctRoot = new XmlSlurper().parseText(xml)
</pre>
<p>The xml variable has the right answer in it, nested appropriately. I use the <code>XmlSlurper</code> to parse the text and return the root of the tree I want.</p>
<p>Now I need a <code>Stadium</code> to update. I deliberately put in the wrong street, city, and state to make sure that I only get the right latitude and longitude if I insert the stub correctly.</p>
<pre class="brush: groovy; title: ; notranslate">
Stadium wrongStadium = new Stadium(
    street:'1313 Mockingbird Lane',
    city:'Mockingbird Heights',state:'CA')
</pre>
<p>(Yes, that&#8217;s a pretty obscure reference. For details, see <a href="http://en.wikipedia.org/wiki/Munsters">here</a>. And yes, I&#8217;m old. If you&#8217;re in the right age group, though, you now have the show&#8217;s theme song going through your head. Sorry.)</p>
<p>The next step is to create the stub and set the expectations.</p>
<pre class="brush: groovy; title: ; notranslate">
def stub = new StubFor(XmlSlurper)
stub.demand.parse { correctRoot }
</pre>
<p>The <code>StubFor</code> constructor takes a class as an argument and builds a stub around it. Then I use the <code>demand</code> property to say that when the <code>parse</code> method is called, my previously computed root is returned rather than actually going over the web and parsing anything.</p>
<p>To put the stub into play, invoke its <code>use</code> method, which takes a closure:</p>
<pre class="brush: groovy; title: ; notranslate">
stub.use {
    geocoder.fillInLatLng(wrongStadium)
}
</pre>
<p>That&#8217;s all there is to it. By the magic of Groovy metaprogramming, when I invoke the <code>parse</code> method of the <code>XmlSlurper</code> &#8212; <em>even when it&#8217;s instantiated as a local variable</em> &#8212; inside the <code>use</code> block the stub steps in and returns the expected value.</p>
<p>For completeness, here&#8217;s the complete test class:</p>
<pre class="brush: groovy; title: ; notranslate">
import static org.junit.Assert.*
import groovy.mock.interceptor.StubFor
import org.junit.Test

class GeocoderUnitTest {
    Geocoder geocoder = new Geocoder()
    
    @Test
    public void testFillInLatLng() {
        Stadium wrongStadium = new Stadium(
            street:'1313 Mockingbird Lane',
            city:'Mockingbird Heights',state:'CA')
        
        String xml = '''
        &lt;root&gt;&lt;result&gt;&lt;geometry&gt;
            &lt;location&gt;
                &lt;lat&gt;37.422&lt;/lat&gt;
                &lt;lng&gt;-122.083&lt;/lng&gt;
            &lt;/location&gt;
        &lt;/geometry&gt;&lt;/result&gt;&lt;/root&gt;'''
        
        def correctRoot = new XmlSlurper().parseText(xml)
        
        def stub = new StubFor(XmlSlurper)
        stub.demand.parse { correctRoot }
        
        stub.use {
            geocoder.fillInLatLng(wrongStadium)
        }
        assertEquals(37.422, wrongStadium.latitude, 0.01)
        assertEquals(-122.083, wrongStadium.longitude, 0.01)
    }
}
</pre>
<p>Since I&#8217;m only calling one method and only calling that method once, a stub is perfectly fine in this case. I could invoke the <code>verify</code> method if I wanted to (<code>MockFor</code> invokes <code>verify</code> automatically but <code>StubFor</code> doesn&#8217;t), but it doesn&#8217;t really add anything here.</p>
<p>There is one limitation to this technique, which only comes up when you&#8217;re doing the sort of Groovy/Java integration that is the subject of my book. You can only use <code>StubFor</code> or <code>MockFor</code> on a class written in Groovy.</p>
<p>All this code is available in the book&#8217;s Github repository at <a href="http://github.com/kousen/Making-Java-Groovy">http://github.com/kousen/Making-Java-Groovy</a>. This particular example is part of Chapter 5: Testing Java and Groovy.</p>
<p>As a final note, I should say that I dug into all of this, worked out all the details, and tried it in several examples. Then I finally did what I should have done all along, which was look it up in <a href="http://manning.com/koenig2">Groovy In Action</a>. Of course, there it was laid out in detail over about five pages. Someday that will stop happening to me. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/331/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/331/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=331&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2012/01/02/groovy-stubfor-magic/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
		<item>
		<title>log.rofl(&#8216;Fun with Groovy metaprogramming&#8217;)</title>
		<link>http://kousenit.wordpress.com/2011/12/13/log-roflfun-with-groovy-metaprogramming/</link>
		<comments>http://kousenit.wordpress.com/2011/12/13/log-roflfun-with-groovy-metaprogramming/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 04:03:42 +0000</pubDate>
		<dc:creator>Ken Kousen</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://kousenit.wordpress.com/?p=328</guid>
		<description><![CDATA[Recently I saw a post by someone (I think it was @jbarnette, but it was retweeted to me) suggesting that there should be some alternate log levels, like fyi, omg, or even wtf. I thought that was pretty funny, but then it occurred to me I could probably implement them using Groovy metaprogramming. As a [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=328&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Recently I saw a post by someone (I think it was <a href="http://twitter.com/jbarnette">@jbarnette</a>, but it was retweeted to me) suggesting that there should be some alternate log levels, like <code>fyi</code>, <code>omg</code>, or even <code>wtf</code>. I thought that was pretty funny, but then it occurred to me I could probably implement them using Groovy metaprogramming.</p>
<p>As a first attempt, consider the following simple example that adds the <code>fyi</code> and <code>omg</code> methods to <code>java.util.logging.Logger</code>:</p>
<pre class="brush: groovy; title: ; notranslate">
import java.util.logging.Logger

Logger.metaClass.fyi = { msg -&gt; delegate.info msg }
Logger.metaClass.omg = { msg -&gt; delegate.severe msg }
</pre>
<p>For those who haven&#8217;t used Groovy much, the <code>metaClass</code> property is associated with every class in Groovy, and allows you to add methods and properties to the class. Here the <code>fyi</code> method is defined by assigning it to a one-argument closure whose implementation is to invoke the (existing) <code>info</code> method in <code>Logger</code>, with the <code>msg</code> argument. Likewise, <code>omg</code> is assigned to the <code>severe</code> method. Therefore, an invocation like:</p>
<pre class="brush: groovy; title: ; notranslate">
Logger log = Logger.getLogger(this.class.name)
log.fyi 'for your information'
log.omg 'oh my goodness'
</pre>
<p>results in</p>
<p><code>Dec 12, 2011 10:09:02 PM java_util_logging_Logger$info call<br />
INFO: for your information<br />
Dec 12, 2011 10:09:02 PM java_util_logging_Logger$severe call<br />
SEVERE: oh my goodness</code></p>
<p>The methods work, but the output isn&#8217;t really what I want. The messages get passed through, but the output shows <code>INFO</code> and <code>SEVERE</code> rather than <code>FYI</code> and <code>OMG</code>.</p>
<p>It turns out it takes a bit of work to define a custom log level. Levels are defined using the <code>java.util.logging.Level</code> class, which predefines levels like <code>Level.INFO</code>, <code>Level.WARNING</code>, and <code>Level.SEVERE</code>. The <code>Level</code> class has a protected constructor which can be used to make new levels. I therefore adding a class called <code>CustomLevel</code>, as follows:</p>
<pre class="brush: groovy; title: ; notranslate">
import java.util.logging.Level

class CustomLevel extends Level {
    CustomLevel(String name, int val) {
        super(name,val)
    }
}
</pre>
<p>Each level gets an integer value. On my Windows 7 system (sorry) using JDK 1.6, the actual values of some of the defined levels are:</p>
<pre class="brush: groovy; title: ; notranslate">
import java.util.logging.Level

println &quot;$Level.INFO: ${Level.INFO.intValue()}&quot;
println &quot;$Level.WARNING: ${Level.WARNING.intValue()}&quot;
println &quot;$Level.SEVERE: ${Level.SEVERE.intValue()}&quot;
</pre>
<p><code>INFO: 800<br />
WARNING: 900<br />
SEVERE: 1000<br />
</code></p>
<p>My second attempt was then to define a Groovy category, so that I could replace a couple of the existing levels in a controlled fashion.</p>
<pre class="brush: groovy; title: ; notranslate">
import java.util.logging.Level
import java.util.logging.Logger

class SlangCategory {
    static String fyi(Logger self, String msg) {
        return self.log(new CustomLevel('FYI',Level.INFO.intValue()),msg)
    }
    static String lol(Logger self, String msg) {
        return self.log(new CustomLevel('LOL',Level.WARNING.intValue()),msg)
    }
}

Logger log = Logger.getLogger(this.class.name)
use(SlangCategory) {
    log.fyi 'this seems okay'
    log.lol('snicker')
}
</pre>
<p>Each of the logging methods in the <code>Logger</code> class (like <code>info()</code> or <code>warning()</code>) delegate to the <code>log()</code> method, which takes two arguments &#8212; an instance of <code>Level</code>, and a message <code>String</code>. I therefore used the category to replace the INFO and WARNING levels with FYI and LOL. The output is now:<br />
<code><br />
Dec 12, 2011 10:20:29 PM sun.reflect.NativeMethodAccessorImpl invoke0<br />
FYI: this seems okay<br />
Dec 12, 2011 10:20:29 PM sun.reflect.NativeMethodAccessorImpl invoke0<br />
LOL: snicker</code></p>
<p>Once again, this is just replacing existing levels, though it does at least have the new level name in the output string.</p>
<p>To really do this right, though, I wanted to be able to define new levels arbitrarily without having to hardwire them. That meant overriding the <code>methodMissing</code> method in the <code>metaClass</code>, using what Jeff Brown describes as the &#8220;intercept, cache, invoke&#8221; pattern for metaprogramming. Here&#8217;s the result, which I&#8217;ll explain after the code.</p>
<pre class="brush: groovy; title: ; notranslate">
import java.util.logging.*

Logger.metaClass.methodMissing = { String name, args -&gt;
    def impl = { Object... varArgs -&gt;
        int val = Level.WARNING.intValue() +
            (Level.SEVERE.intValue() - Level.WARNING.intValue()) * Math.random()
        def level = new CustomLevel(name.toUpperCase(),val)
        delegate.log(level,varArgs[0])
    }
    Logger.metaClass.&quot;$name&quot; = impl
    impl(args)
}

Logger log = Logger.getLogger(this.class.name)
log.wtf 'no effin way'
log.whoa 'dude, seriously'
log.rofl &quot;you're kidding, right?&quot;
</pre>
<p>The <code>methodMissing</code> method of the <code>metaClass</code> takes two arguments: the name of the method, and the arguments passed to it. Whenever you invoke a method that doesn&#8217;t exist, <code>methodMissing</code> gets invoked. That&#8217;s the &#8220;<em>intercept</em>&#8221; part.</p>
<p>The implementation is to define a closure that takes any number of arguments. Inside the closure, I computed a random value between <code>Level.WARNING</code> and <code>Level.SEVERE</code>, and then used that value to instantiate a custom level. The defined level and the new value were used in the <code>log</code> method on the closure&#8217;s <code>delegate</code> property (in this case, the logger) to log the message at the new level.</p>
<p>Finally, the <code>"$name"</code> method to the <code>metaClass</code> (which evaluates the name variable &#8212; otherwise the method added would just be called <code>name</code>) is assigned to the <code>impl</code> closure. That&#8217;s the &#8220;<em>cache</em>&#8221; part. Finally, the implementation is called, which is the &#8220;<em>invoke</em>&#8221; part.</p>
<p>Now I can use a log level with whatever name I want. The output of this script is<br />
<code>Dec 12, 2011 10:31:35 PM sun.reflect.NativeMethodAccessorImpl invoke0<br />
WTF: no effin way<br />
Dec 12, 2011 10:31:35 PM sun.reflect.NativeMethodAccessorImpl invoke0<br />
WHOA: dude, seriously<br />
Dec 12, 2011 10:31:35 PM sun.reflect.NativeMethodAccessorImpl invoke0<br />
ROFL: you're kidding, right?</code></p>
<p>The demos are nice, but this really ought to be tested. I&#8217;m reasonably comfortable with this level (snicker) of metaprogramming, but I&#8217;d feel a lot better if I had a real test for it.</p>
<p>That took a fair amount of digging. It turns out that the inimitable Dierk Koenig (lead author of <a href="http://manning.com/koenig2">Groovy in Action</a>, known as #regina on Twitter; second edition available now through the Manning Early Access Program) wrote a class called <code>groovy.lang.GroovyLogTestCase</code>. That class has a static method called <code>stringLog</code>. The GroovyDocs say:</p>
<p>&#8220;Execute the given Closure with the according level for the Logger that is qualified by the qualifier and return the log output as a String. Qualifiers are usually package or class names. Existing log level and handlers are restored after execution.&#8221;</p>
<p>It took me a while figure out how to use that, but eventually I got it to work. It automatically captures the console appender output, so the resulting test looks like this:</p>
<pre class="brush: groovy; title: ; notranslate">
import java.util.logging.Level
import java.util.logging.Logger

class LoggingTests extends GroovyLogTestCase {
    String baseDir = 'src/main/groovy/metaprogramming'
    
    void testWithoutCustomLevel() {
        def result = stringLog(Level.INFO, without_custom_levels.class.name) {
            GroovyShell shell = new GroovyShell()
            shell.evaluate(new File(&quot;$baseDir/without_custom_levels.groovy&quot;))
        }
        assert result.contains('INFO: for your information')
        assert result.contains('SEVERE: oh my goodness')
    }
    
    void testSlangCategory() {
        def result = stringLog(Level.INFO, use_slang_category.class.name) {
            GroovyShell shell = new GroovyShell()
            shell.evaluate(new File(&quot;$baseDir/use_slang_category.groovy&quot;))
        }
        assert result.contains('FYI: this seems okay')
        assert result.contains('LOL: snicker')
    }

    void testEMC() {
        def result = stringLog(Level.INFO, use_emc.class.name) {
            GroovyShell shell = new GroovyShell()
            shell.evaluate(new File(&quot;$baseDir/use_emc.groovy&quot;))
        }
        assert result.contains('WTF: no effin way')
        assert result.contains('WHOA: dude, seriously')
        assert result.contains(&quot;ROFL: you're kidding, right?&quot;)
    }
}
</pre>
<p>I should mention a couple of minor points. First, the class associated with a script has the same name as the file containing it, so the classes in the <code>stringLog</code> method are the script names. Second, in case you were wondering, the emc part of the script name stands for <code>ExpandoMetaClass</code>.</p>
<p>I spent a very pleasant evening working on this, and learned a few things:<br />
1. Groovy metaprogramming is fun,<br />
2. Now I know how to use <code>GroovyLogTestCase</code>, which is not at all well documented, and<br />
3. I&#8217;ll go to all sorts of trouble to avoid working on what I&#8217;m supposed to be working on, especially if it involves a joke. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I added all this to my book&#8217;s source code. What book, you ask? Why, <a href="http://manning.com/kousen">Making Java Groovy</a>, available through the Manning Early Access Program (MEAP) at <a href="http://manning.com/kousen">http://manning.com/kousen</a>. I don&#8217;t know, however, if I&#8217;ll have room in the text to include all this. </p>
<pre class="brush: groovy; title: ; notranslate">
log.marketing('Please forgive the mandatory advertising for my book')
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kousenit.wordpress.com/328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kousenit.wordpress.com/328/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kousenit.wordpress.com&#038;blog=186706&#038;post=328&#038;subd=kousenit&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kousenit.wordpress.com/2011/12/13/log-roflfun-with-groovy-metaprogramming/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/432fcf0d43d64c1189d9672716ac679d?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">kousenit</media:title>
		</media:content>
	</item>
	</channel>
</rss>
