Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Tuesday, November 11, 2014

Groovy Spring Bean for Static Factory

I started playing around with Grails again recently and ran into a problem trying to create a bean in the Grails resources.groovy file for a static factory. After several frustrating hours trying to find the right combination, I eventually stumbled upon an answer.

The factory I was trying to create a bean from was the JAX-RS Client API class ClientBuilder.newClient() which returns a Client object.

Here is what the bean definition looks like in my Grails resources.groovy file:

import javax.ws.rs.client.ClientBuilder

beans = {
    httpClient(ClientBuilder) { bean ->
        bean.factoryMethod = 'newClient'
        bean.destroyMethod = 'close'
    }
}

Then in your Grails service or controller you can autowire or inject the bean by doing the following:
class FooService {
    def httpClient

    def get(url) {
        return httpClient.target(url).request().get()
    }
}

Hope it helps the next person.

Monday, July 19, 2010

My First Groovy DSL

It's no secret I'm a groovy homer. I love it. One of the things that makes using groovy so fun, is it's syntax. Being able to get the contents of a file by just saying new File("/home/james/test.log").text is refreshing compared to it's java counterpart. Another thing that makes groovy enjoyable is it's ability to support Domain Specific Languages (DSL). MarkupBuilder is a great example. With Groovy, you can create simple or very complex DSLs for your purposes. To my knowledge there are a few ways you can create your own DSL: extending BuilderSupport or using methodMissing/propertyMissing. In my opinion, extending BuilderSupport is more involved while methodMissing/propertyMissing is kind of the poor man's way of creating a DSL.

Up to this point though, I've never actually came across a good use case for creating a DSL until this past week. We have a large set of automated tests that run against our REST Services. Since our application is now multi-tenant, all of our tests need a valid organization (tenant). In our case, an organization contains multiple roles and locations. Each test has different requirements on the types of organizations it needs. Some might need 2 unique organizations, while another might need an organization with at least 2 roles and 2 locations. It was this use case that I thought a groovy DSL would fit perfectly.

My end goal was to have something like this:

def orgs = OrganizationService.getOrganizations().withRoles().withLocations()

This would return a list of organizations that had at least 1 role and 1 location. The nice thing about this DSL is it's scalable. Meaning, if we add new lists of information to an organization, we won't have to update our class. Also, an important feature, is the method name Roles and Locations correlate to the JSON named arrays of the organization. So my JSON looks something like this:

{"organizations": {"name": "James", "roles": ["R1", "R2"], "locations": ["Tulsa", "Omaha"]}}

When writing my DSL I decided to go the poor man's way and use the methodMissing approach combined with the @Delegate annotation. Here it is:

import net.sf.json.JSONArray

class OrganizationFilterArray {
    @Delegate private JSONArray array
    
    OrganizationFilterArray(array) {
        this.array = array
    }
      
    def methodMissing(String name, args) {        
        if (name.startsWith("with")) {
            def length = (args.length == 0) ? 1 : args[0]
            def arrayName = name[4..5].toLowerCase() + name[6..-1]
            
            return filterByLength(arrayName, length)
        } else {
            throw new MissingMethodException(name, this.class, args)
        }
    }
    
    private filterByLength(listName, length) {        
        def filteredArray = array.findAll {
            it."$listName"?.size() >= length
        }
        
        return new OrganizationFilterArray(filteredArray)
    }
}

I could have just as easily extended JSONArray since it's not final, but I was following the @Delegate guide initially and just thought it was an interesting alternative. The big key here is how I used methodMissing to support an infinite amount of possibilities with how to filter an organization. Everything else I think is pretty self explanatory. When it comes across a method that is missing, withRoles(), it calls my methodMissing method. From there I filter out all the organizations that don't fit the criteria. Eventually, this class could be refactored to support more than just the size of an array. Note, I did have to upgrade the gmaven plugin version to 1.0 to get it work in our maven project.

I knew from the beginning I wasn't going to use BuilderSupport. It did take me some time to figure out how I was going to support filtered (getOrganizations().withRoles()) and non-filtered versions (getOrganizations()). That is when I decided to extend List or JSONArray, as both method calls had to return my custom List/JSONArray. Overall, I'm pretty happy with the outcome and how long it took me. It was pretty trivial and very fun thanks to groovy.

Saturday, April 18, 2009

Mock Testing with Groovy

Mock classes enable developers to quickly write unit tests that would otherwise require integration tests because of the need for a database, web container, or servlet container. Using mock classes helps to test a class in isolation and enables rapid feedback. It's not ideal to have a project with only integration tests and no unit tests. Mock classes enable unit testing that otherwise would be impossible.

So how does one create a mock class? Well, there definitely is not a shortage of mock frameworks: EasyMock, jMock, Gmock, MockFor and StubFor. You can always just create your own mock class in your test suite (which I have done in the past when in a pinch). But in my opinion these solutions lack one thing: the ability to quickly create a simple mock that when called returns what I want. To many of the mock frameworks force you to jump through hoops and call methods like expect(), replay(), verify(). What I want is the ability to define a mock class in a single line and inject it myself.

I thought MockFor and StubFor would be the solution, but the documentation is lacking and I haven't figured out how to make it work for me. Ideally I would like to say something like:

def mock = new MockFor(ICarDao.class) {
getCar: {return new Car(color: "blue")}
}
Then MockFor would mock out the remaining methods of ICarDao and now I have a mock class that implements the getCars method that when called by the Class Under Test (CUT) will return a single Car model. But MockFor doesn't work like this and neither do any of the mock frameworks to my knowledge.

There is hope however. Below you can read about 2 alternatives: groovy's metaClass and as keyword. Both require the use of groovy in your tests. If you haven't switched to using groovy to write tests yet, even for Java, then it's time to start now. There is no other framework or library that can make you more productive when writing tests. It's an instant boost.

Groovy's metaClass
As seen in this example, groovy's meta programming is very powerful. In that post I show how one can essentially mock out Thread.startDaemon() by using Thread.metaClass.static.startDaemon. Groovy's meta programming is very powerful as seen by it's heavy use in grails to make things simple. But it doesn't work in all cases.

Groovy's as keyword
Using metaClass is by far the easiest and my favorite way to create a mock class. However, this didn't work for me in my recent attempt to write some unit tests for a Java Manager class that used spring to inject a DAO that the manager used. It didn't work I believe because my Manager class never created the concrete DAO. It defines some getters and setters and expects spring to inject the concrete class. Because of this metaClass didn't work (bummer). So I did a lot of research to come up with a competitive alternative: groovy's as keyword.

Let's start by defining the Manager class:
public class CarManager {
private ICarDao dao;

public void startCar() {
Car car = dao.getCar();
.......
}

public CarManager setCarDao(ICarDao dao) {
this.dao = dao;
return this;
}
}
Now to test this using mock classes and the as keyword all you need to do is this:
class CarManagerTest extends GroovyTestCase {
def void test_start_car() {
ICarDao mock = [
getCar: {return new Car(color: "blue")}
] as ICarDao;

def cut = new CarManager().setCarDao(mock);
}
}

This uses a map and the as keyword to implement an interface. Here the key is the name of the method to mock and the value is a closure of what you want returned when called. And there is no need to define all the methods of the interface, just the ones you want to mock out.

To me, metaClass and the as keyword are much cleaner and simpler compared to the current mock frameworks. At least for this type of testing. Those frameworks might be perfectly useful for other types of testing, I just haven't ran into them yet.

Saturday, January 17, 2009

Testing REST Services with Groovy

For awhile now, RIAs (Rich Internet Applications) have rapidly started replacing traditional server-side web applications (JSP, JSF, etc). Typically, these flashier sites are created using Flex or javascript libraries like extjs or yui. At the heart of these sexy applications live simple REST services that return JSON or XML.

Testing these REST services should be made a high priority for several reasons:

  1. It's the contract between the client and server. Breaking that contract should be avoided.
  2. Your application may not be the only client. Once external parties start consuming your REST services you'll want tests in place to ensure you don't break their clients.
  3. To validate the response is well-formed XML or properly constructed JSON
  4. Valuable black-box test, testing the entire server-side stack starting from the REST layer going all the way down to the DAO layer to the database.
So, what's the easiest way to test REST services? For awhile now I have been combing the internet for the best tools to accomplish this goal, since I wasn't going to do it in pure Java, and I think I finally found the right combination using Groovy and HttpBuilder. Groovy because its super easy to parse XML and JSON, and HttpBuilder because it's a great wrapper for the popular Apache Commons HTTP Client library.

Now let's say you have a REST service at the URL http://localhost:8080/myapp/api/books that returns this JSON:
{"books":[
{"name":"Being Mad","author":"Kit Plummer"},
{"name":"Clown Life","author":"Josh Hoover"},
{"name":"You Miss Me","author":"Ron Alleva"},
{"name":"Talk to me Goose","author":"Jeff Black"}
]}
This is how simple it is to write a test in Groovy using HttpBuilder:
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import static groovyx.net.http.ContentType.JSON

class BooksTest extends GroovyTestCase {
def void test_get_all_books() {
def http = new HTTPBuilder("http://localhost:8080")

http.request(Method.valueOf("GET"), JSON) {
url.path = '/myapp/api/books'

response.success = {resp, json ->
json.books.each { book ->
assert book.name != ""
}
}
}
}
}

To me the major advantage to this approach is being able to traverse the JSON response like I would in javascript. If the response was XML it be just as easy too.

The only two remaining items you would need would be adding the gmaven plugin to your pom and httpbuilder as a dependency.

Friday, July 18, 2008

Grails JSON Parser

Here is a quick example on parsing JSON in grails using groovy (surprisingly, google isn't returning any good hits). Also, if you needed this ability in just straight groovy, I am sure you could include the specific grails jar in your classpath.

import grails.converters.*

def jsonArray = JSON.parse("""['foo','bar', { a: 'JSONObject' }]""")
println "Class of jsonArray: ${jsonArray.class.name}"
jsonArray.each { println "Value: ${it}" }

FYI, it appears from the mailing list this was added around 1.0 RC1.

Building JSON is super easy too in grails/groovy using the render as. And don't forget to import grails.converters.
render Book.list(params) as JSON

Update: Read my recent article on testing REST Services that return JSON using groovy and httpbuilder.

Friday, July 11, 2008

Groovy Threads and MetaClass example

* Update - the code has been updated. The original test was incorrect and was producing a false positive. What you see now is the correct way.

It's been awhile since I have been able to play around with grails/groovy. Now, instead of using a pretend app to learn grails/groovy, I have teamed up with Jeff Black, Chad Gallemore, and Sam Jones (fellow office co-workers here in Joplin, MO) to rewrite an existing small internal java webapp using grails. It's a perfect application for grails and so far we are loving it.

Early on, we needed to figure out 2 things:
1) Groovy way of creating Threads
2) Writing an integration test for a Groovy Service

Groovy Threads
Below is a summary of our service that shows how to start new threads in groovy.

class ProjectService {
def discover() {
Project.list().each {
Thread.startDaemon {
jobService.update(it)
}
}
}
}
Service Integration test with MetaClass
Here is the integration test I wrote that tests the above Service.
void testEmptyProject() {
def called = false

Project.metaClass.static.list = {[]}
Thread.metaClass.static.startDaemon = {Closure c -> c.call()}
JobService.metaClass.update = {called = true}
new ProjectService(jobService: new JobService()).discover()

assertFalse('updateJobs should not have been called', called)
}

The first missing key for me was the static keyword on metaClass since in the service I am calling Project.list() and Thread.startDaemon(). The second mystery was how to mock out Thread.startDaemon() since there could be, and was, a race condition between the update closure setting called = true and my assertFalse.

Thanks Chad for the suggestion of using metaClass. I also got a lot of help from Glenn Smith's blog about testing controllers and Dustin's groovy thread example.

Saturday, May 17, 2008

Groovy Sort List

I am posting a simple example on how to sort a list in groovy because the examples google knows about aren't what I was looking for. With some deep digging I was able to find a clue that eventually solved my problem.

It's real easy to sort a list of numbers

assert [1,2,3,4] == [3,4,2,1].sort()

Or even strings

assert ['Chad','James','Travis'] == ['James','Travis','Chad'].sort()

But this was my example

class Person {
String id
String name
}
def list = [new Person(id: '1', name: 'James'),new Person(id: '2', name: 'Travis'), new Person(id: '3', name: 'Chad')]

list.sort() returns James, Travis, Chad

The solution is ridiculously simple (not that I thought the previous sort would work; I have to be realistic; groovy can't do everything for me).

list.sort{it.name} will produce an order of Chad, James, Travis.

In the previous example note the use of the sort closure sort {} verses the sort() method.

Now I am not sure, off the top of my head and without a Groovy book handy, the simplest way to sort case insensitive.

assert ['a1','A1'] == ['A1,'a1'].sort{fancy closure}

Thursday, February 28, 2008

Groovy's MarkupBuilder and Namespaces

Yesterday Kit Plummer posted an XML example using Ruby to demonstrate how to include attributes and namespaces. So I went on a quest to duplicate his output using Groovy to compare the difference and evangelize.

Here is the desired output:

<person:person text='test'>
<name>Jim</name>
<phone>555-1234</phone>
</person:person>
Using the Groovy Console, and Groovy's ninja-like MarkupBuilder, you can execute the following script to get attributes and namespace prefixes:
import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.'person:person'(text: 'test') {
name('Jim')
phone('555-1234')
}

println writer.toString()

If you prefer to define a default namespace instead do this:
xml.person(xmlns: 'http://people.org', text: 'test') {
name('Jim')
phone('555-1234')
}
Finally, here is an example that uses them all:
xml.'person:person'('xmlns:person': 'http://people.org', xmlns: 'http://people.org', text: 'test') {
name('Jim')
phone('555-1234')
}

This will output:
<person:person xmlns:person='http://people.org' xmlns='http://people.org' text='test'>
<name>Jim</name>
<phone>555-1234</phone>
<person:person>
I think it's more readable than the Ruby example and definitely much better than the equivalent Java code.

By the way, I attempted to use this online syntax highlighter and did not like it. Does anyone know of a good online syntax highlighter?

Thursday, January 24, 2008

Maven Groovy Plugin Example

Here is a powerful example by a co-worker on how to use the maven-groovy-plugin in your maven2 POMs. In this example Ron shows how you can embed a Groovy script in your POM to enforce a specific size of the resulting artifact (in this case an EAR).

This is very valuable because now you can do just about anything in your POM, including adding Java code as in this example (look under Using Java Classes).

However, with this power comes responsibility and you don't want to get in the habit of using this everywhere. Usually this is a red flag meaning you should create your own plugin to be reused by everyone. We should all be able to recognize the drawbacks of Copy+Paste.

Friday, December 28, 2007

Justify using Groovy

How does one justify using Groovy on a project? To me it's no different than including any other dependency in my project and in the end it has the same result but with a lot more benefits. There are a lot of skeptics out there, specifically among my team members, and I just can't imagine why they wouldn't want to use Groovy in their every day development. I guess in this instance "knowledge is a curse." It's kind of difficult to explain why I believe in what Groovy is doing, but I will at least give it a try.

First, the biggest initial hurdle people can't get over is they think to start writing Groovy they have to stop writing Java. That couldn't be further from the truth. Groovy was never meant to replace Java. I have used Groovy to write unit tests for my Java code and I have written Groovy code that has used Java code and vic versa. My experience has shown that Groovy and Java just work seamlessly together, especially when using the maven-groovy-plugin and the IntelliJ Idea JetGroovy plugin (for more information see More Groovy Goodies by Joe Kueser).

Secondly, to me the biggest benefit of Groovy, with no cost to the developer, is the hundreds of extra methods added to existing Java classes (see the Groovy JDK). Just by including a new dependency, I have at my disposal hundreds of new time saving methods that I can start using immediately. For example, there are approximately 50 new methods added to java.lang.String (not sure I will ever use all of them but you get the picture). Now lets say for example you were using some open source project like JFreeChart. And you were using version 1.0.8, and 2.0 was out and it included hundreds of new methods. How long would it take you to change the version in your maven2 pom? To me this is not much different than using Groovy to "extend" Java.

Finally, I want to give a quick example of what the end result of a Groovy class is since Groovy is just complied into Java bytecode. Since I have repeatedly stated that Groovy is no different than including a new dependency in your project let me prove it.

Borrowing an example from my previous post, lets say my Groovy class looks something like this:

class GroovyFileTest {
def void test() {
def file = "/workspace/sandbox/grvyfile/src/test.txt"
println new File(file).text()
}
}

My next step would be to use the Groovy Complier (groovyc) to compile my Groovy source into Java bytecode (or just use the maven-groovy-plugin). That would produce GroovyFileTest.class. Using a Java decompiler, such as Jad, here is the outcome:
public void test()
{
Class class1 = GroovyFileTest.class;
Class class2 = groovy.lang.MetaClass.class;
Object file = "/workspace/sandbox/grvyfile/src/test.txt";
ScriptBytecodeAdapter.invokeMethodOnCurrentN(class1,
(GroovyObject)ScriptBytecodeAdapter.castToType(this, groovy.lang.GroovyObject.class),
"println", new Object[] {
ScriptBytecodeAdapter.invokeMethod0(class1,
ScriptBytecodeAdapter.invokeNewN(class1,
java.io.File.class,
((Object) (new Object[] {file}))), "text")});
}

For the sake of clarity I am not including all the other information that was decompiled (well.... because it's rather long). But to summarize, my two line Groovy script is convereted to 214 lines of decompiled Java code. Initially you might think that boosts well for Groovy and really shows the benefits of Groovy, but there is a lot of Groovy going on behind the scenes.

From my perspective this is the only current argument a Groovy skeptic can make: "well look at all that extra junk they are throwing in. Isn't that going to hurt performance?". And at the end it just might. I think it's obvious that Groovy bytecode probably won't run as fast as Java bytecode, but for me the benefits out way that disadvantage.

I by no means intended this to be an exhaustive list of Groovy benefits (for that I would recommend reading the excellent but lengthy article by Guillaume Laforge on the recent Groovy 1.5 features) . I just wanted to prove that the end result is no different. Hopefully people will respond with questions and criticisms and I can respond intelligently.

To me Groovy is sort of the legal steroids of programming. Those that use it have an unfair advantage, enabling them to deliver software quicker then their competitors and co-workers.

Thursday, November 29, 2007

Using Groovy to work with Files


One of the best applications of Groovy I have come across so far is working with Files. Using Groovy to read data from a file can not get any easier. If you are a Groovy skeptic this is the post for you. Using the maven-groovy-plugin, which allows you to mix Java and Groovy code seamlessly, you no longer have any more excuses (go here for a maven-groovy-plugin how-to).

Recently I was writing unit tests in Groovy for my Java code and I needed to read in the contents of a file for comparison. In Java this would look something like this:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileTest {
public static void main(String[] args) {
try {
String file = "/workspace/sandbox/grvyfile/src/test.txt";
String line = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) !=null) {
sb.append(line);
}
System.out.println("sb.toString() = " + sb.toString());
} catch (FileNotFoundException e) {
System.out.println("e = " + e);
} catch (IOException e) {
System.out.println("e = " + e);
}
}
}

If you are still doing this STOP RIGHT NOW! This boiler plate code took me about 5 minutes to write. Since it's not something I do super frequently I don't commit this syntax to memory, and therefore almost always have to reference the API to remember to use things like java.io.BufferedReader.

Would you like to see the Groovy equivalent? Make sure you don't blink; you might miss it.
def file = "/workspace/sandbox/grvyfile/src/test.txt"
println new File(file).text

That is all folks. In fact if you want to test this real quick, use the groovy command line like the following:
>cd /workspace/sandbox/grvyfile/src
>groovy -e "println new File('test.txt').text"

For those new to Groovy, .text is essentially shorthand for calling the .getText() method on the File object. The method getText() is one of the dozens of new methods added to the JDK (see the GDK for more).

Read my comments in this post (Java: Laugh or Cry, Your Choice...) by Kit Plummer for another good application of Groovy. Here I use the List GDK methods minus() and unique() to decrease the lines of code from ~27 to ~2.

Wednesday, November 21, 2007

Best Groovy quote ever

I think this pretty much sums up Groovy:

"Groovy is executable psuedo-code"
Scott Davis

source http://www.javaworld.com/podcasts/jtech/2007/110107jtech004.html

Monday, November 5, 2007

New Amazon S3 plugin for Grails

Today, Catina Consulting announced the release of an open source Amazon S3 (Simple Storage Service) plugin for Grails with the following goals:

  • Host and manage file assets on Amazon S3 for storage and performance advantages
  • Provide easy mechanisms to reference S3-hosted assets in Grails applications
  • Make most efficient and cost-effective use of S3 hosting resources
Their first version appears to be rather useful with some excellent capabilities coming in the future. This first version focuses on managing user uploaded static content. Planned features include supporting different media types, custom bucket schemas, security integration, support for both REST and SOAP (currently only uses REST), and reporting on S3 usage.

Installation and configuration seem rather simple so it should be rather easy for Grails users to start immediately using this plugin.

What I think is the most interesting was their ability to reuse the JetS3t Toolkit which is written in Java. This just goes to show how groovy can really be the glue between Java and how developers can reuse all that existing Java code.

Go here to learn more about Amazon S3, which is an online storage web service providing unlimited storage through a simple web service interface (REST or SOAP). S3 aims to provide scalability, high availability, and low latency at cheap costs. It accomplishes this by using the same scalable storage infrastructure that amazon.com uses to run its own global e-commerce network.

For example, Smugmug, a popular photo sharing web site, is using it to store and host pictures. For a simple cost analysis view this post by Jeremey Zawodny who contemplates using S3 to replace his backup server.

And finally, I can't leave the Rails community out of this either so here is an article on using the rails AWS::S3 library (this plugin is more feature complete than the grails plugin).

Wednesday, October 31, 2007

Using Groovy to easily avoid nasty NullPointerException

Groovy supports a pretty neat syntactic sugar operator to easily avoid the ugly NullPointerException: the question mark '?'.

Writing this in Java

if (name != null && param1 != null && param1.getUser() != null && name.equals(param1.getUser().getName()))
is now replaced by the much more readable Groovy
if (name && param1 && (name == param1.user?.name))
Amazing how a single character can improve readability that much and avoid potential NPEs. Also if you are curious about my use of == rather than the Java required .equals() see my post on More Groovy Sugar.

Most importantly I have inserted a hidden clue in this post and the first to solve the mystery will receive a free pop of their choice not to exceed 0.77 cents. The winner will be the first commenter with the correct answer.

Thursday, October 25, 2007

Effectively using Groovy Console in Grails App

Each chapter in The Definitive Guide to Grails continues to impress me. Currently I am on Chapter 4 which discusses The Application Domain. In this chapter the author uses the Groovy console within the grails app to test the domains to get some quick feedback. I got to say this ability is awesome! Not only could you do some quick testing, but I am sure it would be great for debugging purposes as well. Now obviously we want to keep testing in the console at a minimum and continue writing those unit tests, but that isn't until chapter 6. So until then here is how you can use the console in your grails app.

Prerequisites
1) Already created a grails app: grails create-app bookmarks
2) Created at least one domain: grails create-domain-class Bookmark
3) Added some properties to the Bookmark domain (URL url)

Now cd into the bookmarks directory and run grails console. This will compile your domain class and make it available to the console. Then execute the following (CRTL + R):

def bookmark = new Bookmark(url: new URL("http://jlorenzen.blogspot.com"))
println 'Bookmark url is ' + bookmark.url
You should see the following output:
Bookmark url is http://jlorenzen.blogspot.com

Wednesday, October 24, 2007

A Groovy switch/case example

Below is an example of Groovy's switch/case feature taken from The Definitive Guide to Grails by Graeme Rocher. I am not a regular user of Java's switch/case feature, but if it had been this way perhaps I might have.


switch (x) {
case 'James':
println "yes it is me"
break
case 18..65:
println "ok you are old"
break
case ~/Gw?+e/:
println "your name starts with G and ends in e!"
break
case Date:
println 'got a Date instance'
break
case ['John', 'Ringo', 'Paul', 'George']:
println "Got one of the Beatles"
break
default:
println "Don't know"
}

More Groovy Sugar

Joe Kueser has some excellent posts on Groovy features (What Makes Groovy...So Groovy and More Groovy Goodies) and I would like to attempt to build on them. He has been nice enough to let me borrow The Definitive Guide to Grails, which so far has been an excellent resource for Groovy and Grails (probably one of the best technical books I have read in awhile).

Expando Objects
Joe does a nice job of explaining this handy new class. Here is another example taken from the Grails book by Rocher:

fred = new Expando()

fred.firstName = "Fred"
fred.lastName = "Smith"

fred.age = 40
fred.happyBirthday = {
    fred.age++
}

fred.happyBirthday()
assert fred.age == 41

You can easily play around with this code with groovy's console (/GROOVY_HOME/bin/groovyConsole). As you can see Expando allows you to define an object, its properties, and its methods at run time. Keep in mind that a method is defined by setting a closure to a property that can be later called like a regular method. One immediate use I can see for Expando is in unit tests.

Groovy's == operator
This is very important for existing Java developers. Groovy's == operator is different than Java's in that it does not evaluate object identity, rather it delegates to the object's equals method. To accomplish object comparison, Groovy introduces a new is method: left.is(right).

The Groovy Truth
Term used by Rocher in the Grails book and coined by Dierk Koenig, that explains the Groovy concept of what is true and what is not. Here is an example of what can be passed to if statements in Groovy and will evaluate to false:

  • A null reference
  • An empty or null string
  • The number zero
  • A regex Matcher that doesn't match
This makes those nasty Java if statements much cleaner.

if (str != null && str.length() != 0 )

now becomes

if (str)

More Mt. Dew sugar to come.

Sunday, October 21, 2007

Great JetGroovy plugin feature for Idea+Grails

Just started using the JetGroovy plugin in Idea and I have to say initially it Rocks! Included is a screenshot of the plugin in Idea version 7 after I created a domain (aka model). Notice how there are nifty buttons for that domains Controller, Views, Domain Tests, and Controller Tests. I was constantly using this ability even in the 5 minutes it took me to create my Hello World grails app. Nice work guys.

Tip for using Grails in Idea

Recently I tried creating my first Grails application using the JetGroovy plugin available in Idea (version 7.0). However, I have Linux (Ubuntu 7.10) and you don't get those nice little icons to start Idea when you install it. Consequently when I tried to create a new Grails project I received the following error:

grails: JAVA_HOME is not defined correctly; can not execute: java

How in the world is that possible I thought to myself? What half decent java programmer doesn't have JAVA_HOME set? Oh but then I remembered my special start script responsible for starting Idea. Idea requires the variable JDK_HOME to be set, but Grails within Idea needs JAVA_HOME. Therefore, here is my new script I use to start Idea 7 which allows me to create new Grails projects. And don't forget Idea 7 on Linux requires JDK 1.6.

sh -c 'export JDK_HOME=/workspace/java/jdk1.6.0_03;export JAVA_HOME=/workspace/java/jdk1.5.0_12;/workspace/java/idea-7361/bin/idea.sh'

Friday, June 8, 2007

Using Grizzly to create a simple HTTP listener

Today I would like to show how you can use Grizzly, a NIO framework for building scalable applications, to create a simple listener to service HTTP requests/responses. My main goal is to provide a simple example, because currently there is a lack of documentation on how to use this great framework (see jean's blog); although they have just made the javadocs available online.

My team and I have been working recently on developing a JBI Binding Component for RSS. To service the incoming HTTP GETs we decided to use Grizzly. Thankfully you can accomplish this with minimal effort.

The following is a simple example to start a TCP listener and respond with some simple text.

import com.sun.grizzly.http.SelectorThread;
import com.sun.grizzly.tcp.Adapter;
import com.sun.grizzly.tcp.OutputBuffer;
import com.sun.grizzly.tcp.Request;
import com.sun.grizzly.tcp.Response;
import com.sun.grizzly.util.buf.ByteChunk;

import java.net.HttpURLConnection;

public class EmbeddedServer implements Adapter {

public static void main(String[] args) {
SelectorThread st = new SelectorThread();
st.setPort(8282);
st.setAdapter(new EmbeddedServer());
try {
st.initEndpoint();
st.startEndpoint();
} catch (Exception e) {
System.out.println("Exception in SelectorThread: " + e);
} finally {
if (st.isRunning()) {
st.stopEndpoint();
}
}
}

public void service(Request request, Response response)
throws Exception {
String requestURI = request.requestURI().toString();

System.out.println("New incoming request with URI: " + requestURI);
System.out.println("Request Method is: " + request.method());

if (request.method().toString().equalsIgnoreCase("GET")) {
response.setStatus(HttpURLConnection.HTTP_OK);
byte[] bytes = "Here is my response text".getBytes();

ByteChunk chunk = new ByteChunk();
response.setContentLength(bytes.length);
response.setContentType("text/plain");
chunk.append(bytes, 0, bytes.length);
OutputBuffer buffer = response.getOutputBuffer();
buffer.doWrite(chunk, response);
response.finish();
}
}

public void afterService(Request request, Response response)
throws Exception {
request.recycle();
response.recycle();
}

public void fireAdapterEvent(String string, Object object) {}
}

That's basically it in a nutshell. So far Grizzly has worked out well for us and is currently being used in Glassfish and Sailfin.

As a side note I have also been reading a lot about groovy recently, so as an added bonus and a personal challenge to write my first groovy script, here is the equivalent groovy code. Remember that groovy scripts can use existing java classes and can also be consumed by java classes.
import com.sun.grizzly.http.SelectorThread
import com.sun.grizzly.tcp.Adapter
import com.sun.grizzly.tcp.Request
import com.sun.grizzly.tcp.Response
import com.sun.grizzly.util.buf.ByteChunk
import java.net.HttpURLConnection

class BasicAdapter implements Adapter {
public void service(Request request, Response response) {
def requestURI = request.requestURI().toString()

println 'New incoming request with URI: ' + requestURI
println 'Request Method is: ' + request.method()

if (request.method().toString().equalsIgnoreCase("GET")) {
response.status = HttpURLConnection.HTTP_OK
def bytes = 'Here is my response text'.bytes

def chunk = new ByteChunk();
response.contentLength = bytes.length
response.contentType = 'text/plain'
chunk.append(bytes, 0, bytes.length)
def buffer = response.outputBuffer
buffer.doWrite(chunk, response)
response.finish()
}
}

public void afterService(Request request, Response response) {
request.recycle()
response.recycle()
}

public void fireAdapterEvent(string, object) {}
}

def st = new SelectorThread()
st.port = 8282
st.adapter = new BasicAdapter()
try {
st.initEndpoint()
st.startEndpoint()
} finally {
if (st.isRunning()) {
st.stopEndpoint()
}
}