Up and Running Groovy: An O’Reilly screencast for my Manning book (wait, what?)

Way back in the Spring of 2009, I was contacted by an editor at O’Reilly about doing a couple of “targeted video/screencasts”. This person (who is no longer there — I’d give you his name but I haven’t asked his permission yet) had the idea of getting people together in an informal setting and talking about state of the art technologies.

To make a long story short (it’ll get longer later), I wound up flying to Sebastopol, CA in late April, 2009, and we recorded two extended screencasts at the Westerbeke Ranch Conference and Event Center in the heart of Sonoma Valley wine country. We were the only people there, so it was pretty quiet. It also hadn’t yet warmed up, so we were on the chilly side, but that wasn’t a problem either. Oh, and the wine was good, too. 🙂

The format of the screencasts was a conversation between me and a single developer, shifting between us and the laptop I was using (a Sony VAIO, with a Camtasia install that almost brought it to its knees).

One of those screencasts, on Enterprise Java, has mercifully been lost to the mists of time. The other now has the title “Up and Running Groovy“, and much to my surprise was released to Safari online today. You can find it at http://my.safaribooksonline.com/video/-/9781449323387.

The code holds up surprisingly well, even after 2 1/2 years. The funniest part, though, is that the second slide mentions the upcoming O’Reilly book “Making Java Groovy“, co-authored by Scott Davis (!) and me.

Um, yeah. The book did start out with Scott, and in late 2009 he signed it over to me. In early 2010, O’Reilly cancelled it, along with many others, citing a lack of demand for Groovy. The people at Manning saw the world differently, and now you can get over half of it through the Manning Early Access Program at http://manning.com/kousen.

So here we are, years later, with the odd situation of an O’Reilly screencast that is effectively marketing a Manning book. I don’t think I could make this stuff up.

If you actually watch it and have any questions, please feel free to send them along. I assure you all questions or comments I’m getting these days are changing how I’m writing my book.

Converting Groovy maps to query strings

Yesterday I was teaching a class on Groovy when I suddenly realized there was a simpler way to do something I’d been doing for years.

I like showing developers how easy it is to access RESTful web services with just a couple of lines of Groovy. The process is particularly simple if all you need is a GET request, since you can just convert a String to a URL and use the getText method to retrieve the response.

For example, consider the Google Chart Tools service. The idea there is that you can send your data in a URL to Google and the service will return a graphical image of the data. The “Hello, World!” example from the documentation looks like

https://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World

There is a base URL (https://chart.googleapis.com/chart) followed by a query string with lots of parameters. In this particular case, the parameters are chs (the chart size, 250×100 pixels), chd (chart data, here 60 and 40), cht (the chart type, here a 3D pie chart), and chl (the chart labels, “Hello” and “World” separated by vertical bars). If you transmit this URL to Google, it will respond with a nice image.

It’s easiest to see that by simply embedding the URL as the href attribute of an <img> tag.

From a Groovy point of view, the URL looks like a base string plus a map that has been converted into a query string. I would write a script like the following to assemble it.

def base = 'https://chart.googleapis.com/chart?'

def params = [chs:'250x100', chd:'t:60,40', cht:'p3', chl:'Hello|World']

def url = base + params.collect { k,v -> "$k=$v" }.join('&')

Nice and simple. The collect method applies the closure to the params map, transforming each entry from a key, value pair into the string “key=value” and returns the resulting list. Then the join method produces a string by connecting each of the list elements with the ampersand delimiter. I’ve been telling people that this particular combination of collect method, closure, and join is a very useful way to assemble a query string from a map of parameters.

Yesterday, however, I was showing the students that according to the Groovy JDK there are two versions of the each iterator on java.util.Map. One version takes a two argument closure that automatically separates the keys from the values, just as I did above. The other uses a single argument closure, which treats each element as an instance of Map.Entry, so that you have to call it.key or it.value (i.e., it.getKey() and it.getValue()) to get the keys and values individually.

To illustrate the point, I took a trivial map and printed out the keys and values, and then I printed out the map entries, at which point I got a surprise.

[x:1, y:2, z:3].each { k,v -> println "$k=$v" }
[x:1, y:2, z:3].each { println it }

Lo and behold, the map entries printed out in the form “key=value”. In other words, the toString method on Map.Entry prints exactly what I needed for the query string.

It then occurred to me to look and see if all the other methods on Map (like find, findAll, count, sort, and especially collect) also had both one- and two-argument closure versions, just like each. And, sure enough, they all did.

In other words, instead of

def url = base + params.collect { k,v -> "$k=$v" }.join('&')

all I really need to write is

def url = base + params.collect { it }.join('&')

and I get the same result. The collect method transforms the map into a list whose elements are the map entries, and then the join method invokes toString on each and assembles the query string out of the result.

Wow. As simple as my original code was, I’ve been doing it the hard way all along.

Of course the down side is that now I need to go back and revise all my similar examples in my book, Making Java Groovy, available in Early Access Form from Manning at http://manning.com/kousen (new Testing chapter added this week).

That’s a small price to pay for discovering that Groovy is even simpler than I realized. 🙂

%d bloggers like this: