Archive for the ‘Groovy’ Category

MongoDB and CouchDB: vastly different queries

Both MongoDB and CouchDB are document-oriented datastores. They both work with JSON documents. They both are usually thrown into the NoSQL bucket. They’re both hip. But that’s where the similarities, for the most part, stop.

When it comes to queries, both couldn’t be any more different. CouchDB requires pre-defined views (which are essentially JavaScript MapReduce functions) and MongoDB supports dynamic-queries (basically what you’re used to with normal RDBMS ad-hoc SQL queries). What’s more, when it comes to queries, CouchDB’s API is RESTful, while MongoDB’s API is more native — that is, you essentially issue a query using a driver in the code of your choice.

For example, with CouchDB, in order to insert some data, I can use a tool like Groovy’s RESTClient and issue a RESTful post like so:

import static groovyx.net.http.ContentType.JSON
import groovyx.net.http.RESTClient

def client = new RESTClient("http://localhost:5498/")
response = client.put(path: "parking_tickets/1234334325",
  contentType: JSON,
  requestContentType:  JSON,
  body: [officer: "Robert Grey",
         location: "199 Castle Dr",
         vehicle_plate: "New York 77777",
         offense: "Parked in no parking zone",
         date: "2010/07/31"])

Note, in this case, I have to delineate a ID for this parking ticket (1234334325) (I can, incidentally, ask CouchDB for a UUID too by issuing an HTTP GET to the /_uuids path).

If I wish to find all tickets issued by Officer Grey, for example, I must define a view. Views are simply URLs that execute JavaScript MapReduce functions. Accordingly, I can quickly code a function to grab any document whose officer property is “Robert Grey” like so:

function(doc) {
  if(doc.officer == "Robert Grey"){
    emit(null, doc);
  }
}

I have to give this view a name; consequently, when I issue an HTPP GET request to that view’s name, I can expect at least one document:

response = client.get(path: "parking_tickets/_view/by_name/officer_grey",
        contentType: JSON, requestContentType: JSON)

assert response.data.total_rows == 1
response.data.rows.each{
   assert it.value.officer == "Robert Grey"
}

In summary, with CouchDB, I can’t quickly issue an ad-hoc RESTful call to obtain some bit of information — I must first define a query (aka view) and then expose it to the outside world. In contrast, MongoDB works much like you’ve been used to with normal databases: you can query for what ever your heart desires at runtime.

For example, I can add the same instance of a parking ticket using MongoDB’s native Java driver (there are better options for working with MongoDB, by the way) like so:

DBCollection coll = db.getCollection("parking_tickets");
BasicDBObject doc = new BasicDBObject();

doc.put("officer", "Robert Grey");
doc.put("location", "199 Castle Dr");
doc.put("vehicle_plate", "New York 77777");
//...
coll.insert(doc);

I can subsequently find any ticket issued by Officer Robert Smith by simply issuing a query on the officer property like so:

BasicDBObject query = new BasicDBObject();
query.put("officer", "Robert Smith");
DBCursor cur = coll.find(query);
 while (cur.hasNext()) {
   System.out.println(cur.next());
 }

Thus, while both document-oriented datastores have some similarities, then it comes to querying, they are vastly different. CouchDB requires the usage of MapReduce while MongoDB allows for more dynamically oriented queries (MongoDB also supports MapReduce). Can you dig it?

Grails hip tip: LinkageError with SAXParseException

Recently a bogue error popped up with an existing Grails project at a client site. In an effort to abstract core domain logic (i.e. business rules) for a financial application, we decided to leverage Drools; consequently, after some prototyping of rules in a non-Grails project, we decided to start evaluating the Grails Drools plugin.

After installing said plugin, however, Grails failed to start up, instead issuing the error:

java.lang.LinkageError: loader constraint violation: loader (instance of ) previously initiated loading for a different type with name “org/xml/sax/SAXParseException”

followed by an equally nefarious stack trace.

It turns out that differing versions of the xml-apis jar will force this issue; accordingly, if this happens to you, you can fix the situation by simply locating the offending jar file (in this case, it was the Drools plugin which includes a differing version: xml-apis-1.0.b2.jar) and removing it.

Effortless Groovy

Does the prospect of learning a new language daunt you? Does the effort it takes to download a jar file and place it in your classpath overwhelm you? If you answered “yes” (or even “maybe”) to either of these questions, have no fear, baby! The bright folks behind the Gaelyk framework (and not to mention Groovy itself) have lowered the bar as low as it can possibly get for checking out Groovy. The Groovy web console is one of the hippest websites around for seeing firsthand how Groovy works.

Via the web console, you can enter in valid (or invalid for that matter) Groovy code and execute it — all that’s required is a browser. That’s it! Interestingly, the website even allows you to save your scripts and view and comment on other people’s scripts — this provides a great way to learn more about Groovy (think of it as an IDE-blog combination). So what are you waiting for? Check it out today (unless the effort to click a link is just too arduous for you).

GAE datastore resources

While I’m a big fan of leveraging Google’s low-level API Entity class (as decorated by Gaelyk) for persisting data into GAE’s underlying datastore, there are some up-and-coming frameworks that are worth examining. Both frameworks note the challenges with JDO and like me, prefer to work with Entity types. Each framework has a good deal of documentation too. Without further ado, check out:

It appears that at the moment, Twig is a bit less verbose (with respect to coding) but each framework supports a wide range of hip features.

Don’t forget to check out Gaelyk (which is a super slick Groovy framework for GAE) and while you’re at it, read “Schemaless data modeling with Bigtable and Groovy’s Gaelyk” for a layman’s approach to data modeling with Entity objects.

A recent Java platform roundtable

I had the pleasure of joining a number of colleagues in a panel discussion regarding the Java platform recently. The resulting dialog can be found on IBM DeveloperWorks entitled “Java platform roundtable, Spring 2010” — in this discussion with the likes of Dan Allen, J. Steven Perry, Alex Miller, and Richard Hightower (just to name a few, man!), we had the opportunity to converse about “most important challenge facing Java-based developers today” and what we see in regards to Oracle’s acquisition of Sun. Moreover, we examined Java 7, alternate JVM languages, Spring, and the cloud.

All in all, I enjoyed reading the varied opinions and views my Java platform compatriots shared. I can’t say I agree with all of them; nevertheless, diversity in opinions makes things interesting. Have a read and see for yourself!

easyb 0.9.7 is on the streets

The easyb team has recently released version 0.9.7, which contains a scattering of features and fixes including one of my favorites: behavior tagging. Briefly, behavior tagging permits the isolation of behavior groups. Much like TestNG’s group annotation, tags in easyb allow you to selectively execute a group of behaviors — this is a handy feature on a number of fronts, not the least of which is test categorization.

What’s more, version 0.9.7 now supports the ability to generate a report of all behaviors without having to run the suite itself; that is, you can generate a listing of all behaviors, which will be marked as “in review” — this is distinctly different than a “pending” state as “in review” behaviors could be either implemented or not; what’s more, they could even be failing. The intent of “in review” is for reviewing the natural language behaviors (i.e. goals) with team members, stakeholder, etc.

Version 0.9.7 also leverages Groovy 1.7.2; plus, there are a few DSL changes, such as but is now supported (works just like and) along with shared_behavior can now be written without the underscore (i.e. shared behavior — this is much like narrative‘s as a and i want).

For more information about what’s in 0.9.7 check out the release page. You can find the 0.9.7 download on easyb’s project page. Thanks to everyone in the community for your support!

ESDC 2010 resources

I recently had the opportunity to present four different talks at the Enterprise Software Development Conference (or ESDC) in San Mateo, California. In an effort to provide additional data points and information, I created individual resource pages for each talk. These pages (hosted at my company’s site — beacon50.com) provide links to articles, blog entries, tutorials, and a copy of each presentation. If you’re curious to see what you missed at ESDC, then have a look, man:

Thanks to everyone who came to ESDC and attended my talks — I had a great time discussing these topics (and more!) with you!

Introduction to easyb video

The easyb team is pleased to announce the posting of a hip introductory video that demonstrates both specifications and stories in action. In this 8 and 1/2 minute video, you’ll learn that easyb enables you to express human readable expectations that verify any Java application (or to be more precise, anything running on the JVM) and that you express those expectations in Groovy.



If you think easyb concisely expresses expectations (i.e. features or requirements) in a simple, yet readable manner, then what are you waiting for, man? Download it today and see for yourself how easy behavior driven development in Java can get with easyb!

Groovy’s Gaelyk on an IBM podcast

I recently had the pleasure of chatting with IBM DeveloperWorks’ Scott Laningham regarding the Gaelyk framework. In this short conversation, I talk about how Gaelyk facilitates rapid development and deployment of Google App Engine applications. Of course, because it’s my bag, I recommend you read the article “Gaelyk for Google App Engine” after listening!

To EasyMock or to Mockito?

From time to time, I’ve found that mocking various dependencies can be helpful in testing behavior. Briefly, mocking an object allows you to fake its behavior so as to more fully isolate some other object depending on this behavior — the classic use case is that of mocking a data access layer, for example. In this case, testing some object that depends on a DAO object becomes a bit easier if you can mock out the DAO and thus not have to worry about an associated database, etc.

There are a plethora of mocking libraries out there (and in many cases, you can roll your own!) — one of my favorites for a long time has been EasyMock. This library has served its purpose for me when I’ve needed it; however, there’s a newer library on the block dubbed Mockito, whose hip description is best read word for word:

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn’t give you hangover because the tests are very readable and they produce clean verification errors.

Indeed, Mockito can mock classes just as easily as interfaces and in many ways, I’ve found its API to be much more natural and BDD-istic. Watch.

Each library is similar in spirit — for instance, when providing a stubbed implementation of a hip object, you request a mock of it and then you instruct the various frameworks on how to behave. For instance, with EasyMock, if you’d like to mock an instance of a Feed class (don’t worry too much about this class, suffice it to say, it is used in a ScoreBoard class, which is the class under test), you can do it like so:

scenario "using easy mock", {
  given "a mocked instance of feed", {
    feed = createMock(Feed.class)
    expect(feed.allScores()).andReturn( [new FootballGame(
        "Cleveland Browns", 20, "San Diego Chargers", 3)] as FootballGame[]
    )

    replay(feed);

  }
  then "things should work normally", {
    scoreBoard = new ScoreBoard(feed,
            new FootballGame("Washington Redskins", 0, "New York Giants", 45));

    games = scoreBoard.getAllScores()

    games[0].awayTeamScore().shouldBe 3
  }
}

As you can see in the EasyMock example (which is being driven via easyb), the Feed class’s allScores method is stubbed — in this case, a fake score is created (rather than say, retrieved from a live scoring system located on another server, for instance). Note how with EasyMock, the fluent interface-like API reads expect and return. With EasyMock, things get started via the replay method — as you can see, later in the scenario, this behavior is validated, thus demonstrating the mock.

EasyMock is definitely easy; however, watch the same example play out with Mockito:


scenario "using mockito", {
  given "a mocked instance of feed", {
    feed2 = mock(Feed.class)
    when(feed2.allScores()).thenReturn([new FootballGame(
       "Cleveland Browns", 20, "San Diego Chargers", 3)] as FootballGame[]
    )
  }
  then "things should work normally", {
    scoreBoard = new ScoreBoard(feed2,
            new FootballGame("Washington Redskins", 0, "New York Giants", 45));

    games = scoreBoard.getAllScores()

    games[0].awayTeamScore().shouldBe 3
  }
}

On the surface, things look to be the same, however, if it’s your bag and you look closely, you’ll see that Mockito’s API reads nicer: when then return — this is quite BDD-like, no? Plus, Mockito doesn’t require a replay-like call. Thus, to me, Mockito is a bit cleaner — it certainly complements easyb stories and scenarios with its when and thenReturn API calls.

While I’m only scratching the surface of features available in both libraries, Mockito’s API is more in tuned with my way of thinking — can you dig it, man?