Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

Tuesday, February 11, 2020

Spock: Expect two calls from one method with specific results.

This is probably nothing new to many people, but it was a very pleasant surprise to me, so I'm posting here in case there are others as clueless as I. 

Here's the situation. I've got a method under test, in Spock. (Yay! Groovy!) There is a mocked class that has a method that will be called twice, so we want to expect that, and we need to specify the return results because they are used by the method under test. In some scenarios, the expected params are known and easy to construct in the test, like a String literal. This is the easy one.



However, in some scenarios, the expected params are more difficult to construct in the test code, and I still want to expect the two calls in a specific order and with specific return values—which, again, are used downstream.

This is where I was stumped.  My very limited Spock skills came back to haunt me, and Google failed to hide my ignorance. No worries: I'm working on a project with the brilliant (and helpful) developers from Object Partners, and Neal Buesing came up with this little gem.


Needless to say, it worked like a charm, and kept me from cluttering up the test with a ton of code to construct the complex objects that would have been needed.


So, if you're reading and didn't know about this trick, tuck it away for later, and you won't have to admit to the world that you were stumped.

Tuesday, January 25, 2011

Groovy / Grails User Groups

Technology user groups benefit both a technology (with the companies behind it) and its users. Java user groups around the world played a big role in the adoption and advance of the Java language and platform. Even now that Java is in its old age (or on its deathbed, depending on who you talk to), JUGs are actively promoting educational and community-building initiatives.

The Groovy community is benefiting similarly from a growing number of user groups. There are currently a few dozen groups around the world, and more are forming every day.

Now there is a website that can help you find a group in your area or help you get one started. G2Groups.net has a list of active Groovy user groups, with links to their sites. If you can't find one in your area, you can propose one. The site will post a link to your proposal on Twitter; you can retweet this to help get the word out. Then when others are interested in your idea, you'll get emailed about it, and you're off and running!

Once you get a few likeminded (and by "likeminded," I of course mean "brilliant") people together and get a group started, send me a note, and I'll invite you to the Groovy User Group Leaders list on Google Groups. This list is a great way to get support and ideas from other Groovy/Grails/Griffon/Gaelyk/Gradle/Getc. group leaders.

I've always said that the best feature of Groovy and Grails is the community. User groups are a big part of that. So if you're not already involved in a G2Group, get plugged in. You'll be glad you did.

Wednesday, April 7, 2010

ÜberConf

I am very excited about the upcoming ÜberConf - June 14 - 17, Denver, CO. Even before I found out that I'd be speaking at it, I was planning to attend. I've been to a lot of conferences, and I think this is going to be the best one ever!

I've been attending technical conferences for over 15 years. I've been to big ones and small ones, free ones and expensive ones. Just doing a quick count in my head, I think I've been to around 35 tech events. Most of these have been as an attendee and on my own dime, because I am convinced of their usefulness and value. More recently I've been speaking at some conferences. Over the years I've become somewhat of a tech conference connoisseur.

Of all these events, the best have been the ones put on by Jay Zimmerman of No Fluff, Just Stuff fame. The NFJS events and others, such as the Groovy/Grails Experience, the Agile IT Experience and SpringOne/2GX, have some elements that other conference organizers just can't seem to duplicate. CodeMash comes close, and the old Borland Developer Conferences were also pretty good, but neither of these are quite up to the level of an NFJS event.

JavaOne used to score real high on the technical content before it became JavaFX One, but the conference organization and overall experience was always lacking. The SD conferences usually had some big names that were worth the price of admission, but the rest of the sessions were hit and miss, and the mobs that were there just for the free expo floor made it so difficult to get to sessions that it often wasn't worth it.

The NFJS events have speakers who are well known, though maybe not as famous as some of the SD headliners. More importantly, they know their stuff, and they have tons of experience in presenting it to others. And since the event size is purposely kept small, it's easy to get to the sessions of interest and easy to get time to talk with the speakers. The schedule is always arranged with plenty of break time for the hallway discussions and questions after the sessions. And all of the little details that we don't really notice but that provide for a much better learning experience are taken care of.

But back to ÜberConf. This event will, I'm sure, have the quality experience and flawless execution common to all NFJS events, but with an expanded focus, expanded schedule and an amazing line-up of speakers (and me too :).

ÜberConf's technical content will be what JavaOne should have been over the last couple years. It will fully embrace Java the platform, with sessions on Java, Groovy, JRuby, Clojure and Scala. ÜberConf goes beyond just the languages and draws from the rich diversity of open source communities that have found a home on the JVM, with Grails, Wicket, Gradle, Maven, Gaelyk, Camel, and more. And since what we're developing with is only part of the story, ÜberConf goes on to bring together some of most important ideas in agile processes from speakers such as Esther Derby, Johanna Rothman, David Hussman, Michael Nygard, and others.

With a mix of 90 minute sessions and 3 hour workshops, and eight concurrent tracks to choose from, ÜberConf will be packed with great content. With attendance capped at 500, it will be easy to get time to talk with speakers and other attendees - and getting to and from the sessions will be easy.

I speak from experience when I say that you will leave this conference full of new ideas and inspiration. Check out the schedule. You'll find plenty of sessions that apply to your current work, but don't stop there. To get the most out of an event like this, you need to go to sessions about topics you know nothing about. You will be amazed at how much you can learn about what you are currently doing by learning about new tools and technologies.

Check out the site for details. There's much more than I've discussed here, including sessions on iPhone, iPad and Android development. For what's included, the full registration price is a steal, but if you register by Monday, April 12th, there's a big discount. So register now, or register later, but do register and attend this awesome conference.

See you there!

Friday, February 5, 2010

My Favorite Tool

Years ago, I worked in construction, building houses. My favorite tool was my Estwing 28oz. waffle-headed framing hammer. I could drive a 16d nail in one hit with that hammer. (I also got carpal tunnel syndrome from using that hammer. But that's a different story.)

That hammer, because of its characteristics (its weight, its size, the pattern on its face, its textured grip, etc.), allowed me to do what I needed to do. Beyond that, it made it easier for me to do what I needed to do. No actually, that's not quite accurate.

The hammer didn't help me do what I needed to do. It helped me to do what I chose to do. In general, I chose to do what I needed to do, but the hammer played no part in that. I had a good boss on that job, and he helped me to determine what I needed to do. I also worked with some very experienced carpenters on that job, and they helped me to learn the right way to do what I needed to do. All the while, my trusty hammer was there just making things easier.

Not all of the tools I used were that way. My circular saw had a safety guard on it that made it difficult to see where I was cutting, and it got in the way when first starting a cut. It would then slide away as I went, but I would often hold it back out of the way when I was starting. The more experienced carpenters just removed their safety guards altogether. I'm sure there were accidents that the safety guards would have prevented, but I guess they were rare enough that most folks decided that the productivity gains were worth the risk. I was always amazed at how fast those guys could frame a house!

I used my saw because I needed to use it, and it was much faster than using a hand saw, but I don't look back at my saw with the same fondness as that hammer. In fact, I can't even remember what brand or model it was. There's just something about a tool that feels good to use: a tool that helps you do what you want to do, and then just stays out of your way.

Tuesday, October 27, 2009

Yet Another 2GX Wrap-up

Finally after more than a year of waiting and nagging, the second 2GX conference was held in New Orleans last week. It was almost as good as the first one. Well, in some ways it was better but in other ways... well, we'll get to that in a bit. But first, I wanted to say how great it was to see so many people from the Groovy community. It is so cool to be able to put real faces to so many on-line friends. I know conference people always say that "the attendees are what really makes the conference great", but as a speaker and part-time staff member at this conference, I can say that it's really true. The questions during the sessions and the discussions between sessions and at meals were the best part of the whole thing. Even better than the Rod Johnson bobble-head dolls. :-)

Speaking of staff, I also want to tip my hat (if I had one) to the guys that pulled it all off. Jay Zimmerman did as good of a job with the 500+ person event as he does with the NoFluffJustStuff conferences and his two volunteers (and one sales guy :), and my co-workers, Erik Weibust, Todd Crone, and Paul Luttrell were tireless in their efforts to keep things running smoothly. It was great working with you guys!

One thing I want to highlight here was how excited I was to see some relative new comers speaking at 2GX. These guys aren't new to Groovy or Grails, but I think this was the first conference appearance for each of them and they were awesome! Matt Taylor, Hamlet D'arcy, Scott Vlaminck (the 'n' is silent), and Burt Beckwith (actually I'm not sure if Burt has spoken at other conferences, so forgive me if I'm wrong)

Matt spoke on Grails UI, the YUI based Grails plugin that he developed and maintains as well as his experiences using Grails "in the wild". I caught his GrailsUI talk and was very impressed, along with the rest of the room who all gave him the coveted "green cards".

I didn't catch any of Hamlet's sessions but from what I heard from other attendees and on Twitter, he was a hit! He gave four presentations altogether: OSGi and Groovy, Functional Groovy, Compiler Metaprogramming with AST transformations, and Legacy Code and Groovy. Rumor has it that he even had Venkat Subramaniam impressed.

Scott Vlaminck, from Refactr, gave talks on Metaprogramming in Groovy and Grails, and AOP in Grails. Again, I wasn't able to catch any of these talks in person, but the feedback was quite good and in fact I happened to be in the room next to one of Scott's talks and the speaker was almost drowned out by the applause!

Burt also gave four presentations. He spoke on Spring Security in Grails, GORM performance, UI performance, and Clustering Grails apps. I only caught the GORM performance talk, but it was one of my favorites. I am already putting things I learned there to use in my day job.

Of course the usual awesome Groovy/Grails/Griffon speakers were there and they were terrific as usual, but you've already heard about them and many others have or will blog about the cool Griffon sessions, or the Grails internals, or the power of Grails plugins, or the DSLs and Groovy testing magic, etc. So I wanted to take a moment to congratulate these guys on a job well done. I look forward to seeing them present at future events.

Now, as to why I don't think this 2GX was quite as good as the first one. The full name of the conference is a clue: SpringOne 2GX. SpringOne is a good conference, but 2GX is a great conference! (or a GR8 conference :) So, when combined we ended up with a more than good but not quite great conference. Spring technology is cool. Much of it (though not all) is behind some of the power of Grails. And I do very much appreciate the support that SpringSource is giving to Groovy and Grails, but I think they just gave a bit of a "corporate feel" to the conference.

I don't want to end on a downer though. There were some distinct benefits of having the two events combined. One was that SpringOne had some very good content and some exceptional speakers to add to the mix. Another is that more than a few Spring users got to glimpse the goodness of Groovy, Grails and Griffon for the first time. The oohs and ahhs were music to my ears! It serves as a reminder to just be patient and hang in there... it's only a matter of time until they'll be holding the Groovy, Grails, Griffon and Spring conference!

Wednesday, September 16, 2009

10 Reasons to attend SpringOne 2GX

I was going to come up with one of those clever top 10 lists but when I went to the SpringOne/2GX home page, I saw 10 great reasons to attend staring me in the face.



The early bird discount ends Friday, September 18th, but even at full price this event is less expensive than JavaOne and will contain way more good technical content. Check out the rest of the speakers and the awesome session list at http://springone2gx.com

If you're interested in Groovy, Grails, Griffon, (or related technologies) or if you use Spring in any of it's myriad forms, or, for that matter, if you use Java, you won't want to miss this conference!

See you there!

Thursday, July 23, 2009

We have a US Groovy/Grails/Griffon Conference!

But let's not blow it!

A while back I wrote about the need for a US conference dedicated to the G3 technologies. Well, now there's one scheduled! You've probably already heard about the SpringOne 2GX (I know it should be 3GX, but names are hard to change sometimes, so we'll cut them some slack :-).

This conference will be a two-for-one deal. You can sign up for either the SpringOne or the 2GX (Groovy / Grails Experience) and you get to go to both. Which means that there will be 8 concurrent sessions to choose from. Ouch! That's going to hurt when I try to split myself into pieces to go to more than one at a time.

The speaker line-up is fantastic. I won't try to list all of them all here, but the three Gs are well represented, with 20 different speakers on the Groovy / Grails / Griffon side and even more on the Spring side. You can see the full list on the website.

But the sessions are only part of the picture. The interaction with speakers and other attendees during breaks and meals is the part that just can't be reproduced or replaced. You may be able to find a book that covers some of the topics, but you won't find a book that contains that great conversation you had with the creator of your favorite tool or framework.

So why did I start this post off with the warning to not blow it? Well, you may have noticed that the economy isn't doing all that great lately. You may have also noticed that many conferences and training events have been canceled due to lack of attendance. I don't think that would happen with the SpringOne 2GX -- but why take the chance? If we want these types of events to continue, we need to support them. So if you haven't registered yet, head over to http://springone2gx.com and register. The early bird pricing, which will save you $400, ends July 31st! Why wait? You can save a good chunk of change while at the same time telling the organizers that they might as well start planning the next one!

You can also help by getting the word out. Tell your co-workers, colleagues, friends, neighbors, etc.

This is going to be an excellent conference. It will be way less crowded than JavaOne, and with much better sessions and overall experience. And it's cheaper to boot! There's just no good reason to miss this event. I hope to see you there!

Tuesday, June 30, 2009

It's Official: Grails has a DZone Refcard!

The Grails Refcard is now available for download at http://refcardz.dzone.com

Writing a refcard was a bit more challenging than I thought it would be. The main difficulty being determining what it should have in it. I put the question out here and on the Grails mailing lists and got some good ideas but no help in narrowing it down. Should it be solely a reference for experienced Grails users? An easy getting started guide for new Grails users? Should it just be a copy of the docs in a smaller font?!

I leaned more towards it being a reference for existing users but I know there are still many poor souls out there who don't yet know how much better their jobs could be with Grails. So, I settled on a hybrid approach. The first section is a brief introduction to Grails and some of it's key benefits. I could have done so much more here but hopefully it's enough to convince those not yet using Grails to take a second look. The rest of the card is dedicated to some of the concepts and details that I and others I know of have had to lookup most frequently. I know I didn't hit everyone's key points but hopefully I covered enough of them to make it useful.

Download it and take a look. The download is free and feedback is always welcome.

I would like to thank the folks at DZone for giving me this opportunity and even more for their support of the G3 community with first the Groovy Refcard and now the Grails Refcard. There's no Griffon Refcard yet, but they do listen so send them an email to let them know you'd like to see one or better yet, offer to write it. It's a fun and challenging experience.

Tuesday, June 2, 2009

Groovy Buzz at JavaOne

As suspected the G3 buzz at JavaOne is much higher than indicated by the technical session list.  You hear it in the hallway conversations; you hear it in the attendees questions at other sessions; and you heard it loud and clear at the Scripting Bowl (aka, the Alternative JVM Languages Bowl).  The contenders were Jython, Groovy, Clojure, Scala and JRuby.  The clear winner was Groovy!  Dick Wall, of Java Posse fame, came in second with Scala but based on audience feedback Groovy was the one!  

Guillaume Laforge was the Groovy representative and he showed off some cool demos with help from the grooviest guys in desktop development, Danno Ferrin, James Williams and Andres Almiray.  It was a great community effort and a great opportunity to show folks how powerful, easy to use and just plain fun Groovy is.

Wednesday, April 29, 2009

We need a US Groovy/Grails/Griffon Conference

It's been over a year since the best conference I've ever attended. The Groovy/Grails Experience was held in February 2008 near Washington DC. It was an awesome experience. For the nostalgic and those with too much time on their hands you can read my review of it here.

But we are way overdue for another. The folks that put that conference together, Jay Zimmerman and Scott Davis, both heroes of mine, tried to organize another but when the economy took a turn for the worse they decided to hold off. I understand their concerns. One only has to look at the desperate attempts at drawing attendees the JavaOne organizers are going through to realize that this is a tough climate for conferences. But hey we're talking about Groovy, Grails and Griffon here.

These are technologies that transcend tumultuous times.
While other conferences are being scaled back or cancelled, The GR8 conference, dedicated to G3 technologies, has had to move to a larger venue! And from what I've heard, the turnouts at the growing number of Groovy and Grails training classes haven't been too shabby. The G3 user group community continues to grow. The Grails podcast audience is climbing. We even have a G3 dedicated magazine. We are ready for a G3 Experience.

So, what are we going to do about it? We could get together and put one on ourselves but I still have faith in Jay and Scott. Anyone who has been to a NoFluffJustStuff or related conference knows that nobody does it better. So, let's let them know that it's time. Here's a few steps you can take:

  • Go to the 2GX website: http://groovygrails.com/gg/2gexperience and use the form there to register your interest.

  • Go to the NoFluffJustStuff feedback form and tell them it's time. You can even plead for your favorite city.

  • Send Jay and/or Scott an email (I'll leave it as an exercise for the reader to track down their email addresses)

  • Repeat this urgent plea on mailing lists, news groups, forums, at user groups, at work, in letters to the editor, etc.

  • Finally, if you are attending an upcoming NFJS event (coming to Atlanta, Denver, Dallas, Columbus) tell Jay or Scott that it's time for another G3 Experience.


Let's get to work, we can make it happen. After all, we are the G3 community. It's not like we're a bunch of (insert your favorite inferior language or technology here) hackers!

I'll see you at the next G3 Experience!

Tuesday, April 28, 2009

Linux Journal Readers Choice Awards

Well the votes are in and Groovy didn't get enough votes to get mentioned in the Linux Journal's Readers Choice awards.  The winner for favorite programming language was Python and favorite scripting language was bash (go figure :)  But I know that many Groovy users registered their votes in the "other" category so I wouldn't be surprised if next year we're at least on the list.  In fact as evidence that a write in one year can do well the following year, I am thrilled to announce that Contegix won the Readers Choice Award for Favorite Linux Friendly Web Hosting Company!  A quote from the article: "Talk about a meteoric rise, Contegix went from one write-in vote in 2008 to champion of the Favorite Linux-Friendly Web Hosting Company category in 2009."   

Since I have only been working for Contegix since last October, I don't feel like I can take any credit for this big win, but I am still thrilled because I can see how much they deserved it.  I have never worked with a more dedicated and sharp team of technologists.  It is an honor to be among them and I hope I can do my part to help win this award again next year.

But back to Groovy, the key point here is that last year Contegix was just a write in!  This year Groovy was just a write in...  Just wait till next year!   In the meantime, thank you to all you who voted for Groovy and for Contegix!

Sunday, March 1, 2009

Thoughts on Groovy, Grails, Griffon and JavaOne

You may have already heard that Groovy, Grails and Griffon are going to be under-represented at this year's JavaOne. While this is a bummer and hard to understand in the face of the enthusiasm that continues to grow in the community (see below for some examples), I don't think the right reaction is to say "who needs them" and skip JavaOne altogether. One idea Graeme Rocher mentioned on Twitter is a good one: a G3 mini conference would be great! The Monday night before JavaOne kicks off would be a perfect time for that.

Anyhow, it's important to note that last year there weren't all that many Groovy related talks either, but what I observed was that Groovy was represented as much by excited attendees as by presenters. I think it can be the same this year. Some of the brightest minds in the G3 community will be at JavaOne and they will have many opportunities outside of the session rooms, to talk about and demonstrate the power, efficiency and fun of Groovy, Grails and Griffon. The rest of us can do the same. So if you can make it to JavaOne go for it and feel the Groovy in the air!

Speaking of enthusiasm in the community, here are a few examples:

Here's a screenshot of the DZone popular link tab for 3/01/2008


This is one of my favorites, from a Sun blog.



This one is from the Stephen Colbourne's blog and shows the results of a whiteboard poll at Devoxx, a European conference that is very similar to JavaOne.

So don't be discouraged- the better mousetrap is doing all right!

Saturday, February 28, 2009

First NoFluffJustStuff of the year

It's finally here. The first NFJS of 2009! I'm sitting in Scott Davis' "Dim Sum Grails" session right now. Yesterday Scott had three brand new Groovy talks. They were very good. He's moving beyond the "what is Groovy" and into some really cool stuff. All, of course, in his award winning style!

There are also new sessions from Neal Ford, David Geary, Ken Sipe, Venkat Subramaniam, Mark Richards, Stuart Halloway and Brain Goetz. Since I haven't mastered the art of being in two places at once I will pretty much be in the Scott Davis track and then the Brian Goetz track.

I'll try to post more later. For now back to the dim sum!

Tuesday, November 11, 2008

Congratulations to SpringSource!

It looks like SpringSource has their answer to JBoss Seam, and what an answer it is!  There are all kinds of aspects and angles to SpringSource's recently announced acquisition of G2One, the company behind Groovy and Grails, but this one struck me right off the bat.  

While Groovy will give new energy to the entire Spring portfolio, Grails, specifically, will help round out their competitive position vis a vis RedHat.  In recent demos at our Java User Group and at JavaOne, it appears that RedHat is using Seam to draw people into their whole platform.  And until now, SpringSource hasn't had a direct answer to that.   Not only will they have a framework that competes with Seam, but they will have one that blows it out of the water!  Don't get me wrong, Seam is heading in the right direction and with the eventual advent of JSF 2.0 it will get even better, but it is no where near as productive, effective or awesome as Grails.

Over the next several days, we will probably be hearing a lot about what this acquisition means to the future of Groovy and Grails.  I think, overall, it will be a major positive in that regard.  But, I think the real winner is SpringSource.   Congratulations to Rod Johnson and the gang for once again jumping ahead of the curve!

Tuesday, August 26, 2008

BGG takes top honors at CapJug Meeting!

Last week at the August meeting of the Capital Java User Group, we had several excellent books to give away. Apress had sent us a copy of Beginning Groovy and Grails: From Novice to Professional, which Shawn Hartsock has dubbed "BGG". The Pragmatic Programmers sent us several of their recent titles (special thanks to Jared Richardson, author of one of my favorites: Ship It!) and we had one left from an earlier supply from O'Reilly.

When we have this many books to give out we like to treat it like a poll. So, I'll describe each of the books and then start drawing names. Each winner can take their pick from the books remaining. I am happy to announce that Beginning Groovy and Grails was the first pick! Congratulations to Christopher, Joseph and James! The CapJug pick of the months is quite an honor. We still have another copy to give away next month so we'll see if they can hold the record for a second month.

It is great to see the growing interest and excitement in Groovy and Grails at our Java User Group and I know that ours is not unique. Java User Groups all over the world are beginning to embrace the next generation of Java!

Wednesday, June 11, 2008

Grails to the Rescue

Everyone in software development knows what a death march is but not as many are familiar with a forlorn hope. The term comes from the time when wars were fought over fortresses or walled cities. Cannons were used to make a breach in the walls big enough to send troops into. Needless to say, the first troops to go into those breaches did not fare well. So, the first unit to be sent in became known as a forlorn hope. It was often a volunteer unit with the promise of fame, glory and military advancement for those that survived.

I've read and heard about death march software projects before but I had never experienced one until recently. About a month ago I was put in charge of a 2 1/2 year JSF/EJB project that had 8 months left and was less than half done. (By the way, that's my excuse for not blogging in a while. It's not as good as Glen Smith's excuse but it's all I've got) At first this was quite disheartening. I assessed the situation and made it clear that there was no way that we could meet the deadline but was told to just "do the best we could". So, I marched on...

Then, as I dug into the project more, I discovered that there were major pieces of the application that were isolated enough that they could be done in a different environment without impacting the overall system. Grails to the rescue. We are now using Grails for most of the remaining development and gaining momentum quickly. Two of the four of us on this team have Grails experience but the other two are coming up to speed very quickly and, I might add, enjoying their jobs more than they have for some time. One of the pleasant side effects of using Groovy and Grails is increased job satisfaction and motivation.

While there's still much to do and it is still unlikely that we will make that deadline, switching from JSF/EJB to Grails has turned this death march into a forlorn hope. In this case the reward won't be fame, glory and promotion but it just might be another IT shop standardizing on Groovy and Grails. Here's hoping!

Saturday, May 17, 2008

Introducing JugList.net

As part of a homeschool project and a way to try out their budding Groovy & Grails development skills, two of my sons, Zak and Ben, have been working on a website. Their creation is now up and running and you can see it at www.juglist.net

JugList.Net is a searchable directory of Java User Groups around the world.


You can search for a JUG (Java User Group) by name, city, state/province or country. If you still can't find a JUG in your area, there is a link to an article, by yours truly, that gives some tips on starting your own group.

Java User Groups are a valuable resource for honing your craft and building your career. They also provide a great way for experienced programmers to give a little back to the community. If you are not involved in a JUG yet, then check out juglist.net and find one near you.

Friday, May 16, 2008

Another way to use Groovy in the Enterprise

Another great way to incorporate Groovy into your enterprise Java projects is Groovy SQL. GSql makes JDBC access so easy and Groovy's seamless Java integration and dynamic nature provides for some interesting ways to take advantage of it.

In this example we'll build a utility class that will use convention to turn an SQL select statement into a List of data transfer objects.

Our goal here is to take an SQL statement and a Class, execute that statement and use the results to populate instances of the Class. We will assume the convention of camel case for object properties and underscores for database fields, so that a field called LAST_NAME would be mapped to a property called lastName. We will also assume that the select statement will only return fields that have a corresponding property in the Class.

So let's see what this might look like:

static Collection getData(String query, Class clazz, Connection con){
def field = ''
def result = []
def sql = new Sql(con)
sql.rows(query).each {row ->
def dto = clazz.newInstance()
row.keySet().each{
field = toCamelCase(it)
dto."${field}" = row."${it}"
}
result << dto
}
result
}


After defining a few variables, we create our groovy.sql.Sql object using the constructor that takes a Connection. This will allow us to use Connections provided by an application server such as WebLogic or WebSphere. We could easily change this method to take advantage of the other constructors.

Next we'll call the rows method of the Sql class, which will execute the SQL statement and return an ArrayList of GroovyRowResults. Now we'll iterate through this ArrayList and create a new instance of our DTO class for each row. GroovyRowResult implements the Map interface so we can loop through its keys with row.keySet().each. This will give us each of the fields in that row and we will turn them into property names with a call to the toCamelCase() method (which we'll look at shortly). Notice how we take advantage of GStrings to dynamically access properties of our DTO as well as keys of the row map. After we assign each of the fields in the row to properties of the DTO instance we add it to the result List. When the loop is done we just return the List. Obviously, more can be done to make this more robust and more flexible, but it's pretty amazing how easy it was to build a Groovy class that can replace tons of repetitive Java code.

Let's take a look at how we could use this class from a Java project:

...
Connection con = getConnectionFromPool();
String query = "SELECT FIRST_NAME, LAST_NAME, EMAIL FROM MEMBER";
Collection members = GroovyData.getData(query, MemberDTO.class, con);
...

That's all there is to it.

Now let's take a quick look at the toCamelCase() method we mentioned above. This doesn't directly have anything to do with the purpose of this post, but I am hoping that someone might see this and offer a groovier way to do the same thing. Basically the goal is to take a database field name such as LAST_NAME and turn it into a camelCase string like lastName. Here's how I did it:

static String toCamelCase(String val){
def sb = new StringBuffer()
Boolean newWord = false
val.toLowerCase().each{
if (it == '_')
newWord = true
else{
if (newWord){
newWord = false
sb << it.toUpperCase()
}
else
sb << it
}
}
sb.toString()
}

I was sure there was a groovier way to do this and, sure enough, Andres Almiray came up with this awesome improvement:

static String toCamelCase(String val){
def result = val.split("_").collect { word ->
word[0].toUpperCase() + word[1..-1].toLowerCase()
}.join("")
result[0].toLowerCase() + result[1..-1]
}

Thanks Andres! And if that wasn't groovy enough, Ted Naleid came up with this cool mix of regular expressions and meta-programming. Good stuff Ted!

def camelCaseConverter(orig) {
orig.toLowerCase().replaceAll(/_(\w)?/) { wholeMatch, firstLetter ->
firstLetter?.toUpperCase() ?: ""
}
}

String.metaClass.toCamelCase = {->
camelCaseConverter(delegate)
}

Thursday, May 1, 2008

Groovy and Grails at JavaOne

It's less than a week until JavaOne 2008! It is going to be an exciting week packed full of brain stretching content. There will be technical sessions, birds of a feather sessions, panels, keynotes, etc. on just about everything having anything to do with Java. But most importantly, there will be a bunch of Groovy and Grails related sessions. Starting with Jeff Brown's Grails presentation at Community One on Monday, followed by the G2One / NoFluffJustStuff gala Monday evening at the W Hotel.

Then for the rest of the week a groovy search in the Content Catalog turned up the following list:

ID

Session Title

Speaker(s)

Date / Time

Room

TS-5771

The Duke and the Elephant: PHP Meets Java™ Technology--the Best of Both Worlds

Rob Nicholson, IBM

Tuesday
05/06/2008
10:50 AM -11:50 AM

Esplanade 301

TS-5764

Grails in Depth

Guillaume Laforge, G2One, Inc., Graeme Rocher, G2One Inc

Tuesday
05/06/2008
6:00 PM -7:00 PM

Esplanade 307-310

BOF-5613

Jersey: RESTful Web Services Made Easy

Jakub Podlesak, Sun Microsystems
Paul Sandoz, Sun Microsystems, Inc.


Tuesday
05/06/2008
8:30 PM -9:20 PM

Esplanade 307-310

PAN-5435

The Script Bowl: A Rapid-Fire Comparison of Scripting Languages

Guillaume Laforge, G2One, Inc., Charles Nutter, Sun Microsystems, Inc., Jorge Ortiz, Stanford, Raghavan Srinivas, Sun Microsystems, Inc.,
Frank Wierzbicki, Sun Microsystems


Wednesday
05/07/2008
9:30 AM -10:30 AM

Gateway 104

TS-5572


Groovy, the Red Pill: Metaprogramming--How to Blow the Mind of Developers on the Java™ Platform

Scott Davis, Davisworld Consulting, Inc.

Wednesday
05/07/2008
9:30 AM -10:30 AM

North Mtg-121/122/124/125

TS-5815

Going Mobile with JavaFX™ Script Technology, Groovy, and Google Android

Mike Mannion, Canoo Engineering AG

Wednesday
05/07/2008
10:50 AM -11:50 AM

Esplanade 301

TS-6050

Comparing JRuby and Groovy

Neal Ford, ThoughtWorks Inc.

Wednesday
05/07/2008
1:30 PM -2:30 PM

North Mtg-121/122/124/125

TS-5274

Groovy on a Cloud: Testing Java™ Platform, Enterprise Edition (Java EE Platform) Applications on Amazon EC2

Chris Richardson, Chris Richardson Consulting, Inc.

Wednesday
05/07/2008
4:10 PM -5:10 PM

Gateway 104

TS-6213

Boldly Go Where the Java™ Programming Language Has Never Gone Before

Geert Bevin, Terracotta

Wednesday
05/07/2008
4:10 PM -5:10 PM

North Mtg-121/122/124/125

BOF-5102

Cooking Your Own Groovy Builder: A Step Forward into Domain-Specific Languages

Andres Almiray, Oracle, Ixchel Ruiz, Clemente Camara y Asociados

Wednesday
05/07/2008
8:30 PM -9:20 PM

Gateway 104

BOF-5110

Extending Groovy’s Swing User Interface in Builder to Build Richer Applications

Danno Ferrin, Intelligent Software Solutions, Inc., James Williams, Spatial Networks

Wednesday
05/07/2008
8:30 PM -9:20 PM

Hall E 133

TS-5793

Groovy and Grails: Changing the Landscape of Java™ Platform, Enterprise Edition (Java EE Platform) Patterns

Guillaume Laforge, G2One, Inc., Graeme Rocher, G2One Inc

Thursday
05/08/2008
9:30 AM -10:30 AM

North Mtg-121/122/124/125

TS-5693

Writing Your Own JSR-Compliant, Domain-Specific Scripting Language

John Colosi, VeriSign, Inc.; David Smith, VeriSign Inc.

Thursday
05/08/2008
1:30 PM -2:30 PM

Esplanade 301

TS-6457


Choosing Your Java™ Technology-Based Web Framework: A Comparison

Richard Pack, Hyperic; Stacey Schneider, Hyperic

Thursday
05/08/2008
2:50 PM -3:50 PM

Esplanade 307-310

TS-6606

Patterns for Integrating Java™ and JavaScript™ Technology: Tales from the Front Lines

David Caldwell, David P. Caldwell, Inc.

Thursday
05/08/2008
2:50 PM -3:50 PM

North Mtg-121/122/124/125

BOF-5101

Boosting Your Testing Productivity with Groovy

Andres Almiray, Oracle;, James Williams, Spatial Networks

Thursday
05/08/2008
7:30 PM -8:20 PM

Gateway 102/103

TS-5098

Building Rich Applications with Groovy's SwingBuilder

Andres Almiray, Oracle;, Danno Ferrin, Intelligent Software Solutions, Inc.

Friday
05/09/2008
12:10 PM -1:10 PM

Esplanade 305

TS-6050

Comparing JRuby and Groovy

Neal Ford, ThoughtWorks Inc.

Friday
05/09/2008
1:30 PM -2:30 PM

Esplanade 303

TS-6039

Jython - Implementing Dynamic Language Features for the Java™ Platform Ecosystem

Jim Baker, Zyasoft, Tobias Ivarsson, Neo Technology

Friday
05/09/2008
2:50 PM -3:50 PM

Esplanade 305



Well, if you read this far and if you happen to be wandering around the Pavillion on Tuesday afternoon at 3:30, I will be giving a mini-talk on Java User Groups at the java.net Community Corner. (That way I can say that I gave a presentation at JavaOne).

Monday, April 14, 2008

NoFluffJustStuff JUG Events

I was just at nofluffjuststuff.com and I noticed this impressive list of Java User Group events coming up:

Apr. 15 - Omaha, NE - Eclipse Plugin Development at OJUG - Omaha Java Users Group
Apr. 21 - Durham, NC - Groovin Builds Gant Get Any Easier at Triangle Java Users Group
Apr. 24 - New York, NY - Give It a REST at New York Java Sig
Apr. 30 - Houston, TX - Design Patterns in Dynamic Languages at Houston Java Users Group
May. 14 - Dallas, TX - 10 Ways to Improve Your Code at JavaMUG
May. 15 - Salt Lake City, UT - Thorough Introduction to Groovy at Utah Java Users Group
Jun. 11 - Calgary, AB - Core Groovy at Calgary Java Users Group
Jun. 11 - Dallas, Texas - Grails - Agile Web 2.0 The Easy Way at JavaMUG

As the leader of a JUG (Capital Java User Group - Madison, WI) I appreciate all the support that the folks at NoFluffJustStuff provide to the Java community. As a Groovy / Grails developer, I also appreciate the way that they are helping to usher in the next generation of Java!