thejavajar

Development

Groovy and Closures

by RJ Salicco on Jan.10, 2010, under Development

Happy New Year! So it is 2010 and you still haven’t looked at Groovy or had fun developing with Closures? It is time to give it a try. Download Groovy (currently 1.7), setup a GROOVY_HOME variable, and add GROOVY_HOME/bin to your system path. Now open up a text editor, I like Textmate on my Mac and Notepad ++ when I am on a Windows machine, and create a new file, something like ClosureFun.groovy. Now let’s get some coding done. First, let’s add a class:

class Person {
    def firstName
    def lastName
    def emailAddress
}

This is really not too difficult to understand, right? We have a class, Person, with three attributes; firstName, lastName and emailAddress. Now let’s create some instances of Person:

bob = new Person(firstName:"Bob", lastName:"Jones", emailAddress:"bob.jones@yahoo.com")
rob = new Person(firstName:"Rob", lastName:"Fake", emailAddress:"rob.fake@gmail.com")
ray = new Person(firstName:"Ray", lastName:"Real", emailAddress:"ray.real@gmail.com")
tom = new Person(firstName:"Tom", lastName:"Real", emailAddress:"tom.real@yahoo.com")
mike = new Person(firstName:"Mike", lastName:"Test", emailAddress:"mike.test@msn.com")
drew = new Person(firstName:"Drew", lastName:"Wilkins", emailAddress:"dwilkins@aol.com")

We now have six instances of Person; bob, rob, ray, tom, mike and drew. Groovy supports these Map-like constructors and they are given to us just like Java gives us a no arg constructor by default if we do not create a constructor for our Java class. We also get new Person(firstName:”value”), new Person(lastName:”value”), new Person(emailAddress:”value”), new Person(firstName:”value”, emailAddress:”value”)… and the other permutations. This feature is quite nice. Now let’s create a list of Persons:

def list = [bob, rob, ray, tom, mike, drew]

Maybe the Groovy syntax is a little different than Java, but it is pretty easy to see how, in the code above, to create a list of Persons. Now, we have this instance of list, as in java.util.ArrayList, that now contains our instances of Person. We have created a class Person, we have our six instances of Person and they all exist in a list. What now?

Well, I want to be able to print out the values of firstName and lastName of particular instances of Person that are in the list. I want to print out the Person instances in our list where the firstName value begins with “R”. Then I want to be able to print out the Person instances in our list where the emailAddress contains “yahoo”. Someone else wants to print out the Person instances where the last letter in lastName is “e” and their friend wants the Person instances where the last letter in lastName is “s”. Should I write a method for each scenario that will take a list as a parameter and loop through each value and check for our desired condition then print the firstName and lastName? Sure, why not?

def printPersonsWithFirstNameBeginingWithR(list) {
    list.each {
        if(it.firstName.startsWith("R")) {
            println "$it.firstName $it.lastName"
        }
    }
}

Our first method is done. If you are not familiar with Groovy, ‘list.each’ is like a ‘for’ loop in Java and ‘it’ is an implicit placeholder for each item in the list. In our case, ‘it’ represents a Person class. More information on syntax of Groovy can be found on the Groovy Web site.

def printPersonsWithEmailAddressContainingYahoo(list) {
    list.each {
        if(it.emailAddress.contains("yahoo")) {
            println "$it.firstName $it.lastName"
        }
    }
}

def printPersonsWithLastNameEndingWithE(list) {
    list.each {
        if(it.lastName.getAt(-1) == "e") {
            println "$it.firstName $it.lastName"
        }
    }
}

def printPersonsWithLastNameEndingWithS(list) {
    list.each {
        if(it.lastName.getAt(-1) == "s") {
            println "$it.firstName $it.lastName"
        }
    }
}

That would work, right? Yeah, we could then write some code to call each method passing in our list and we would get what we want. Cool, we’re done. Wait, we need to support another condition. We need to support a request to print out all Person instances in our list where the emailAddress contains “gmail”. Well, I guess we should write another method? Why not?

def printPersonsWithEmailAddressContainingGmail(list) {
    list.each {
        if(it.emailAddress.contains("gmail")) {
            println "$it.firstName $it.lastName"
        }
    }
}

In our case, we see a pattern emerging. The only thing that changes in each of the above methods is the name of the method and the conditional statement in the if block. Well, when we take advantage of Closures in Groovy we can ignore the 5 methods we wrote above and just write 1 method like the one below (yeah, 5 methods into 1):

def printPersons(list, clos) {
    list.each() {
        if(clos(it)) {
            println "$it.firstName $it.lastName"
        }
    }
}

The above method looks just like our other 5 methods but we have changed our input parameters. Now we are expecting a list and a Closure as arguments and we evaluate the Closure parameter in the if block as our conditional statement (Closures can do more than return true or false). So how do we call our re-factored, re-written method? We now call the method passing is our list as a parameter and because the Closure is the last argument in the printPersons method, we can create our conditional Closure within brackets as you can see here:

// firstName starts with 'R'
printPersons(list) { it.firstName.startsWith("R") } 

// emailAddress contains 'yahoo'
printPersons(list) { it.emailAddress.contains("yahoo") } 

// last letter of lastName is 'e'
printPersons(list) { it.lastName.getAt(-1) == "e" }

// last letter of lastName is 's'
printPersons(list) { it.lastName.getAt(-1) == "s" }

Without getting into all the syntax and semantics of Groovy, we use ‘it’ again because it is a special implicit variable in Groovy used quite often with Closures and other Groovy code structures. In our case, ‘it’ will represent each Person instance in the loop, ‘list.each’. Now when we need to add that last minute request, well, it is already supported! Just pass the new condition.

// emailAddress contains 'gmail'
printPersons(list) { it.emailAddress.contains("gmail") }

Very cool stuff. Now, we can combine everything in one file, like ClosureFun.groovy and run the script. There are plenty of articles and blog posts all over the Internet about Groovy and Closures. I have learned quite a bit by attending presentations by people like Venkat Subramaniam, Scott Davis, Guillaume LaForge, Graeme Rocher, Jeff Brown and a few others. At the end of the day, it is all about getting your hands on Groovy, so get out there and write some code!

1 Comment :, more...

Hazelcast Groovyness

by RJ Salicco on Dec.10, 2009, under Development

Data distribution is a pretty cool topic. Recently, I have been working with Hazelcast, which is an open source clustering and data distribution platform for Java. Well, I really like what I have seen so far and I figured why not have some fun with Hazelcast and Groovy.

I started by adding the Hazelcast 1.7.1 jar to $GROOVY_HOME/lib. Hazelcast, at an introductory level, provides distributed implementations of java.util { Queue, List, Set, Map }. I can run a Groovy script on multiple JVM’s and I can share a Map of customers on each instance. For example:

def customersMap = Hazelcast.getMap("customers")

Now, I have an instance of Map and I can add values using Hazelcast’s distributed id generator:

def idGen = Hazelcast.getIdGenerator("customer-ids")
def id = idGen.newId()
customersMap.put(id, "Customer $id")

So, that was pretty simple, right? Here is the entire Groovy script HazelcastGroovynessAdd.groovy:

import com.hazelcast.core.Hazelcast
import com.hazelcast.core.IdGenerator

def customersMap = Hazelcast.getMap("customers")
def idGen = Hazelcast.getIdGenerator("customer-ids")
def id = idGen.newId()
customersMap.put(id, "Customer $id")

I can open up a few different command prompts and enter:

> groovy HazelcastGroovynessAdd.groovy

Now, the customers Map has a few customers in it and our Groovy scripts are still running. Let’s add an com.hazelcast.core.EntryListener to the customers Map so we can detect a com.hazelcast.core.EntryEvent. Here is HazelcastGroovyness.groovy:

import com.hazelcast.core.Hazelcast
import com.hazelcast.core.EntryListener
import com.hazelcast.core.EntryEvent

def listener = [
	entryAdded: { EntryEvent ev ->
		println "key $ev.key was added with value $ev.value to $ev.name"
		Hazelcast.getMap("customers").values().each {
			println it
		}
	},
	entryUpdated: { EntryEvent ev -> },
	entryRemoved: { EntryEvent ev -> },
	entryEvicted: { EntryEvent ev -> }
] as EntryListener

def customersMap = Hazelcast.getMap("customers")
customersMap.addEntryListener(listener, true)

In the above code, we define listener which implements com.hazelcast.core.EntryListener. I now start up HazelcastGroovyness.groovy at a new command prompt(s):

> groovy HazelcastGroovyness.groovy

We can go back to our original HazelcastGroovynessAdd.groovy script and open (re-open) a few more command prompts and run the script that adds customers to the Map. Now in each running instance of HazelcastGroovyness.groovy we see something like:

key 2000001 was added with value Customer 2000001 to c:customers
Customer 2000001
Customer 1000001
Customer 1

Hazelcast is very cool, easy to use technology that provides distributed data with a few lines of code, especially with Groovy. More information can be found at Hazelcast’s website and at the project site at Google Code.

1 Comment :, more...

Grails on JBoss AS 5.1.0 GA

by RJ Salicco on Nov.03, 2009, under Development

Grails is changing the way Java developers approach Web development. If you are not familiar with Grails, it is a Web application platform for the agile and dynamic language, Groovy, that runs on the Java Virtual Machine. There are plenty of available books on Groovy and Grails and there is a plethora of blog posts and online documentation to help you get started with your first Groovy and Grails project. This article will discuss creating a simple Grails application for JBoss AS 5.1.0 GA and demonstrate how simple Java Web development can be.

I have taken some time to explore developing a simple Grails 1.2-M3 application and deploying it on JBoss AS 5.1.0GA. Grails is all about productivity. In a few short steps, I create a simple Web application, generate a Web archive (.war) file and deploy it on JBoss AS 5.1.0 GA.

After Grails 1.2-M3 is installed and properly setup, I open a command prompt and enter

> grails create-app

and when I am prompted, I enter a name for my application.

> demo

A directory is created with the same name as my application. I then navigate to that directory.

> cd demo

Next, I create two domain classes to represent the solution to my business problem, storing company information in a database.

> grails create-domain-class org.axiomaticit.model.Company
> grails create-domain-class org.axiomaticit.model.Address

The above commands create two .groovy files in the directory grails-app/domain/org/axiomaticit/model/, Company and Address. Here is what the Company.groovy file looks like:

package org.axiomaticit.model

class Company {
    static constraints = {

    }
}

Next I open the Company.groovy and Address.groovy files in a text editor or IDE and add some detail. Here is the Company.groovy file after I add some fields and constraints:

package org.axiomaticit.model

class Company {

    String name
    String website

    static hasOne = [address:Address]

    static constraints = {
        name(blank:false)
        website(blank:false, url:true)
        address(nullable:true)
    }

    String toString() {
        "$name"
    }
}

And here is the Address.groovy file:

package org.axiomaticit.model

class Address {

    Company company
    String street1
    String street2
    String city
    String state
    String postalCode

    static constraints = {
        company(nullable:false)
        street1(blank:false)
        street2(blank:true)
        city(blank:false)
        state(blank:false)
        postalCode(blank:false)
    }

    String toString() {
        "$street1 $city, $state"
    }
}

If you are not familiar with Groovy and the conventions of Grails, this might be a little weird to look at. If you are a Java developer, some of the above code looks a lot like what you already know, right? Let’s talk about what I just did. I created two classes to represent company information. First, I created a company class with a few important fields like ‘name’ and ‘website’.

    String name
    String website

Then I created another class, Address, to represent standard US address data.

    String street1
    String street2
    String city
    String state
    String postalCode

I also added an Address to the Company class,

static hasOne = [address:Address]

and a Company to the Address class.

Company company

Don’t get too wrapped up in all the details if you are new to Grails, but what you should understand is that I am building a domain model and creating properties and relationships between persistent entities. The Grails documentation is quite detailed and the user community is also very helpful if you get stuck with the Grails conventions and semantics of Groovy.

Now that I have my domain model, I want to create the controllers and views for my Web application. Controllers and views? Think MVC (Model, View, Controller). So, I go back to my command prompt and enter each command:

> grails generate-all org.axiomaticit.model.Company
> grails generate-all org.axiomaticit.model.Address

The commands above will create a few things based the domain model objects; they create default controllers and views that will support basic CRUD (Create, Read, Update, Delete) functionality. The controllers will be in grails-app/controllers/org/axiomaticit/model/ and the views will exist in grails-app/views/company and grails-app/views/address respectively for each domain model object Company and Address. Let’s go ahead and see what I have created and run the application from the command line.

> grails run-app

Once the application starts up, I browse to http://127.0.0.1:8080/demo and test out the application. It might not be everything I wanted, but I have a great starting point, right? Let’s deploy this on JBoss AS 5.1.0 GA. Back to the command line to create a Web archive (.war) file.

> grails war

If everything builds properly, I have just created a file, demo-0.1.war, that I can drop into the JBoss deploy directory. I can start up JBoss and point the browser at http://127.0.0.1/demo-0.1 and test out the application. Wow, that took about 10-20 minutes and now I have a fully-functional Web application. Grails is a great platform for proof-of-concept work but because it is based on proven technologies like Spring and Hibernate, many developers are moving Grails applications right into production. Combine Grails with an enterprise level application server like JBoss AS 5.1.0 and you have productivity built on top of dependability.

This is a copy of what I posted at Jboss.org.

4 Comments :, more...

Ruby Proc Fun

by RJ Salicco on Aug.31, 2009, under Development

I am fairly new to Ruby but I do have experience with Groovy so I have found learning and experimenting with Ruby somewhat of an easy effort. The Ruby community is pretty big so there are plenty of blog posts and other Web sites that are available, via a Google search, to help understand some problems when I get stuck. I started playing around with Ruby Proc (procedures), if/elsif/else and case/switch statements and here is what I am having fun with:

# define our apple Proc
apple = proc { |t| puts "my apple" + t }

Above we have our executable (proc) code assigned to the ‘apple’ variable.

# doIt1 with if statements
def doIt1(c, t)
  if t.respond_to?("call")
	puts "-- callable"
    c.call " is awesome"
	t.call " is really awesome"
  elsif t.kind_of?(Array)
	puts "-- not callable Array"
	t.each { |t1| c.call t1 }
  else
	puts "-- not callable String"
	c.call t
  end
end

Then we have a method ‘doIt1(c,t)’. This method expects 2 arguments; the first argument, ‘c’, I expect is a Proc and the second argument, ‘t’, I expect to be a Proc, Array or String.

if t.respond_to?("call")

The ‘if’ statement checks to see if ‘t’ has a method named ‘call’ that it will respond to. I think the ‘respond_to’ method is great for dynamic languages. I could have just checked to see if ‘t’ is a Proc as well, but then that limits me to one Object type, right?

t.kind_of?(Array)

The ‘elsif’ statement checks to see if ‘t’ is of type Array. Like instanceof in Java.

# doIt2 with case/switch block
def doIt2(c, t)
	case t
	  when Proc
	    puts "-- callable"
		c.call " is awesome"
		t.call " is really awesome"
	  when Array
	    puts "-- not callable Array"
		t.each { |t1| c.call t1 }
	  when String
	    puts "-- not callable String"
		c.call t
	  else
	    puts "not valid"
	end
end

Then I created a method just like ‘doIt1′ called ‘doIt2′. In ‘doIt2′, I used a case/switch statement and handled things similarly to ‘doIt1′. In the second method, I check ‘t’ to be of type String and have a default case for when ‘t’ is not a Proc, Array or String.

# doIt1 tests
doIt1 apple, apple
doIt1 apple, " works good"
doIt1 apple, " works hard"
doIt1 apple, [" looks good", " looks elagant", " looks shiny"]

# *'s used to separate method tests
puts "*" * 40
puts "*" * 40

# doIt2 tests
doIt2 apple, apple
doIt2 apple, " works good"
doIt2 apple, " works hard"
doIt2 apple, [" looks good", " looks elagant", " looks shiny"]

Then I wrote a few ‘tests’ to see what would happen. Ruby is fun and I definitely enjoy working with Ruby and Groovy. Here is the full script file: appleProc.rb

Leave a Comment :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!