Groovy

Euler was groovy too

I recently stumbled across Project Euler, which is a hip website containing quite a few different math challenges. The idea being that people can attempt to solve any particular challenge which ever way they can (that is, in any language and with any algorithm) — the site doesn’t provide answers either — you must create an account and submit your answer. Project Euler will then check your answer and issue a response — correct or incorrect. If it’s your bag and you Google the project, you’ll find some interesting posts solving various problems in various languages ranging from F# to Scala to C (and everything in between). What’s also interesting is that each post for a problem usually is different in some way or another, which of course provides some interesting learning opportunities.

Problem 1 entails figuring out the sum of numbers divisible by 3 and 5:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

I thought it would be interesting to see if I could solve this in Groovy as the solution clearly deals with iterating over a series of numbers — and as everyone who has played with Groovy (or some other dynamic language for that matter) knows, iteration is a blast, baby!

Accordingly, my first pass yielded the following code:

def sum = 0
(1..<1000).each{
 if((it % 5 == 0) || (it % 3 == 0)){
   sum += it
 }
}
assert sum == /* do it yourself, baby! */

Note that I’m using Groovy’s exclusive range feature to easily iterate over all numbers less than 1000. I then proceed to use Groovy’s it variable, which represents the current value in the iteration (i.e. 1, 2, 3, etc) and test the instance with Java’s modulo operator (that is, modulo returns the remainder of division — 10 modulo 5 is 0, but 11 modulo 5 is 1). If there is a match, I add it to the sum variable. This is programming 101 and brought me back to the Age of Aquarius, baby!!

That was easy enough; however, I wanted to see if I could do away with the sum variable by using one of Groovy’s many hip magic methods attached to collections. Thus, my second attempt leverages Groovy’s findAll method, which permits putting a condition in the resulting closure, which then returns a collection meeting that criteria. Accordingly, with the returned collection of numbers meeting my criteria (that is, any number that is divisible by 5 or 3), I then have to issue the sum method like so:

def val = (1..<1000).findAll{(it % 5 == 0) || (it % 3 == 0)}
assert val.sum() == /* you gotta figure it out yourself, man! */

Groovy’s sum method is straight forward — it takes all the values in a collection (presumably add-able) and adds them up!

Admittedly, the second example is a bit harder to read (at first glance, that is) but it sure is a bit more aesthetic than the first brute force bogue example, isn’t it?

Grails hip tip: testing RESTful services

Are you building hip RESTful services in Grails that leverage XML? Because it’s your bag, do you want to test these services, easily? If so, then I’ve got a tool for you, baby. Grails’ Functional Testing Plugin makes verifying XML based web services a snap, baby!

This handy dandy plug-in along with Groovy’s multi-line Strings makes testing XML GETs, POSTs, PUTs, and DELETEs a breeze with as little code as possible. To get started, you must first install the plug-in like so:

$>grails install-plugin functional-test

Next, create a functional test like so:

$>grails create-functional-test MyRESTfulTest

This command will create a new Groovy file in a test/functional directory. The newly generated Groovy class is an instance of an old style JUnit 3.x test — accordingly, from here you can implement simple test methods in Groovy that have a lot of special methods at their disposal.

For example, to verify an HTTP GET to a RESTful service you can simply write:

void testRESTfulGET() {
 get('/currentComnWidgRes/1200992722')
 assertStatus 200
 assertContent """<?xml version="1.0" encoding="UTF-8" ?>
   <list><currentComnWidgRes id="1200992722">
   <effectiveDate>2009-04-30 00:00:00.0 EDT</effectiveDate><nib>4348.23</nib>
   </currentComnWidgRes></list>"""
}

Note the call to the plug-in’s get method; plus, note how I can compare the resulting response (in XML too, baby) via the assertContent call that can take a multi-line String — isn’t that a snap?

POSTs are as easy too — simply leverage the plug-in’s post method and have at it, man!

void doRESTfulPOST(){
 post("/currentComnWidgRes/"){
  body{
    """<?xml version="1.0" encoding="UTF-8" ?>
      <currentComnWidgResid="6969"><nib>-90.0</nib>
      <effectiveDate>2009-04-30</effectiveDate>
      </currentComnWidgRes>"""
    }
 }
 assertStatus 200
 assertContent """<?xml version="1.0" encoding="UTF-8" ?>
   <currentComnAcctRes id="6969">
   <effectiveDate>2009-04-30 00:00:00.0 EDT</effectiveDate>
   <nib>-90.0</nib> </currentComnAcctRes>"""
}

Note, the post method takes a closure where you can set the body via another closure and like before, you can easily verify HTTP status codes and responses.

Running the plug-in is simple too — simply type:

$>grails functional-tests

This command is quite handy as it fires up an instance of your web application; thus, the Grails Functional Testing plug-in makes functional testing, well, easy. What’s not to like about that?

Grails hip tip: logging SQL

When working with Grails (especially, when slapping it over legacy database, man) it’s often helpful to see the hip SQL the framework generates when manipulating domain objects. As mapping a legacy database to Grails can be tricky (but indeed, solvable, baby!), seeing generated SQL can unveil incorrect mapping, etc.

Luckily, you can easily enable SQL logging without having to mess with Log4J configurations (i.e. debug, error, warn “packages blah blah”). In the DataSource.groovy file in your project’s grails-app/conf directory, simply add the loggingSql variable to a desired dataSource closure (that is, you can enable this feature for a particular environment or all of them) like so:

dataSource {
  //blah blah
  loggingSql = true
}

After that, you’ll notice that all SQL statements Grails (or really, Hibernate) utilizes will be logged to whichever appender you’ve configured (i.e. System.out, by default). This little tip has proved quite copacetic for me, man! Can you dig it?

RESTing easy with Groovy’s HTTPBuilder

Interacting with RESTful web services couldn’t be easier with Groovy’s HTTPBuilder. This handy library has a slick extension dubbed RESTClient, which facilitates handling all aspects of REST (such as GET and POST) quite nicely; plus, parsing and building of both requests and responses in either JSON or XML is a breeze, baby!

Check it out– first, you must create an instance of RESTClient like so:

def zorillo = new RESTClient("http://acme.zorrillo.com/")

Because it’s my bag, I’m interacting with a service whose base URI is acme.zorrillo.com. With this instance, I can easily obtain information via an HTTP GET like so:

def res = zorillo.get(path:"widget/1010081127")

In the above code, I’ve issued a GET request to http://acme.zorrillo.com/widget/1010081127, which returns an XML response that looks something like this:

<widget id='1010081127'>
 <type>JPM</type>
</widget>

Interestingly, with an instance of a response (in my case, res), you can grab an instance of the returned XML via the data property, which is the root node returned via Groovy’s hip XMLSlurper. Thus, data points to the widget element; consequently, I can grab the attribute id and the corresponding element’s value quite easily:

assert res.data.@id.text() == '1010081127'
assert res.data.type.text() == 'JPM'

Need to post some data? That couldn’t be easier either, man — simply use RESTClient’s post method, which allows you to use a MarkupBuilder to construct corresponding XML like so:

def ans = zorillo.post(path:"widget/",
		requestContentType: XML,
         body: {
           widget(id:'129033'){
             type("TFR")
          }
        })

Note in this case, the POST URL is http://acme.zorrillo.com/widget/ and I’m posting a document which looks like so:

<widget id='129033'>
 <type>TFR</type>
</widget>

But, because I’m using Groovy’s MarkupBuilder I don’t have to deal with XML directly — not bad, eh? The /widget service returns an XML document of the created widget if everything works; thus, I can verify things are kosher like so:

assert ans.status == 200
assert ans.data.@id.text() == '129033'
assert ans.data.type.text() == 'TFR'

How’s that for easy, man? The next time you need to interact with a RESTful web service, consider using Groovy’s HTTPBuilder — it’s a snap!

Forcing a failure in easyb

Occasionally during the course of writing a hip easyb story or specification, you might run into a condition that requires a forced failure. That is, based upon some behavior of the code under verification, you might explicitly want easyb to fail a particular scenario. For example, because it’s my bag, I have a then phrase within a scenario that contains a conditional — if something is true then verify some result; however, if something is false, then force a failure. It can be coded like so:

then "the cell returned should be a date type", {
 sndcells = sheet.getRow(1)
 dtype = sndcells[2].getType()
 if(dtype == CellType.DATE){
  dt = sndcells[2].getDate()
  dt.getTime().shouldBe 1201737600000
 }else{
  fail "the type obtained wasn't a date, but was a ${dtype}"
 }
}

In the code above, which is a copasetic snippet of a larger story on parsing an Excel template, I’m verifying that I can obtain a Date type from a particular cell represented as a string (i.e. 1/31/2009). As you can see, if the dtype variable is of a desired type (i.e. Date), I can easily validate it via the shouldBe phrase. If for some reason, however, the cell I expect isn’t a date, I can force easyb to fail by using the fail phrase, which takes a String (note how you are free to use Groovy’s groovy GString feature in the phrase as I’ve done with ${dtype}).

Of course, I could have omitted the else clause entirely; however, in that case, I wouldn’t explicitly know that a particular scenario failed! Can you dig it, baby?

1, 2, 3 storage with S3

Amazon Simple Storage Service (or S3, man) is a publicly available service that hip developers can leverage for storing digital assets such as images, video, music, and documents. S3 provides a RESTful API for interacting with the service programmatically. In IBM DeveloperWorks’ article entitled “Storage made easy with S3″, you’ll learn how to use the open-source JetS3t library to leverage Amazon’s S3 cloud service for storing and retrieving data.

Mashups are Groovy, baby!

Online social networking is all the rage these days, man! In DeveloperWorks’ “Social mashups with Groovy” article, you’ll learn how to build a social network with Google Maps, Twitter, Groovy, and Ajax. By combining a Google Map with location information that Twitter exposes, you can create a mashup that allows people to view Twitter in light of a particular location. The simple application this article builds lets users view a map of their Twitter friends, a.k.a: hip geo-view of their entire network.

So what are you waiting for? Go ahead and read the article now!

Chewing the fat over Grails 1.1

I had the pleasure before the official release of Grails 1.1 to chat with Grails founder and ultimate hip cat Graeme Rocher for JavaWorld’s Java Technology Insider. In this podcast, Graeme talks about what developers will find in Grails 1.1, including performance improvements based on changes in Groovy 1.6; upgrades to the Grails plug-in ecosystem; support for Maven and Ant Ivy; and the exciting, unexpected liberation of GORM, baby!

It’s always a pleasure to speak with Graeme and this conversation was no exception, man. Have a listen and hear for yourself!

easyb is a Jolt award winner!

easyb 0.9.5 is out!The easyb team is proud to have won the 19th annual Jolt award! Because it’s our bag, easyb won in the Testing Tools category; what’s more, the other tools in this category were a stellar bunch including two of our favorites — Sonar and Atlanssian’s Clover. Congratulations to all the Jolt award winners!

It’s been a blast of a journey since we first released easyb, baby and the best is yet to come! Most importantly, thanks to the easyb community for all your support — we couldn’t have done it without you, man!

easyb 0.9.5 is out

easyb 0.9.5 is out!The easyb team is proud to announce version 0.9.5 is now live. It has been a long time coming and this version is jam-packed with new features, baby! Behavior driven development in Java just can’t get any more fun (nor could it get any easier)!

At a high level, this version includes:

  • HTML reports
    • Just pass in the -html flag via the command line or specify the reporting format as html via the Ant/Maven task
  • Enhanced exception reporting
    • easyb offers two options:
      • -e for a full exception stack trace
      • -ef for exception stack trace filtering — that is, a lot of the noise associated with a Groovy exception stack is filtered out
  • Support for ignoring scenarios
    • ignore is a hip keyword now in stories and it can take as an argument a scenario name, a list of scenario names, and even a regular expression
  • Pretty printing
    • Pass in the -prettyprint flag and the output will be nicely colored, baby!
  • Narratives support non underscores
    • as_a can alternately be
      written as as a along with i want and so that
  • Numerous API improvements along with bug fixes!
  • This version leverages Groovy 1.6.0

Please note, this version has changed the package names — previous versions’ package names started with org.disco.easyb.*. We’ve corrected things and removed the disco portion; consequently, all easyb package names are org.easyb.*. This version also has an enhanced plug-in mechanism (which leverages a new keyword, using) for integration with other frameworks — for instance, we anticipate these changes will facilitate easier integration with Grails 1.1.

Thanks to the community for numerous suggestions, comments, and patches! We anticipate that this will be the final version before we release a 1.0 candidate. So what are you waiting for? Download easyb 0.9.5 now and have a blast, baby!

Next »