Categories
Groovy

Making Java Groovy at JavaOne 2013

Monday morning I gave my “Making Java Groovy” presentation at JavaOne in San Francisco. This is my first trip to JavaOne, and the sheer size of it is rather overwhelming. Of course, it’s also obvious at almost every turn that JavaOne is the weak sister of Oracle Open World, but hey, it could have been IBM, right?

I’ve been thinking about this presentation for literally years. I give a related talk on the No Fluff, Just Stuff tour all the time, and I’ve done similar talks at DevNexus, Gr8conf.us, and more. But this is JavaOne — the heart of the Java universe — and doing well here is supposed to mean something. Besides, if the evals are good enough, you can become a JavaOne Rock Star, which is likely the closest I’ll ever get to being any kind of rock star, so there’s that.

The biggest thing I worried about, though, was condensing my talk into an hour. On the NFJS tour I’m accustomed to 90 minute blocks, and frankly I can talk about Groovy all day long (and frequently do in training classes). I kept cutting parts I liked, though, until I thought I had something reasonably condensed.

Perhaps it’s not surprising, therefore, that I was much more nervous for this talk than normal. Nate Schutta (fellow NFJS speaker and one of the best presenters I’ve ever met) likes to remind me that we speakers are an odd breed. It’s pretty strange to find somebody who both likes to code and likes to stand up in front of an audience and talk about it. Actually, it’s weird enough to do the latter. Most people find public speaking terrifying. Somehow we manage to like it and even look forward to it.

Since this was my only talk at the conference (probably a mistake on my part; I should have submitted more proposals), I knew I could use everything I had. At NFJS conferences, I worry that after two or three talks, everybody’s heard all my jokes, which is a serious disadvantage. Of course, that assumes they listened to them in the first place. 🙂

I still had time after setting up, so I did a couple of things to entertain the audience before the mics were turned on. One was that I went to http://speedtest.net and checked the speed of the ethernet connection, which came in at around 85 Mbps. Sweet. I did this while the projector was on, partly just to see the reaction and partly to make the “wow, I could have downloaded that whole Breaking Bad episode in five minutes” joke.

That is a joke, of course. I would never do anything our corporate masters at the MPAA (and the RIAA) wouldn’t want, and if I did, I certainly wouldn’t admit it in a public forum like this.

Then I opened up a tab in my browser to http://emergencykitten.com . I liked refreshing the page anyway, but I claimed I did it in case anything in the presentation went wrong, which might even have been true.

I noticed, btw, that there is a GitHub link on emergencykitten.com, which says that the site apparently runs using nodejs on Heroku. If you look in the data folder there, you’ll find kittens.yml (!), which contains the links to the Flikr pages for all the images.

I’ll come back to that in a moment.

JavaOne wanted me to use PowerPoint, which was a singularly uncomfortable proposition. I used it anyway, but felt free to make fun of it during the talk, especially because it became balky every time I switched from it to a demo and back. The slides are mostly for summaries anyway, since my talk is almost completely code based, but I did add some fun meme-based pictures.

For example, check out this one:

grinds_my_gears

The slides themselves are now on slideshare.net, so you can see the whole presentation here.

I start with a demonstration that you can execute compiled Groovy code with the Java command, if you just add the “groovy-all” jar file to your classpath. That’s a cool demo, but it also shows that you don’t need to modify your production Java environment at all in order to add Groovy to your system.

Then I talk about operator overloading, and how even though I don’t do it a lot, it shows up in all sorts of places in the Groovy JDK.

I jumped from there to POGOs, and wrote a POGO that had a couple of attributes and AST transformations for @ToString, @EqualsAndHashCode, and @TupleConstructor, before replacing all three with @Canonical.

I then did my favorite demo of accessing and using the Groovy v3 geocoder. The code for that is in my book’s GitHub repository in a couple of different places, along with Spock tests for both online and offline (!) usage.

This nice image followed:

success_kid_mjg

I went from there to my default JSON example, which is still based on ICNDB: the Internet Chuck Norris Database. When I use it now I generally use the firstName and lastName properties so I can replace “Chuck Norris” with Guillaume Laforge, or Paul King, or even Brian Goetz. As luck would have it, the site was up and running, so I was able to do that, too.

That leads to my favorite image:

most_interesting_mjg

I said I would come back to the Flikr issue, and since I want to add something technical to this post, I’ll do that here. Flikr has a REST API, but it’s rather more involved than I like to use in a presentation. Here’s my basic search:

[sourcecode language=”groovy”]
String key = ‘…my key…’
String endPoint = ‘http://api.flickr.com/services/rest?’
def params = [method: ‘flickr.photos.search’, api_key: key,
format: ‘json’, tags: ‘cat’, nojsoncallback: 1,
media: ‘photos’]
[/sourcecode]

I’m searching for cat pictures, which as everyone knows is the reason the Internet was invented. Most of the parameters are required, but I used nojsoncallback=1 to keep from wrapping the JSON response in a method. The only tag I submit is ‘cat‘, but I might want to add some more because that doesn’t always give me what I want. You have to be careful with Flikr, though, because you can get back almost anything.

I assemble the needed URL and submit it in the usual way:
[sourcecode language=”groovy”]
def qs = params.collect { it }.join(‘&’)
String jsonTxt = "$endPoint$qs".toURL().text
def json = new JsonSlurper().parseText(jsonTxt)
[/sourcecode]
Turn the map entries into list elements of the form “key=value” then join with an &; convert the string to a URL and download the text, then parse it with a JsonSlurper. This stuff becomes automatic after a while.

The complication with Flikr is that the response doesn’t actually include the image URL. Instead it breaks it into pieces, which I have to reassemble:
[sourcecode language=”groovy”]
def urls = []
json.photos.photo.each { p ->
urls << "http://farm${p.farm}.staticflickr.com/${p.server}/${p.id}_${p.secret}.jpg"
}
[/sourcecode]
Drilling down into each photo element, I can extract the farm, server, id, and secret elements and use them to create the URL for the actual image. This I then insert into a Java ImageIcon:
[sourcecode language=”groovy”]
new SwingBuilder().edt {
frame(title:’Cat pictures’, visible: true, pack: true,
defaultCloseOperation: WC.EXIT_ON_CLOSE,
layout:new GridLayout(0, 2)) {
urls[0..5].each { String url ->
label(icon:new ImageIcon(url.toURL()))
}
}
}
[/sourcecode]
The only odd part of this is the WC constant, which is an alias for javax.swing.WindowConstants. I build a GUI with six cat pictures in it, and I’m done.

Putting it all together (so you can copy and paste if you want — change the key to your own to make it run):
[sourcecode language=”groovy”]
import groovy.json.*
import groovy.swing.SwingBuilder

import java.awt.BorderLayout as BL
import java.awt.GridLayout
import javax.swing.ImageIcon
import javax.swing.WindowConstants as WC

String key = ‘…insert your key here…’
String endPoint = ‘http://api.flickr.com/services/rest?&#8217;
def params = [method: ‘flickr.photos.search’, api_key: key,
format: ‘json’, tags: ‘cat’, nojsoncallback: 1,
media: ‘photos’]

def qs = params.collect { it }.join(‘&’)
String jsonTxt = "$endPoint$qs".toURL().text
def json = new JsonSlurper().parseText(jsonTxt)

def urls = []
json.photos.photo.each { p ->
urls << "http://farm${p.farm}.staticflickr.com/${p.server}/${p.id}_${p.secret}.jpg"
}

new SwingBuilder().edt {
frame(title:’Cat pictures’, visible: true, pack: true,
defaultCloseOperation: WC.EXIT_ON_CLOSE,
layout:new GridLayout(0, 2)) {
urls[0..5].each { String url ->
label(icon:new ImageIcon(url.toURL()))
}
}
}
[/sourcecode]
I ran the script and got two cat pictures and four pictures of tractors. I was confused until somebody pointed out that they were probably Caterpillar tractors, which shows what kind of trouble you can get into on Flikr. Believe me, it could have been worse.

Bringing it back to the GitHub repo for emergencykitten.com, maybe in the future I’ll grab the Flikr URLs in their repo and do the same thing. Still, this is a reasonably cool demo, and why not live a bit dangerously anyway?

The talk went well and a good time was had by all. At least I hope so, though I won’t know for sure until I see the session surveys and find out of I’m a rock star after all.

For the record, I’d like to say that as Groovy Rock Stars go, if Paul King is Led Zeppelin, Guillaume Laforge is the Rolling Stones, and Graeme Rocher is the Beatles, then I want to be E.L.O. I always liked E.L.O. and owned several of their albums when I was a kid.

Actually, that’s not quite right. I didn’t own several of their albums. I owned several of their 8-track tapes. Whoa.

I have to say, though, that the most interesting experience of all was seeing my book on the shelves of the bookstore at the conference. I went in late in the day and was about to frown at the number of copies on the shelf when somebody walked up, took one, browsed through it, grinned wryly to himself, and actually bought the bloody thing. I was extremely tempted to introduce myself and offer to sign it or take a picture of him holding it, but in the end I decided that would be too creepy.

My wife, who came along to do sightseeing in San Francisco, agreed with that. Still, I’ll be at the conference until Thursday, so if anyone wants me to add my chicken scratch to their book, just ask around. I promise not to hover too close to the store.

Categories
Groovy

Making Java Groovy: JavaRanch this week

This week Making Java Groovy is the featured book at JavaRanch, where I’ve been a member for many years. JavaRanch is yet another of Kathy Sierra’s (and Bert Bates’s) contributions to the community, which started out as a certification study site and evolved into an excellent message board. Until StackOverflow came along, it was my favorite place for getting answers to technical questions. It’s still an excellent example of how a friendly non-trolling technical community can operate.

If you drop by and ask a question in the Groovy forum, you can win a copy of my book.

Last week was a very busy one for me. I gave four talks at the NFJS event in Seattle, then went from there to the SpringOne2GX conference in Santa Clara, and then did the NFJS event in Boston area (Framingham, to be specific). I had a great time at all three events.

One of my favorite moments was in my “Advanced Groovy: Tips and Tricks” talks, when I noticed Paul King walk into the room. If you’ve read any of my book, you know I’m a big fan of his. In addition to being a Groovy committer, he’s also a co-author on Groovy in Action. If you’re interested in anything Groovy, be sure to check out his presentations at SlideShare.net.

While I was able to handle most of the questions, Paul did show me a few items after I was finished. For example, running collect on a map is even easier than I thought. To build a query string, I used to do this:
[sourcecode language=”groovy”]
String qs = [a:1, b:2, c:3].collect { k,v -> "$k=$v" }.join(‘&’)
assert qs == ‘a=1&b=2&c=3’
[/sourcecode]
Paul noticed I did that in a blog post and reminded me that the toString method on Map.Entry returns “key=value”, so I can reduce that to:
[sourcecode language=”groovy”]
String qs = [a:1, b:2, c:3].collect { it }.join(‘&’)
assert qs == ‘a=1&b=2&c=3’
[/sourcecode]
It turns out that now there’s even a default collect method that returns it, so I can make this even simpler:
[sourcecode language=”groovy”]
String qs = [a:1, b:2, c:3].collect().join(‘&’)
assert qs == ‘a=1&b=2&c=3’
[/sourcecode]
I need the parentheses on the collect method (or the compiler will think it’s a property), but it’s hard to get any simpler than that.

Another interesting question came up when I was talking about metaprogramming. For years I knew you could add a method to a class by adding a new property to its metaclass. For example, I can add a cook method to Map:
[sourcecode language=”groovy”]
Map.metaClass.cook = { BigDecimal purity -> "$purity% pure meth" }
assert ‘85% pure meth’ == [a:1, b:2].cook(85)
[/sourcecode]
(Sorry about the drug example. Like so many people, I’m totally caught up in the last few episodes of Breaking Bad. And btw, I have no idea what the actual ingredients are for meth, though I know one of them involves ephedra because I have to sign for my allergy medication at the pharmacy now.)

The question that came up was, can I overload that method using the same technique? I can certainly create a closure with different arguments, but can I assign it to the same property without messing up the original assignment?

Here’s an alternative implementation of the cook method:
[sourcecode language=”groovy”]
import java.awt.Color

Map.metaClass.cook = { Color c -> "$c-tinted meth" }
assert ‘java.awt.Color[r=0,g=0,b=255]-tinted meth’ ==
[a:1, b:2].cook(Color.blue)
[/sourcecode]
I can assign the two different implementations to the same property:
[sourcecode language=”groovy”]
import java.awt.Color

Map.metaClass.cook = { Color c -> "$c-tinted meth" }
Map.metaClass.cook = { BigDecimal purity -> "$purity% pure meth" }
assert ‘85% pure meth’ == [a:1, b:2].cook(85)
assert ‘java.awt.Color[r=0,g=0,b=255]-tinted meth’ ==
[a:1, b:2].cook(Color.blue)
[/sourcecode]
It still looks funny to me, but it works under the hood. Good to know.

Paul would probably appreciate it if I also mention that the example I chose was my own. He didn’t suggest drugs at any stage of development.

If you get a chance, please drop by the Groovy forum at JavaRanch this week and say hi. As another reminder, my Making Java Groovy presentation at JavaOne is Monday morning at 10am, so if you’re there, please drop by. I gave away over 20 print copies of my book at SpringOne2GX, and I’m sure I’ll have more at JavaOne. I’ll even deface sign one for you if you like. 🙂

Categories
Groovy

Trains on the Range

I’m at SpringOne2GX this week, but this morning before my first presentation I noticed the following in my Twitter feed:

DailyGrailsTip_ranges

First of all, I think that’s the first time anything of mine has ever appeared in @DailyGrailsTip, so yay for me. On the other hand, the link is to a script that isn’t terribly self explanatory. At the risk of spoiling part of my Advanced Groovy Tips and Tricks talk, I thought I’d discuss it here.

The basic idea is that any Groovy class can be made into a range if it:

  1. implements java.util.Comparable
  2. has a next method
  3. has a previous method

My example uses a TrainStation class, which forms a doubly-linked list when I place them along a track. So part of the implementation is trivial:
[sourcecode language=”groovy”]
class TrainStation implements Comparable<TrainStation> {
// Links to next and previous stations
TrainStation next
TrainStation previous

TrainStation next() { next }
TrainStation previous() { previous }

@Override // implement Comparable
int compareTo(TrainStation ts) {
// Hmm. What to do here?
}
}
[/sourcecode]
The TrainStation has a reference to the next one and the previous one, and the implementations of next and previous just return them. (I considered making a wrapper class called Track, but kept it simple here.)

The question is, how am I going to implement Comparable? Since one important characteristic of train stations is their physical location, I decided to use latitude and longitude, and made the comparison based on latitude.

The result is:
[sourcecode language=”groovy”]
import java.text.NumberFormat

class TrainStation implements Comparable<TrainStation> {

// Links to next and previous stations
TrainStation next
TrainStation previous

// location attributes
String city
String state

// set by Geocoder service
BigDecimal latitude
BigDecimal longitude

TrainStation next() { next }
TrainStation previous() { previous }

@Override
int compareTo(TrainStation ts) {
this.latitude <=> ts.latitude
}

String toString() {
NumberFormat nf = NumberFormat.instance
"$city, $state \t (${nf.format(latitude)}, ${nf.format(longitude)})"
}
}
[/sourcecode]
Each train station has a city and state, which I set, and a latitude and longitude, which are computed from a geocoder. My geocoder is based on Google’s RESTful web service, which I’ve used many times before:
[sourcecode language=”groovy”]
class Geocoder {
public static final String BASE = ‘http://maps.google.com/maps/api/geocode/xml?&#8217;

void fillInLatLng(TrainStation station) {
String encoded =
[station.city, station.state].collect {
URLEncoder.encode(it,’UTF-8′)
}.join(‘,’)
String qs = [sensor:false, address: encoded].collect { it }.join(‘&’)
def response = new XmlSlurper().parse("$BASE$qs")
station.latitude = response.result[0].geometry.location.lat.toBigDecimal()
station.longitude = response.result[0].geometry.location.lng.toBigDecimal()
}
}
[/sourcecode]
The fillInLatLng method takes a train station and URL encodes its city and state, so that they can be sent as part of a URL. It then builds a query string by converting the map entries in the form “key:value” into list entries in the form “key=value”.

(Note: I used to write that as [a:1, b:2].collect { k,v -> "$k=$v" }. Then Paul King pointed out that the default toString method on Map.Entry is in fact “key=value”. Therefore I can just write [a:1, b:2].collect { it } and it does the same thing. Live and learn.)

After building the query string, I use the parse method from XmlSlurper to access the web service, download the resulting XML, parse it into a DOM tree, and hand me the root. The rest is just walking the tree, keeping in mind that sometimes Google returns more than one request, so I made sure to use the first one only by writing result[0].

To use the new class, I need to create some train station and set their next and previous properties. Then I can use them in a range. Here’s a script to do all that:
[sourcecode language=”groovy”]
// Amtrak, NE corridor (mostly)
TrainStation was = new TrainStation(city:’Washington’, state:’DC’)
TrainStation bal = new TrainStation(city:’Baltimore’, state:’MD’)
TrainStation wil = new TrainStation(city:’Wilmington’, state:’DE’)
TrainStation phl = new TrainStation(city:’Philadelphia’, state:’PA’)
TrainStation nwk = new TrainStation(city:’Newark’, state:’NJ’)
TrainStation nyc = new TrainStation(city:’New York’, state:’NY’)
TrainStation nhv = new TrainStation(city:’New Haven’, state:’CT’)
TrainStation pvd = new TrainStation(city:’Providence’, state:’RI’)
TrainStation bos = new TrainStation(city:’Boston’, state:’MA’)

// Arrange the stations on the track
was.next = bal; bal.previous = was
bal.next = wil; wil.previous = bal
wil.next = phl; phl.previous = wil
phl.next = nwk; nwk.previous = phl
nwk.next = nyc; nyc.previous = nwk
nyc.next = nhv; nhv.previous = nyc
nhv.next = pvd; pvd.previous = nhv
pvd.next = bos; bos.previous = pvd

def ne_corridor = [was, bal, wil, phl, nwk, nyc, nhv, pvd, bos]

// Fill in all the latitudes and longitudes
Geocoder geo = new Geocoder()
ne_corridor.each { station ->
geo.fillInLatLng(station)
}

// range heading north
println ‘\nNorthbound from WAS to BOS’
(was..bos).each { println it }

// range heading south
println ‘\nSouthbound from BOS to WAS’
(bos..was).each { println it }

// subrange from nyc to bos
println ‘\nNYC to BOS’
(nyc..bos).each { println it.city }
[/sourcecode]
The resulting output is:

Northbound from WAS to BOS
Washington, DC (38.907, -77.036)
Baltimore, MD (39.29, -76.612)
Wilmington, DE (39.746, -75.547)
Philadelphia, PA (39.952, -75.164)
Newark, NJ (40.736, -74.172)
New York, NY (40.714, -74.006)
New Haven, CT (41.308, -72.928)
Providence, RI (41.824, -71.413)
Boston, MA (42.358, -71.06)

Southbound from BOS to WAS
Boston, MA (42.358, -71.06)
Providence, RI (41.824, -71.413)
New Haven, CT (41.308, -72.928)
New York, NY (40.714, -74.006)
Newark, NJ (40.736, -74.172)
Philadelphia, PA (39.952, -75.164)
Wilmington, DE (39.746, -75.547)
Baltimore, MD (39.29, -76.612)
Washington, DC (38.907, -77.036)

NYC to BOS
New York
New Haven
Providence
Boston

There you have it. I’ve taken an arbitrary class, TrainStation, and enabled it to be used in a Groovy range. This whole demo is part of the code I use in my “Advanced Groovy” talk, stored in my GitHub repository at https://github.com/kousen/AdvancedGroovy .

Quick book update: The ebook version of Making Java Groovy should be released today. The print book should be available from Manning on 9/16 or 9/17. The remaining mobile formats (epub and mobi) will be released on 9/27. I’m still hoping to have some physical copies here at the conference to give away, but I haven’t seen them yet.

Btw, it’s wonderful seeing so many of the Groovy and Grails team members at the conference. I seriously doubt, however, that any of them took the train to get here. 🙂

Categories
Groovy

Making Java Groovy: Operator Overloading

This is partly a spoiler for my “Making Java Groovy” talk that I normally do at NFJS events and plan to use in my similar talk at JavaOne, but to celebrate the book going to the printer I thought I’d try to contribute something technical here.

I’ve always felt that one of the keys to understanding Groovy was operator overloading. Operator overloading has a mixed reputation, conjuring up horror stories of developers changing + to be *, which might be good for job security but not good in general.

(Ultimately it’s not be good for job security, either.)

To be honest, I don’t do a lot of operator overloading in my own code, but I take advantage of it all the time. Most Groovy developers don’t realize how thoroughly operator overloading occurs throughout the Groovy JDK, among other places.

This web page lists all the operators in Groovy and their corresponding methods. What’s easy to overlook, however, is that every operator in Groovy actually invokes a method. That table doesn’t just provide you with options — it’s what’s actually happening under the hood. Note that it’s not just operators like + or * that call methods. Array-like access (the [] operator) calls getAt and putAt on maps, and even == invokes the equals method.

(Actually, == invokes the compareTo method if the class happens to implement java.util.Comparable, but according to the Comparable contract that ought to be equivalent.)

The code simplifications that result are dramatic. For example, consider the plus method in java.util.Date, which takes an int representing the number of days:
[sourcecode language=”groovy”]
Date now = new Date()
Date then = now + 3
assert 4 == (now..then).size()
[/sourcecode]

It’s also why you can not only concatenate with strings using +, you can also subtract substrings from them using the minus operator:
[sourcecode language=”groovy”]
String s = ‘silly string’
assert ‘more silly string’ == ‘more ‘ + s
assert ‘string’ == s – ‘silly ‘
[/sourcecode]
Note that in each case, the operator is returning a new string rather than modifying the original. Strings are still immutable, even in Groovy.

Let me give a larger example that uses Groovy / Java integration to make coding easier. If you’ve ever done financial calculations in Java (or if you’ve ever seen Office Space), you know you need to use java.math.BigDecimal for the amounts rather than just doubles. But BigDecimal in Java is an annoying class to work with, because (1) you have to instantiate it, (2) you have to remember to use the constructor that takes a String, or the results are not predictable (see the JavaDocs for details), and (3) you lose all your operators and have to use all the associated method calls, keeping in mind that (4) all instances of the class are immutable. That makes for a rather verbose class when all you want is to wrap a numerical value.

You can do all that, or you can take advantage of the fact that the native data type for floating point values in Groovy is already BigDecimal. Not only that, but the Groovy JDK includes methods like plus, minus, and multiply in the java.lang.Number class (the superclass of BigDecimal), so you can use your normal operators. The result is a class like:
[sourcecode language=”groovy”]
package com.mjg

import groovy.transform.Canonical

@Canonical
class Account {
BigDecimal balance = 0.0

BigDecimal deposit(BigDecimal amount) {
balance += amount
}

BigDecimal withdraw(BigDecimal amount) {
balance -= amount
}
}
[/sourcecode]
The only attribute is the balance, stored as a BigDecimal, initialized to zero. Since the attribute lacks a public or private modifier, Groovy automatically generates public getter and setter methods for it. The deposit and withdraw methods take advantage of operator overloading to update the balance using simple + and – operators. Finally, the Canonical AST transformation adds equals, hashCode, and toString methods to Account, as well as a “tuple” constructor that can be called from Java. That’s a lot of mileage for 16 lines of code.

Before I use it from Java, let me verify that it works so far:
[sourcecode language=”groovy”]
package com.mjg

// Normal Groovy ctor that sets the property
Account acct = new Account(balance:250)
assert 250 == acct.balance
assert 300 == acct.deposit(50)
assert 200 == acct.withdraw(100)

// check the tuple ctor
acct = new Account(150)
assert 150 == acct.balance

// toString method
assert ‘com.mjg.Account(150)’ == acct.toString()

// equals and hashCode
Set accounts = [new Account(balance:250), new Account(250)]
assert accounts.size() == 1
[/sourcecode]
Accounts can be created using the normal map-based constructor or the tuple constructor, which in this case has only a single argument (because the class has a single attribute). Accessing the balance property actually invokes the getBalance method, which is supplied by Groovy automatically. The generated toString method is as shown, and to prove that both equals and hashCode are working I added two identical accounts (instantiated by either constructor) into a Set and verified that Groovy added only one of them.

That’s all well and good, but if I can’t verify a Groovy class using Groovy tests, I might as well give it up. Instead, I want to access the Groovy class from Java. Here, therefore, is a highly contrived Bank class, in Java:
[sourcecode language=”java”]
package com.mjg;

import java.math.BigDecimal;

public class Bank {
public Account openAccount(double initialBalance) {
Account acct = new Account();
acct.deposit(new BigDecimal(initialBalance + ""));
return acct;
}

public BigDecimal getBalance(Account acct) {
return acct.getBalance();
}

public BigDecimal addFunds(Account acct, double amount) {
return acct.deposit(new BigDecimal(amount + ""));
}

public BigDecimal removeFunds(Account acct, double amount) {
return acct.withdraw(new BigDecimal(amount + ""));
}
}
[/sourcecode]
The Bank has a method to open an account using a double, which is wrapped in a BigDecimal using the String-based constructor. Then addFunds and removeFunds just delegate to the associated methods in Account.

To test this, I might as well switch back to Groovy again, but in a normal JUnit test:
[sourcecode language=”groovy”]
package com.mjg

import static org.junit.Assert.*;

import org.junit.Test;

class BankTests {
Bank bank = new Bank()
Account acct = bank.openAccount(250);

@Test
void testOpenAccount() {
assert acct
}

@Test
void testGetBalance() {
assert 250 == bank.getBalance(acct)
}

@Test
void testAddFunds() {
bank.addFunds(acct, 50)
assert 300 == bank.getBalance(acct)
}

@Test
void testRemoveFunds() {
bank.removeFunds(acct, 100)
assert 150 == bank.getBalance(acct)
}
}
[/sourcecode]
All the tests work without a problem, demonstrating how easy it is to switch from Groovy to Java and back again. If you ever have to add code to an existing Java system that involves BigDecimal, writing a class in Groovy is a very easy way to do it.

In my book, incidentally, the chapter on Spring and Groovy uses a similar Account class, but with an added id. Then I implement an AccountDAO interface (written in Java, of course) using the a Groovy class that takes advantage of Spring’s JdbcTemplate (again from Java), complete with Spock tests. If you want to see the source code now, just check out ch07 in the GitHub repository for the book.

As in this example, when I code in Groovy I don’t often do operator overloading, but the effects of it show up everywhere. Hopefully these simple examples will help you take advantage of it in the future.

BTW, I received notice from Manning that I will have actual hard copies of Making Java Groovy at the SpringOne2GX conference next week. Even if you don’t want one, please come by and say hello. Don’t be surprised if I can’t stop grinning the entire time.

Categories
Groovy

At long last, Making Java Groovy

I guess you could say it all started with Jason Rudolph.

In April of 2005, I decided to leave the training company where I worked (The Golden Consulting Group, which no longer exists) and go out on my own as an independent technical trainer. My one-person company is called Kousen IT, Inc., and if the old laptop in my office is still running you can even browse my website. The decision to go independent was a long time coming, but that is a story for another day. My story today is about the long, tangled process that eventually resulted in a book called Making Java Groovy, which goes to press next week from Manning Publications.

(Mandatory Hitchhiker’s Guide to the Galaxy reference: mine is a wholly remarkable book, containing much that is apocryphal, or at least wildly inaccurate, but still, a wholly remarkable book. Actually, I dearly hope it’s accurate, and I have lots and lots of test cases in the book’s GitHub repository to make sure.)

Shortly after I became an independent, I realized that there was no one to act as a filter between me and the general public. It sounds obvious, but at the time it was quite a surprise, and a scary one at that. After spending over 15 years in one company or another, suddenly my voice was the voice of the company, so whatever I said had direct impact on the company’s reputation.

As it turns out, that’s quite the incentive to stop talking. Instructors need that incentive, too. If you’ve ever been in a training class, you know that you should never let an instructor start talking. My job is to keep talking until you either agree or give up. 🙂

The beauty of being an independent, though, is that I don’t need anyone else’s permission to risk the entire company on a change in direction. If I think a new technology is seriously cool, I can dive in, hoping against hope that it will eventually become popular enough to bring in business. I just need to get good enough at it that I can offer training in it to handle that business.

In 2005, I was completely invested in the Java platform. I did training classes in all areas of Java, which at the time ranged from introductory courses to design patterns to EJBs (version 2.0 — shudder). The biggest event of 2005 to hit the Java world, however, was the introduction of Ruby on Rails.

Looking back, RoR was like a meteor striking planet Java, killing off many of the dinosaurs. I remember the first time I watched David Heinemeier Hansson‘s initial RoR screencast, where he wrote a complete blogging application in 15 minutes. Nowadays everybody makes screencasts, but at the time it was sufficiently unusual to be remarkable. He built the whole app, and it was dazzling, especially if you came from the Java world, where we would still be arguing over tools and technologies during the first 15 minutes.

In December of 2005, I bought the Ruby book (the pickaxe book in common parlance) and the Agile Web Development with Rails book and started digging in.

I readily admit now that it was rough going. Clearly to make progress in RoR I needed to learn Ruby, and even though all these testimonials said that Ruby was easy, I wasn’t prepared for it. I think I could learn it now without much difficulty, but at the time it was quite a transition. I plugged away at it for a few months in my spare time, but for a variety of reasons it just didn’t take.

In November of 2006, however, I happened to be teaching a Spring framework class in Philadelphia. That was one of my first Spring classes, and I was still getting used to the ideas behind it. I noticed, however, that the local Spring Users Group in Philly was hosting a meeting that week, and that the speaker was Jason Rudolph, and he was giving a talk on something called Grails.

That talk changed my life.

I told Jason this years ago, but I doubt he remembers. He may not even remember me, though he might. He was on the No Fluff, Just Stuff tour at the time and it was one of dozens of similar presentations he gave that year and the next, and that talk was part of the reason I started going to the NFJS events near Boston. I attended his talks each time and peppered him with questions. I also devoured his Getting Started with Grails book, available as a free download at InfoQ, which was the only real reference at the time. It was written using Grails version 0.4, if you can remember back that far.

Since I already was comfortable with Java, was really digging into Spring, knew something about Hibernate, and was familiar with the basic ideas from Ruby on Rails, I was the target audience for a Grails presentation. I immediately bought Groovy in Action, and was very pleasantly surprised that it was, and is, one of the best technical books I’ve ever read. I fell in love with Groovy back then, and suddenly coding was fun again.

I told all my training company clients that both Groovy and Grails were going to be huge. They asked me for course outlines, which I provided, and we waited for the requests to roll in. They stubbornly refused to do so for about three more years, but that, too, is another story.

After being a tech reviewer for a couple of Groovy books (including Scott Davis’s Groovy Recipes and Venkat Subramaniam’s Programming Groovy), I eventually built up enough expertise to want to write a book of my own. Through various machinations that I’ll detail in a later blog post, I eventually wound up at Manning, where the contract for Making Java Groovy was signed back in March of 2010.

Btw, the original contract still refers to the book as “Groovy in Practice”. That’s the book they were after, and I went along with the idea in order to get it sold, but I always prefered the current title.

That’s not quite true. We went through a phase where the book was going to be called “Groovy and Java: The Sweet Spots”. That abbreviated to GaJ, which didn’t really scan, so I suggested we change the name to “Java and Groovy: The Sweet Spots”, which abbreviated to JaG. That worked, and was even a TV show with Catherine Bell in it, so it was all good. In fact, even though we eventually changed the name to Making Java Groovy (abbreviated MJG, which isn’t even pronounceable, sigh), I still put all the meetings with my editor on my calendar as “JaG review”.

I have tons more to say (see what I mean about never letting an instructor start talking?), but this post has already gotten long, so let me tell you what’s coming:

1. The book is supposed to go to the printer next Tuesday (September 3), right after Labor Day. That’s when I plan to start a series of Silly Marketing Ideas (abbreviated SMI), mixed in with a few Serious Marketing Ideas (abbreviated SMI).

2. I will be at the NFJS event in Seattle September 7 and 8, where I’ll no doubt mention the book sooner or later.

3. I’m traveling from there to the wonderful SpringOne2GX conference in Santa Clara, September 10 to 12. We’re actually hoping to have advanced copies of Making Java Groovy available at the conference, which will be the first time anyone will see it in print. The phrase “woo hoo!!” comes to mind, but I’ll wait until it happens to believe it.

4. From SpringOne2GX I’m headed to the NFJS event in Boston on the weekend of September 13 to 14. Please drop by and say hello (world?) if you get a chance.

5. The week of September 17 to 20 my book will be featured at JavaRanch, and I’ll be answering questions (probably combined with some really bad jokes) in the forums there. Feel free to ask anything you like, though I prefer really easy questions mixed in with unbridled praise and adulation for the book. Or whatever.

6. At 10am on Monday morning, September 23, I’m giving a talk entitled “Making Java Groovy” (what an amazing coincidence!) at JavaOne in San Francisco. I’ve never been to JavaOne, but since my book is intended to appeal to Java developers in general, that seemed like an irresistible opportunity. Please, please, please if you’re at the conference please come to the talk. I’d hate to be showing cool Groovy demos to an empty room. I promise you I’ve added several hilarious figures to the presentation, so at least I’ve got that going for me. Which is nice.

During the entire time I hope to write lots of blog posts, partly because I’m so excited I can’t stand it, partly in my hopeless but wryly amusing quest to make my book the first Java/Groovy integration book to make the New York Times Best Seller list, partly because it’ll help me deal with all the massive fears and insecurities that have forced themselves to the surface as this all becomes real at last, and partly because hey, when am I ever going to do something like this again?

So life is happening to me right now, and I’m trying to get out ahead of it. I’ll apologize in advance for going a little overboard on the marketing side, but I promise to inject as much humor as possible into the process. I also promise that I’ll always tell the whole truth here, in my blog, so that no matter what you hear from other sources, I’ll make sure you are always in on the gags if you read them here.

My goals are (not in any particular order) to have fun, make some money, and show as many Java developers as possible how much easier their lives can be if they’re willing to mix some Groovy into their projects. At the very least, it ought to be a wild ride.

Oh, and thanks again, Jason. You’re actually the first person I mentioned in my Acknowledgements. Surprise! 🙂

Categories
Groovy

Gr8 Gr8Conf.US Was Gr8

This week I attended Gr8Conf US in Minneapolis. I did a Groovy workshop for Java developers, gave my Making Java Groovy talk, gave a talk on Grails testing, and even managed to throw in an Advanced Groovy Tips and Tricks talk at the last minute when Guillaume Laforge was unable to travel.

(Guillaume said he burned his hand rather badly while cooking. I prefer to believe that he was defending a bunch* of children from a horde of vicious biker ninjas (or possibly Scala developers) intent on world domination. That fits my mental image of him much better. He may look like Clark Kent, but when attacked by a horde of vicious biker ninjas (or possibly Scala developers) he transforms into — well, you know. Seriously, Guillaume, get well soon. You were missed.)

*What is the collective noun for children, anyway? Bunch? Herd? I like “mess”, as in “a mess of children.” Seems appropriate somehow.

This was the third Gr8Conf I’ve attended, and the quality has improved each year. Shaun Jurgemeyer did a great job of organizing, both in the quality and quantity of talks. One thing that was different this year was the Target Hackathon, which was held Sunday evening after the workshops and involved building an application using the Target API. I had what I thought was a good idea, but simply ran out of time, so I’ll save it for next year.

Later I saw pictures of the venue where the Hackathon was held, complete with ping-pong table and outdoor chess set. Like a typical developer, I had my head buried in my laptop the whole time and missed all that. I did manage to sit next to the eventual winner, Todd Miller, who turned out to be a seriously cool guy.

I don’t want to go through the talks I attended one by one, but I do have a few observations:

  • After sitting through Cedric Champeau’s workshop on AST transformations, I have to say I still find them confusing, but at least now my confusion has boundaries. I expect I’ll need to sit down and really dig into the associated chapter in Groovy in Action to understand them.
  • Several talks brought up the new capabilities planned for Grails 2.3, especially involving RESTful web services. I’m looking forward to them, too. What I didn’t expect was the backlash against HATEOAS (Hypermedia As The Engine Of Application State). On the NFJS tour I guess I’ve been hanging out with too many RESTafarians* lately. Peter Ledbrook told me that even David Heinemeier Hansson doesn’t see the benefit of hypermedia, though he’s hardly shy about speaking his mind or going against the popular wisdom. I spent months getting hypermedia to work for my REST chapter in Making Java Groovy**. I still think that was a good investment in time and effort, especially since there are very few good hypermedia examples out there, but maybe I shouldn’t worry so much about the fact that the word “hypermedia” doesn’t even appear in the JAX-RS 2.0 specification.
  • I had no idea how much the tooling in the JavaScript space has evolved. I’d never heard of Grunt, or Bower, or Yeoman, or any of the other tools that come from the nodejs ecosystem. I did hear one good quote, though I can’t remember who said it (probably Zan Thrash but I’m not sure), saying these tools “bring all the joys of downloading the internet to the JavaScript space.” I suppose it seems odd spending so much time on JavaScript at a Groovy conference, but that’s the web world we now live in.
  • I wish I could have seen Luke Daley’s Ratpack presentation, especially after he helped me get the build running at UberConf. Dan Woods managed to implement FOAAS on Ratpack (check it out, but it’s arguably NSFW). At the speaker dinner (thanks, Shaun!), Luke claimed that this was only the second Ratpack app in production, with the first being the Ratpack web site itself. 🙂
  • I also wish I could have attended Marco Vermeulen’s talk on GVM. I use GVM all the time and recommend it everywhere, especially if you ever have to change Groovy or Grails versions easily. I finally got to meet Marco, and it turned out he even likes my book***. He’s yet another great guy in the Groovy community. Honestly, the extraordinary friendliness and humility of the developers in the Groovy ecosystem is one of its best features.

*Yah mon, dey be callin’ demselves RESTafarians, which shows much more of a sense of humor than I originally thought they had.

**Are you impressed I made it this far before mentioning my book, Making Java Groovy? I know I am. I just uploaded the revised preface and appendices after the tech review, so everything is still on schedule for an early September release.

***Yeah, that’s probably a humblebrag. Let me turn it into a real brag. At both Gr8Conf and UberConf I had several people tell me how much they liked the book, which feels especially weird (oops, there’s the definitive humblebrag keyword again) because it’s not quite in production yet. Still, that was great to hear.

I feel obligated to do something technical in my blog posts, so let me mention a technique I use a lot and can implement with a tiny bit of metaprogramming. Whenever I need to access a RESTful web service that requires a set of parameters on a query string, I assemble them from a Groovy map.

For example, The random.org web site has a service that generates truly randome numbers “via atmospheric noise,” as they say on the site. To generate a set of random integers base URL is ‘www.random.org/integers’ and you add a series of parameters to specify what you want. In their main example, they ask for 10 numbers between 1 and 6, in 10 columns, base 10, in plain format using a new generator.

Here’s a quick Groovy script to call it:
[sourcecode language=”groovy”]
String base = ‘http://www.random.org/integers/?&#8217;
def qs =
[num:10, min:1, max:6, col:10, base:10, format:’plain’, rnd:’new’]
.collect{ k,v -> "$k=$v" }.join(‘&’)
def nums = "$base$qs".toURL().text.split()
[/sourcecode]
I put all the query parameters in a map, then use the collect method to produce a list of “key=value” pairs based on the map entries, and join them using an ampersand. Then I use the toURL method from the String class in the Groovy JDK to turn the address into an instance of java.net.URL, and the text property of the URL class to invoke the getText method. The result is something like:

[4, 1, 4, 6, 3, 3, 1, 4, 3, 3]

I’ve been writing code like that for years, but some time ago the brilliant Paul King told me I could simplify it. It turns out that the toString method in Map.Entry returns “key=value”, so I can write instead:
[sourcecode language=”groovy”]
[num:10, min:1, max:6, col:10, base:10, format:’plain’, rnd:’new’]
.collect{ it }.join(‘&’)
[/sourcecode]
He’s right, of course. I still use the more verbose version in presentations to Groovy newcomers, because it’s a bit clearer, but I normally use the simpler one in my own work.

It occurs to me that I can use Groovy metaprogramming to simplify this even further, if I plan to use that construct a lot. Here I add a toQS method to the Map interface.
[sourcecode language=”groovy”]
Map.metaClass.toQS = { -> delegate.collect { it }.join(‘&’) }

def qs =
[num:10, min:1, max:6, col:10, base:10, format:’plain’, rnd:’new’].toQS()
assert qs == ‘num=10&min=1&max=6&col=10&base=10&format=plain&rnd=new’
[/sourcecode]
I get the metaclass from the java.util.Map class* and add a toQS method by assigning it to a closure. Since my method doesn’t take any arguments, I used a zero-argument closure. The delegate property inside the closure refers to the map the closure was invoked on, and the rest is as before.

*Yes, I know java.util.Map is an interface, but it appears as a class in the Groovy JDK.

The final version of the demo script is therefore:
[sourcecode language=”groovy”]
Map.metaClass.toQS = { -> delegate.collect { it }.join(‘&’) }

String base = ‘http://www.random.org/integers/?&#8217;
def qs =
[num:10, min:1, max:6, col:10, base:10, format:’plain’, rnd:’new’].toQS()
println "$base$qs".toURL().text.split()
[/sourcecode]
There you have it. Now that I think about it, I should probably fork the Groovy project and submit a pull request for it. I’ll probably have to talk to Paul or Guillaume about that.

One last thing: what kind of motorcycle would vicious biker ninjas drive? Harley’s would be way too loud. I presume it would be one of those cool machines like in Tron, all in black.

Categories
Groovy

A Groovy Chuck Norris Script

This week I’m at UberConf (http://uberconf.com), a truly alpha-geek experience with sessions morning, afternoon, and evening. On Tuesday I did a day-long tutorial on Groovy for Java developers, which was really fun. I love teaching Groovy to existing Java developers. Sometimes they get tears in their eyes at how much easier life can be. 🙂 Wednesday I had a Spock workshop followed by a Grails workshop. Yesterday I did my Bayes’ Rule talk (“Bayes’ Rule Says You’ll Attend This Talk”), and today I’m doing my “Managing Your Manager” talk and my “Making Java Groovy” talk again.

Making Java Groovy has now moved into the production phase. So far this means discussing art work with the illustrators and trying to explain to them what I actually meant with my limited attempts at using a drawing tool.

I’ve been working on this book for nearly five years, and that means some of the earliest chapters needed some serious updating recently. When I started I think Groovy had just released version 1.6, so it’s changed versions at least four times during the writing process. Groovy 2.2 may even come out when the book shows up in print, at which point I’ll have to go back to the GitHub repo and update all the Gradle build files again.

One of the earliest chapters I wrote was the “Groovy by Example” chapter. In it I used the Google Chart API (which is now deprecated but still available) and an early version of my Groovy Baseball application. I really wanted to update all that to newer examples, but there simply wasn’t time, especially given that they all still worked correctly.

Still, I did take the time to write another example, even if it turned out to be too late to add it to the book. I’d like to show it here, because it’s simple but still pretty interesting, which is a good combination.

In many of my presentations (including one I’ll be doing later today), I like to access the ICNDB web site as an example of a RESTful web service that serves up JSON data. That’s ICNDB, as in the Internet Chuck Norris Database. ICNDB is a RESTful service in name only; it doesn’t do content negotiation (it doesn’t even set the “Content-Type” header correctly, a fact I discovered when I made an Android front end for it — see the ICNDB app in the Google Play store) and it only supports GET requests.

(Mandatory jokes: wouldn’t a RESTful service that only supports GET requests be called a GETful service? And if it’s stateless, wouldn’t that make it a FORGETful service? Insert rimshot here.)

The Groovy JDK makes it trivially easy to access a URL with a GET request. Groovy adds a toURL method to the String class, which converts a String into an instance of java.net.URL, and a getText method to the URL class, which returns the response as a String. Calling it is as simple as:
[sourcecode language=”groovy”]
import groovy.json.JsonSlurper

String base = ‘http://api.icndb.com/jokes/random?limitTo=%5Bnerdy%5D&#8217;
def json = new JsonSlurper().parseText(base.toURL().text)
println json?.value?.joke
[/sourcecode]
Following the normal Groovy idiom, I invoke getText by accessing the text property of the URL. Then I use a JsonSlurper to parse the result, which essentially converts it into a nested map-based data structure. The JSON object has a value property that holds another JSON object, which stores the actual joke in a property called joke. I don’t really need the safe de-reference operator here, but it doesn’t hurt.

The results are similar to:

Chuck Norris can unit test entire applications with a single assert.

The interesting question then becomes, how do I turn this into a client-side application with a graphical interface?

The Groovy API includes a so-called “builder” class called SwingBuilder, which makes Swing development almost (but not quite) cool. It even has easy ways to handle threading issues, so that I can access the service off of the event dispatch thread, but update the GUI back on it. The key is in the doOutside and doLater methods. The former allows you to do work without locking up the GUI, while the latter is where you update the interface.

(The best discussion of SwingBuilder I’ve ever seen is contained in Griffon in Action, by Andres Almiray, Danno Ferrin, and Jim Shingler.)

Here’s the whole script, which I’ll explain afterwards. In the book source code (just because I couldn’t put the app in the book doesn’t mean I couldn’t add it to the repo), this script is called icndb_with_label_and_button.groovy.
[sourcecode language=”groovy”]
import groovy.json.JsonSlurper
import groovy.swing.SwingBuilder

import java.awt.BorderLayout as BL
import java.awt.Color
import java.awt.Font

import javax.swing.WindowConstants as WC

String startHTML = "<html><body style=’width: 100%’>"
String endHTML = ‘</body></html>’

String base = ‘http://api.icndb.com/jokes/random?limitTo=%5Bnerdy%5D&#8217;
def slurper = new JsonSlurper()

new SwingBuilder().edt {
frame(title:’ICNDB’, visible: true, pack: true,
defaultCloseOperation:WC.EXIT_ON_CLOSE) {
panel(layout:new BL(), preferredSize:[300, 250], background: Color.WHITE) {
label(‘Welcome to ICNDB’,
constraints:BL.NORTH,
font: new Font(‘Serif’, Font.PLAIN, 24),
id: ‘label’)
button(‘Get Joke’, constraints:BL.SOUTH,
actionPerformed: {
doOutside {
def json = slurper.parseText(base.toURL().text)
doLater {
label.text = "${startHTML}${json?.value?.joke}${endHTML}"
}
}
}
)
}
}
}
[/sourcecode]
A couple of the import statements use the as operator to create aliases. That is, I can use WC in the script to refer to javax.swing.WindowConstants, and BL to represent java.awt.BorderLayout. That’s an interesting but underused feature of the as operator.

I want to add the joke to a JLabel, which supports HTML. Therefore, I defined strings to surround the HTML when I put the joke in the label.

The SwingBuilder class has an edt method which lets me operate on the event dispatch thread when building the GUI. Then terms (actually, method calls) like frame, panel, label, and button create instances of JFrame, JPanel, JLabel, and JButton from the Swing API. The attributes, like visible:true and title:'ICNDB' invoke the setVisible and setTitle methods, respectively.

Arguably the best part, though, is the actionPerformed property. If you’ve ever done Swing development, you know that clicking a JButton generates an ActionEvent. In order to capture the event you need an ActionListener, which has a single method called actionPerformed. In regular Swing development, the result is usually an inner class (or even an anonymous inner class) that implements the interface and updates the GUI. You use an inner class because the inner class is able to access the private attributes of the outer class, and when I used to do Swing development I normally made the labels and buttons attributes of my GUI class.

Here, though, I don’t need an inner class at all. Instead I assign the actionPerformed property to a closure, and I’m finished. One of the nicest uses of closures is to eliminate anonymous inner classes this way.

Inside the closure I use the doOutside method to access the service. Then I get back onto the EDT using doLater and update the GUI. By giving the label an id attribute, I was able to access it inside the doLater closure using the value of the id.

The result is something like:
icndb_label_with_button

That’s all there is to it. I’m not thrilled with the HTML parts, though, so I also implemented the script using a text area instead. The resulting script is in the file icndb_with_textarea_and_button.groovy:
[sourcecode language=”groovy”]
import groovy.json.JsonSlurper
import groovy.swing.SwingBuilder

import java.awt.BorderLayout as BL
import java.awt.Color
import java.awt.Font

import javax.swing.WindowConstants as WC

String base = ‘http://api.icndb.com/jokes/random?limitTo=%5Bnerdy%5D&#8217;
def slurper = new JsonSlurper()

new SwingBuilder().edt {
frame(title:’ICNDB’, visible: true, pack: true,
defaultCloseOperation:WC.EXIT_ON_CLOSE) {
panel(layout:new BL(), preferredSize:[300, 250], background: Color.WHITE) {
scrollPane {
textArea(‘Welcome to ICNDB’,
constraints:BL.NORTH,
font: new Font(‘Serif’, Font.PLAIN, 24),
lineWrap: true, wrapStyleWord: true, editable: false,
id: ‘textArea’)
}
button(‘Get Joke’, constraints:BL.SOUTH,
actionPerformed: {
doOutside {
def json = slurper.parseText(base.toURL().text)
doLater {
textArea.text = json?.value?.joke
}
}
}
)
}
}
}
[/sourcecode]
I wrap the text area in a scroll pane, but other than that it’s essentially the same code. The result now looks like:
icndb_with_textarea_and_button

So that’s it: a small, but hopefully non-trivial application that demonstrates Groovy capabilities including builders, thread handling, RESTful web services, and even the as operator. Have fun with it.

In the meantime, I’m ignoring the take down notice I received from Chuck Norris’s lawyers about my ICNDB app in the Play store. Sigh.

Categories
Groovy

Categories, old and new, and status of Making Java Groovy

My book, Making Java Groovy, is almost finished. I mean, I’m done, except that I’m not.

(Picture Michael Corleone in “Godfather, Part III”: “Just when I thought I was out, they pull me back in.”)

I thought I was essentially done in early June, after I turned in the last chapter. Then the reviews came back, and most of them were really positive, so I was very hopeful I was actually finished.

That’s when the tech editor chimed in.

In addition to the regular reviewers, Manning hires a tech editor for each book. I didn’t realize what that meant until I saw the result. My tech editor, Valentin, ripped my poor baby apart.

Except he didn’t, really. He just identified all the flaws I knew about and many that I’d missed. He did a fantastic job, actually, darn him.

After recoiling in horror, I eventually developed the following pattern. For each chapter, I would

  1. Read all the comments, trying not to (over)react to them with anger, denial, frustration, or any other emotion
  2. Close the document
  3. Come back at least half a day later, or sometimes a whole day
  4. Read what he actually wrote and start making the changes necessary to improve the book

I would estimate that based on Valentin’s (and the other reviewers’) comments I probably rewrote as much as a quarter of the book during June. In general, I hate rewriting, but the improvements were so obvious I couldn’t even complain about the process, though I tried. I just wish I could have shortened it a bit, but so be it.
The book is much, much better now. I hope you like it too.

After that I finished the rest of the book, meaning the preface*, acknowledgements, part headings, dedication page, adding another appendix**, and uploading all the figures. I finished all that last weekend, so I was finally all done.

* Nobody, and I mean nobody, will write a preface like mine. You’ll understand when you read it. I’m sure no one else would ever add 16 footnotes to a 4 1/2 page preface, with comments ranging from Star Trek to Joseph Campbell to the new cover sheets for T.P.S. reports.***

** Installing Groovy, which is so much easier thanks to GVM.

*** We’re putting new cover sheets on all the T.P.S. reports before they go out now. Did you get the memo?

Except I’m not done, because the graphics people want a different format for many of my figures. Plus, my editor (who spent the last ten days in an igloo in Alaska, or some such nonsense) hasn’t signed off on it yet.

So I’m not really done, but I’m awfully, awfully close. I’m still hoping that the book will be available in print in time for JavaOne in September, where I’m giving a talk entitled, “Making Java Groovy”. Yes, that’s the same name as the book, by an astonishing coincidence. I’m part of a large Groovy contingent at JavaOne this year, which is really groo^H^H^H^H cool.

One side effect of finishing will hopefully be the resurrection of my blog. I stopped blogging when I discovered that there were only so many words I could write in a day, and they really needed to go to the book rather than here. Now that that’s done (hopefully), I can start bringing my blog back to life.

For example, I did far less metaprogramming in the book than I wanted to, but I did come up with a simple example of a category in Groovy, which I implemented both in the old way and the new way.

Here’s the old way, saved in a class called CurrencyCategory.groovy:
[sourcecode language=”groovy”]
import java.text.NumberFormat

class CurrencyCategory {
static String asCurrency(Number amount) {
NumberFormat.currencyInstance.format(amount)
}

static String asCurrency(Number amount, Locale loc) {
NumberFormat.getCurrencyInstance(loc).format(amount)
}
}
[/sourcecode]
Note that both methods are static, and that their first argument is java.text.NumberFormat. That means the methods are added to the NumberFormat class.

The new way (as of Groovy 2.0, so not all that new, really) is in a class called AnnotationCurrencyCategory.groovy:
[sourcecode language=”groovy”]
import java.text.NumberFormat

@Category(Number)
class AnnotationCurrencyCategory {
String asCurrency() {
NumberFormat.currencyInstance.format(this)
}

String asCurrency(Locale loc) {
NumberFormat.getCurrencyInstance(loc).format(this)
}
}
[/sourcecode]
This class uses the @Category annotation, and the included methods are now instance methods that are added to class that is the argument of the annotation.

Here’s a test case to make sure they’re working:
[sourcecode language=”groovy”]
public class CurrencyCategoryTest {
public static final String EURO = ‘\u20ac’
def amount = 1234567.89012

@Test
void testCurrencyCategory() {
use(CurrencyCategory) {
if (Locale.default == Locale.US) {
assert amount.asCurrency() == ‘$1,234,567.89’
}
assert amount.asCurrency(Locale.GERMANY) == "1.234.567,89 $EURO"
assert amount.asCurrency(new Locale(‘hin’,’IN’)) == ‘INR 1,234,567.89’
}
}

@Test
void testAnnotatedCurrencyCategory() {
Number.mixin AnnotationCurrencyCategory
if (Locale.default == Locale.US) {
assert amount.asCurrency() == ‘$1,234,567.89’
}
assert amount.asCurrency(Locale.GERMANY) == "1.234.567,89 $EURO"
assert amount.asCurrency(new Locale(‘hin’,’IN’)) == ‘INR 1,234,567.89’
}
}
[/sourcecode]

In the first test, I employ a use block. Inside the use block, the category methods are added to the NumberFormat class. In the second test, I use the mixin method to make the new methods available.

Pretty cool, eh? I have a lot more examples to present, but that’s enough for a single blog post. More to come, on a much more regular basis now.

I’ll let you know when I’m really, really done, at which point I start rolling out the Silly Marketing Ideas (abbreviated SMI, as opposed to the Serious Marketing Ideas, abbreviated SMI). You’ve been warned.

Categories
Groovy

My Review of Programming Grails

Originally submitted at O’Reilly

Best Practices for Experienced Grails Developers

Excellent look under the hood of Grails

By Ken Kousen from Marlborough, CT on 9/25/2012

 

5out of 5

Pros: Accurate, Helpful examples, Easy to understand

Best Uses: Intermediate, Expert

Describe Yourself: Developer, Educator

Yes, this “early access” 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.

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.

(legalese)

Categories
Groovy

Adding a license to source files

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.

About a week ago, someone contacted me about the source code from my book, Making Java Groovy. The source code is located at my GitHub repository, https://github.com/kousen/Making-Java-Groovy. The requester noted that I didn’t have any sort of license file on my code and wondered what the terms were.

Leaving aside the wonder that (1) somebody found the book code useful (ack! humblebrag 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’t answer right away, so I interpreted that as freedom to do whatever I wanted. 🙂

A friend on a mailing list suggested that the Apache 2 license is appropriate if I don’t care too much how the code is used (and I don’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?

I thought I would solve the problem with the eachFileRecurse method that Groovy adds to Java’s java.io.File class. I quickly realized, though, that there were directories I wanted to skip, and that lead me to the traverse method, which takes a Map of parameters.

Here’s the result:
[sourcecode language=”groovy”]
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 "License");
* 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 "AS IS" 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 ->
// only add license if not already there
if (!file.text.contains(license)) {
def source = file.text
file.text = "$license$source"
}
assert file.text.contains(license)
}
[/sourcecode]
I used static imports for the FileType and FileVisitResult classes. The FILES constant comes from FileType, and the SKIP_SUBTREE constant comes from FileVisitResult. The parameters I used return only files whose name ends in either ‘java’ or ‘groovy’ and aren’t in any directory tree including ‘.metadata’.

Ultimately everything is based on the getText and setText methods that the Groovy JDK adds to the java.io.File class. Both are called using the text property. The getText method returns all the existing source code, and the setText method acts as an alias for the write 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.

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 FileTest and can be viewed in the Groovy GitHub repository here. The test cases showed how to use all of the methods, including traverse, so it was just a question of looking for the right example.

(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’s a great, great feature, especially if you don’t want to clone the source of every project you care about onto your own local disk.)

Since I hadn’t known about the traverse 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’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 John Lennon in the rooftop concert at the end of Let It Be, on behalf of Groovy and myself, I hope I passed the audition.