Archive for February, 2009

easyb satiation this May 7th and 8th

easyb quenches your thirstA disconnect between the stakeholders who define requirements and the developers who implement them has long plagued software development, baby. In recent years, frameworks based on dynamic languages (like Groovy and Ruby) and domain-specific languages have come a long way in bridging this stakeholder-developer gap by making code read more like normal language. One such framework is easyb, which enables teams to collaboratively verify behavior of Java (and Groovy!) applications in a more natural way.

This May 7th and 8th in Reston, Virginia, I am delighted to offer a 2 day hands on course focusing on BDD with easyb. This hip course features 16 hands-on workshops where you’ll understand the benefits of collaborative stories implemented with easyb and how this framework makes collaboration easy (and fun!). You’ll learn how to validate applications in the style of Test Driven Development (TDD) that facilitates mocking, user acceptance testing with Selenium, database dataset management with DbUnit and even ascertaining code coverage.

Throughout the program, you’ll be challenged with lab exercises that’ll drive home various techniques of Behavior Driven Development with easyb along with tools and related processes. You’ll verify Java code as well as web applications and leverage a bevy of tools including Selenium, DbUnit, and various mocking libraries and techniques. What’s more, you will learn how to combine these tools in an effort to create highly structured deep verification assets that exercise applications from a micro level to a macro level.

Regardless if you’re a developer or a tester and regardless of your experience with BDD and easyb you’re bound to learn something new and exciting in this course. Ultimately, by applying a more collaborative platform in your software projects, you’ll produce better code more quickly. So what are you waiting for? Sign up today while there is still room!

Book review: Groovy Recipes

While Groovy can found existing in one jar file, it is a large platform with a plethora of features and tricks. In fact, Groovy in Action (for which I had the pleasure of participating in) weighed in at almost 700 pages. Consequently, Scott Davis’s Groovy Recipes: Greasing the Wheels of Java is a handy light-weight (roughly 250 pages) reference bag of tricks suitable for any Groovy developer’s desk (beginner to expert, baby).

Scott starts out answering the questions any beginner would ask — for example — how to use groovysh, groovyc, Groovy with IDEA (my preferred IDE!). He then proceeds to explain the core of Groovy — the syntax magic, operator overloading, and native collections to name a few goodies. Chapter 4 is particularly hip as it covers the tight relationship Groovy shares with Java, which always comes up when bringing the good news of Groovy to Java developers.

Scott spends two chapters covering XML — both parsing and creating it. If you haven’t seen Groovy’s XMLSlurper in action, you are in for a real doozy, baby! After that, Scott covers file tricks, the command line, and web services in Groovy– something that I’ve fully embraced Grails for. By far, my favorite chapter though is chapter 10 — Metaprogramming — which exposes the magic behind everyone’s favorite web framework: Grails. Metaprogramming is where Groovy really shines and this chapter is bound to wow a few hip souls.

The book finishes up with two chapters focused on Grails– while there are entire books written on the aforementioned subject, Grails can be covered at such a high-level quite nicely. In fact, in chapter 11 alone, you’ll have a working Grails application up and running!

All in all, my friend Scott does a wonderful job of distilling what’s a large copasetic platform into a practical bag of tricks appropriate for Java developers looking to jump into Groovy and even those in the Groovy community that need a quick reference nearby.

RESTful Grails services in 3 steps

Leonardo da Vinci once mused:

simplicity is the ultimate sophistication

REST embodies this thought and thus yields highly scalable, loosely coupled systems that, as it turns out, are simple to build, baby! There are a few mechanisms for implementing RESTful applications– Restlets and JSR 311 are two in a handful of options available in Java; however, they address one aspect of RESTful applications and ignore other aspects like an ORM and testing. Groovy’s Grails gives you the ability to apply RESTful techniques with a full fleged web application framework that supports an ORM and testing to boot! As you’ll see, using Groovy’s Grails framework makes building RESTful Web services a snap — in 3 steps, in fact.full stack, baby!

Briefly, the three steps are:

  • Create domain objects
  • Update URL mappings
  • Create one or more controllers to handle RESTful requests and responses

Say for instance, you’d like to create a RESTful web service that enables runners to sign up for races. In this context, imagine a company (foo) that provides the management platform that facilitates putting on races and other organizations (bar, etc) then create races (for which the first organization, foo, puts on). The management company will accordingly construct a web service that enables organizations to:

  • create races
  • associate runners with those races

Accordingly, the first step is to create two domain objects — a Race and a Runner.

Hip domain objects in Grails are indubitably easy to create as there is little to no boiler plate code. For instance, my Race object, minimally speaking, has three properties — a name, a distance, and a collection of associated runners.

class Race {
 String name
 double distance

 static hasMany = [runners:Runner]
}

As you can see, properties inherent to a domain object are simply declared as normal properties (i.e. String name) and relationships are handled by GORM‘s hasMany syntax, which states there is a runners property (a collection) that contains instances of Runner.

Next, my Runner domain object is similarly coded; however, in this case, I’ve stipulated that runner’s must be at least 13 in order to be eligible.

class Runner {
 static constraints = {
  age(min:13)
 }

 String firstName
 String lastName
 int age

 static belongsTo = Race
}

Note too how in GORM, I can make a relationship bi-directional by specifying a Runner instance belongs to a related Race via the belongsTo syntax.

The second step involves manipulating Grail’s URL mappings so as to expose my desired behavior in a more RESTful manner. Because REST relies on named resources rather than messages, it easily facilitates loose coupling when designing applications. As everything on the web, in essence, is a resource (think web pages, images, etc), REST’s reliance on resources limits the exposure of the underlying technology involved.

For instance, the following URL exposes a resource without implying anything about the underlying technology involved

http://thediscoblog.com/2008/03/20/unambiguously-analyzing-metrics/

As you can see, baby, there is a resource represented here– in this case an article called “Unambiguously analyzing metrics.” Notice how the URL is also noun based rather than verb based (which would look something like getArticle?name=blahblah). What’s more, requesting this resource leverages the HTTP GET command– one could also imagine posting a new resource (i.e. article) via HTTP’s POST command (such as http://thediscoblog.com/2008/03/22/rest-is-good-for-you/). Yet, using the same getArticle contrary example from earlier, you can imagine other API’s associated such as createArticle?name=blahblha and deleteArticle?name=blahblah– but in this case these calls are hijacking the HTTP GET command and for the most part, ignoring the already built (and did I say successful?) HTTP infrastructure available!

Thus, making Grail’s URLs more RESTful is done via the UrlMappings class, found in conf directory of a Grails application. In the case of the RESTful races and runners application, the class can be coded like so:

class UrlMappings {
 static mappings = {
  "/$controller/$id?"{
    action = [GET:"show", POST:"save", PUT:"update", DELETE:"remove"]
  }
  "500"(view:'/error')
 }
}

In the code above, I’ve indicated that for any controller in my application, if the HTTP request, for example, is a GET, then Grails should invoke the show closure on that particular controller. Same for POST, PUT, and DELETE.

For instance, because it’s Grail’s bag, if Grails receives an HTTP GET request like www.acmeracing.com/race/165 — Grails will invoke the show closure on the RaceController.

Consequently, the final step in creating a RESTful web service in Grails is to code your controllers — in my case, I’d need two — one for handling races and another for handling runners — conceivably, these could be combined into one logical model as well. For example, my RunnerController is as follows:

import grails.converters.XML

class RunnerController {

 def show = {
  if(params.id && Runner.exists(params.id)){
   render Runner.findById(params.id) as XML
  }else{
   render Runner.list() as XML
  }
 }

 def save = {
  def runner = new Runner(params['runner'])

  if(runner.save()){
   render runner as XML
  }else{
   //handle errors...
  }
 }
}

The show closure is simple (as is the entire class, right, man?) — the id parameter is obtained and consequently a related runner is found; otherwise, all runners are displayed. Note, I’m using Grail’s XML render type, which renders objects in XML logically like so:

<?xml version="1.0" encoding="UTF-8"?>
 <runner>
  <age>20</age>
  <firstName>Mary</firstName>
  <lastName>Smith</lastName>
 </runner>

Note how easy it is to leverage Grail’s XML render — I just have to type render x as XML. I could just as easily, by the way, use Grail’s JSON render as well.

Creating a hip runner is just as easy — in this case, my application is expecting that a posted XML document follow the same structure as I’ve outlined above; thus, I can easily create a new runner instance with one line of code:

def runner = new Runner(params['runner'])

As coded, ‘runner’ is the root element — Grails auto-magically maps everything else for me!

That’s it — 3 steps in short order! First, create your domain objects. Second, create your mapping via the UrlMappings class; finally, code your controller(s) — they can either use XML or JSON — the choice is yours, baby!

Indeed, Grails makes RESTful web service creation a breeze. For as English Poet Alexander Pope once suggested:

There is a certain majesty in simplicity which is far above all the quaintness of wit.

Can you dig, man?

Jump into Groovy and Grails this April

ThirstyHead.comMy good friend Scott Davis (author of The Pragmatic Programmers’ Groovy Recipes
and Mastering Grails among other worthy books and articles) and yours truly have teamed up to offer Groovy and Grails training, baby! In fact, I’ll be conducting a 2 day “Jump into Groovy and Grails” course in Reston, Virginia on April 2nd and 3rd.

This jam-packed hands on course will feature 16 workshops that dive deep into core Groovy and web development with Grails. We’ll cover closures, Groovlets, GroovySQL, the GDK, collections, XML handling, and even metaprogramming on day one; then, we’ll hit all things Grails with GORM, security, controllers, views, mapping legacy databases, and RESTful web services! I can’t think of a more fun filled 2 hip days of pure Groovy indulgence.

Throughout the program, you’ll be challenged with lab exercises that will drive home various techniques of programming in Groovy and leveraging Grails, which will serve to provide an energizing and engaging learning environment, baby! You’ll then be able to leverage what you learn immediately with confidence. Plus, it’ll be the most fun 2 days of your year! So what are you waiting for? Sign up today and I’ll see you in April!

Tim Bray on the future of Java web development

Not long ago, I had the delight of talking with Tim Bray of Sun Microsystems about his thoughts regarding Java web development for JavaWorld’s Java Technology Insider. In this podcast, Tim muses about alternate languages on the JVM, concurrency, cloud computing and REST, just to name a few, man.

Tim is a hip cat (who happens to be the Director of Web Technologies for Sun) and I thoroughly enjoyed listening to his thoughts– I think you’ll also find the conversation interesting, especially if you find yourself building web applications in Java, baby! 

Talkin’ about SpringSource’s acquisition of G2One

Shortly after SpringSource’s November 2008 acquisition of G2One, I had the pleasure of chatting with both Rod Johnson and Graeme Rocher– both gents are always interesting to chat with as they each possess a deep understanding of technology and its applicability with business.

In this JavaWorld podcast, Rod (who I also chatted with in a previous podcast regarding Spring’s dm Server) and Graeme discuss what the acquisition means for Groovy, Grails, and Spring-based developers. Learn what motivated the companies to come together, what you don’t need to fear about the merger, and what developers can expect from Groovy and Grails, now that they’re backed by the entity behind Spring.

Leveraging closures

Because it’s my bag, I recently found myself writing some code that read various .csv files containing data related to similar concepts (why that data is in various .csv files isn’t germane to the story, baby, so just keep reading); that is, each file contained slightly different data but all the data was inter-related. Accordingly, what I did with the data once I read it was both similar and different. For example, regardless of file, first, I had to see if a particular item (in a row) existed elsewhere (i.e. a database); if it did, I then needed to handle its corresponding elements (i.e. the rest of some portion of the row following that element).

Accordingly, I ended up writing a number of bogue methods that had the following pattern:

def readr = new CSVReader(new FileReader(new File(filepath)))
def header = true
readr.readAll().each{ csvrow ->
 if(!header){
  def lnid = csvrow[0].trim()
  if(this.isItemAnHGA(lnid)){
   //do different stuff with the row data, such as build domain objects and cache them...
  }
 }
 header = false
}

Note, each hip file contains a header row (full of column names), which describes the data in the following rows; consequently, upon iterating over all the rows in a file, I’ve got a boolean flag to skip the header (that is, the first row). Once the header row is ignored, I then proceed to grab the initial datum, which is always an id; accordingly, I call the isItemAnHGA method to see if this is an item I should process. If that is the case, I then do something with it. That something, of course, varies depending on what file I’m reading.

After repeating this pattern twice, I was left wondering how I could refactor things a bit– clearly, the logic above didn’t need to be rewritten n times for every file I was going to process.

As it turns out, the code that lies within the inner conditional is an copasetic candidate for a closure, which is essentially a block of code that can be executed at a later point (that is, it is not executed when it’s defined). Thus, I can refactor things a bit and define a more generic .csv file reading and initial data validation logic like so:

def handleCSV(filepath, closure){
 def readr = new CSVReader(new FileReader(new File(filepath)))
 def header = true
 readr.readAll().each{ csvrow ->
  if(!header){
   def lnid = csvrow[0].trim()
   if(this.isItemAnHGA(lnid)){
    closure.call([csvrow])
   }
  }
  header = false
 }
}

In the code above, note how the method takes a parameter dubbed closure, which is later used inside the conditional. In this case, the closure is passed a parameter, which is the row read from the .csv file (of course, it not being the header!), via the call method.

Now, I can leverage this generic method and pass it a closure that achieves my specialized logic like so:

def buildCacheForConsHSCFile(filepath){
 this.handleCSV(filepath){ input ->
  def csv = input[0]
  cacheService.cacheConsHSC(getItem(csv[0], csv[2], csv[4]))
 }
}

In the code above, the handleCSV method is invoked and in this case, Groovy allows you to define the closure parameter inline (remember, because it’s Groovy’s bag, it won’t be invoked immediately, but later (i.e. inside the handleCSV method))– thus, the input parameter passed into the closure (i.e. all the code between the {}‘s) is a validated row from a .csv file. In this particular example, I then proceed to cache these items via a cashService.

Closures can be quite helpful in creating reusable code in an elegant manner; in fact, at a high level, they can embody the strategy or command pattern, if you think about it. Closures, however, are a bit more flexible as they don’t require interfaces nor abstract classes to achieve polymorphic behavior. Can you dig it, man?