Nick Carroll

Metabolising caffeine into code

Archive for the ‘groovy’ tag

Gradle Android Plugin

without comments

I have recently joined a newly formed team developing Android applications at a large telco, and I am pleased to announce that we are using Gradle for our builds. We are using Gradle with the Android plugin, and instantly we managed to build a simple application, run tests, and have it installed on a device. Our build script simply looks like the following, which is all that is necessary to use the Android plugin.

buildscript {
  repositories {
    mavenRepo(urls: 'http://jvoegele.com/maven2/')
  }
  dependencies {
    classpath 'com.jvoegele.gradle.plugins:android-plugin:0.8'
  }
}
usePlugin com.jvoegele.gradle.plugins.android.AndroidPlugin

Of course this is a rather simplistic script, but it does everything I need it to do right out of the box. The Android plugin provides a number of tasks that allow you to build, test, package and sign your application. You can even install the packaged application on a device or emulator by running gradle androidInstall. Make sure to set the property “adb.device.arg” to “-e” for a running emulator or “-d” for a connected device.

There is also support in Hudson to trigger a Gradle script. Hudson has a Gradle plugin that can be installed from the Admin console, and allows you to directly trigger a Gradle script in your project. Otherwise you can create a simple shell script to call the Gradle tool from the command line.

It is also worth noting that both IntelliJ and Eclipse provide support for Gradle and the Groovy syntax. That is if you don’t like using the command line to trigger your builds.

Gradle has allowed us to spend less time setting up our build and continuous integration environment, and more time on actual Android development. Our team has benefited greatly from this boost in productivity.

Written by Nick

April 26th, 2010 at 5:30 pm

Posted in Programming

Tagged with ,

May Sydney Groovy Group

without comments

I am amazed with how many quality presenters we have had at the Sydney Groovy Group, and the number of project leads that have presented on their Groovy projects.

At the last meeting we got to hear about Griffon from James Williams, one of the project’s lead developers. Griffon is a Grails like framework for developing Swing based desktop applications. I was extremely impressed with Griffon, and how easy it was to create components without having to implement a bunch of event listeners or interfaces that you don’t need or care about. It was also interesting to see how the MVC pattern was applied to a Swing application. It made me wish Griffon was around 10 years ago when I was building Swing applications for Xylogy.

The May Sydney Groovy group will be meeting this Wednesday. Graeme Rocher will be giving a webinar on Grails, plus a run down on the recent GR8 Conference. So you’ll get to hear first hand on where Spring intends to take Groovy and Grails.

If you intend to make it to the meeting then please express your interest in the forums.

Written by Nick

May 24th, 2009 at 10:24 pm

Posted in Programming

Tagged with , , ,

Configuring the Grails Root Application Context

with 9 comments

By default if you create a Grails application called funkysite (i.e. you did grails create-app funkysite on the command line), then when you run your application the root context is set to /funkysite. This means that your controllers such as a UserController with a show action will be available at http://localhost:8080/funkysite/user/show. Having “funkysite” as the root context is redundant, especially if you want to host your application at http://funkysite.com/funkysite/user/show.

My preference is to just have “/” as the root application context. Fortunately, you can easily configure the root application context in Grails. All you need to do is edit conf/Config.groovy and add grails.app.context = “/”. This will set your root application context to “/”, so that the above UserController and show action will be available at http://localhost:8080/user/show.

Written by Nick

March 27th, 2009 at 11:24 pm

Posted in Programming

Tagged with , ,

You are a tool if you aren’t using Gant

without comments

If you are still writing your build scripts in XML then you my friend are a tool (the slang associated with the word “tool” is also implied :p). You are doing far too much heavy lifting and wasting everybody’s time and money by maintaining your build scripts in XML.

My recommendation is to use a build tool like Gant, which is a groovy based build tool that wraps Ant tasks and more. All you need is the standalone version of Gant, which includes all dependencies (eg groovy, ivy, maven, etc). You’ll need to use at least version 1.4, as there is a bug with 1.3 that prevents you from using the Ivy tool set.

The following is a simple Gant script that shows you how to manage your project’s dependencies using Gant’s Ivy integration. The script creates a lib directory and two sub-directories. The sub-directories will contain Jars for the application and for testing respectively. The script depends on having internet access, as the Jars will be downloaded from a public repositiory (ibiblio) and stored in your local repository. Your local repository acts as a cache, so you don’t have to keep downloading the dependencies every time you run your build script in a continuous integration system like Cruise.

libDirectory = 'lib'

includeTargets << gant.targets.Clean
cleanDirectory << libDirectory
cleanPattern << [ '**/*~' , '**/*.bak' ]

includeTool << gant.tools.Ivy

target ( retrieveDependencies : 'Retrieves library dependencies for main and test.' ) {
    depends ( clean )
    mkdir ( dir : libDirectory )
    ivy.retrieve ( organisation : 'commons-lang' , module : 'commons-lang' , revision : '2.3' , inline : 'true', pattern : libDirectory + '/main/[artifact]-[revision].[ext]' )
    ivy.retrieve ( organisation : 'junit', module : 'junit', revision : '4.5', inline : 'true', pattern : libDirectory + '/test/[artifact]-[revision].[ext]')
}

setDefaultTarget ( retrieveDependencies )

Execute the build.gant script using Gant and you will observe the Jars being downloaded and copied to the main and test directories. If you run the script again the Jars will be copied to the lib directory from your local Ivy repository (on Ubuntu this is .ivy2). The end result is the following directory structure.

build.gant
lib
    main
        commons-lang-2.3.jar
    test
        junit-4.5.jar

The equivalent script in XML will probably take ten times more effort, especially if you have to maintain your Ivy files in XML as well! Your build scripts in Gant look less cluttered and more readable than your typical XML based Ant scripts, which will make maintaining your build scripts far less painful. Plus you have the power of Groovy at your disposal for handling more complicated logic. So don't be a tool when it comes to builds. Use Gant for your build tool.

Written by Nick

December 9th, 2008 at 12:23 pm

Posted in Programming

Tagged with , ,

Spring just got a whole lot groovier

without comments

SpringSource (creators of the Spring framework) announced yesterday that they have acquired G2One (creators of Groovy and Grails). This is exciting news for all enterprise Java developers. SpringSource obviously views Groovy and Grails as strategic technologies for improving productivity with developing applications using the Spring framework.

Martin Fowler has blogged a lot on his bliki about Dependency Injection, and more recently about Domain Specific Languages (DSLs). With Groovy on Spring you get to have your cake and eat it too. Spring uses Dependency Injection which allows for a more loosely coupled architecture that is more testable and configurable. With Groovy you will be able to use the more expressive nature of the Groovy language to encapsulate your business rules in a DSL, then call them straight from your Java code. Yes that is correct, Groovy and Java play nicely together on the JVM. Groovy can also be used as a power tool for Java development: build scripts and functional tests can easily be written in Groovy, which saves you from writing XML, and tedious amounts of Selenium RC code in Java.

Warning: Gratuitous plug follows.

The next Groovy Sydney meeting will be held on Wednesday, 26 November 2008 at the ThoughtWorks Sydney office on Pitt St. More details of the meeting are located in the forums. Coincidentally it will be the last Groovy meeting in Spring as Summer is just around the corner.

Written by Nick

November 12th, 2008 at 7:43 am

Posted in Programming

Tagged with , ,

Groovy October Meeting

without comments

The next Sydney Groovy meeting will be held at the ThoughtWorks office on Pitt St on Wednesday 29 October, 2008.

The theme for the meeting is Groovy for Java developers. I will be presenting on how to make your Java code groovier with Groovy.

If you would like to present or attend then please register your interest in the Groovy Sydney forums.

Written by Nick

October 9th, 2008 at 7:42 am

Posted in Programming

Tagged with ,

Groovy Sydney – September Meeting

with 3 comments

Last Wednesday we had our first Groovy user group meeting in Sydney. It was well attended by both external participants and ThoughtWorks developers.

The evening began with a social gathering around pizza and beer. Then we went straight into the presentations. I presented an introduction to Grails. The purpose of my presentation was to raise awareness of a Groovy web application framework, and to become familiar with the command line Grails tool. I was wanting to present a demo as well, but couldn’t for the life of me get my Ubuntu laptop connected to the data projector with a reasonable resolution for a coding demo.

Gianny Damour also gave a presentation after mine on Closures in Groovy. It was quite an advanced presentation on Groovy closures which challenged many people in the room. Gianny introduced us to the concept of builders using Groovy closures, which in term provides the building blocks for developing DSLs in Groovy. More on this topic will no doubt come about in future Groovy meetings.

Gianny did plan to hold a code kata after the presentations so that everyone could get their hands dirty with Groovy, but given it was our first meeting, most people felt uncomfortable with writing code and just wanted to discuss technical topics. This led us to rethink the format of future Groovy meetings. We will still have at least 2 lightning talks, followed by either a third talk or a coding workshop depending on volunteer contributions.

The highlight of the night was having the Groovy meeting hijacked by David Peterson who talked about Buildr, a Ruby build tool for Java projects. Damn Ruby folk are everywhere! :p

The next meeting will be held on 29 October at the ThoughtWorks office in Sydney. The theme of the next meeting will be Groovy for Java developers. If you are interested in presenting on Groovy, Gant, Gradle, EasyB, then please get in contact with me, or post your presentation topics in Groovy Sydney Google group.

Written by Nick

September 28th, 2008 at 1:50 pm

Posted in Programming

Tagged with ,

Dabbling with Groovy

with 2 comments

I am currently implementing a Bayesian document classifier in Groovy and I have to say that I am really enjoying the language. As far as dynamic languages go, Groovy has all the bells and whistles, such as closures, meta-programming, and dynamic typing. The language has a familiar feel for Java developers, yet has the features to accommodate developers that know Ruby, Python, or Perl.

Furthermore, Groovy and Grails have excellent tool support with IntelliJ IDEA. I cannot recommend that IDE enough. Auto-completion, code navigation, syntax highlighting, and more importantly refactoring all work as expected. This is something that I have found lacking with IDEs for other dynamic languages like Ruby and Python. Yes, I know there is a Ruby plugin for IntelliJ IDEA, but it still isn’t as good as the Groovy plugin!

Ok, enough of the sales pitch, lets see some code for the document classifier that I am building. The following Feature class contains a method for extracting a set of features from a document. The document is simply a string of text, and the features are all unique words that have three letters or more. So words like [I, a, be, is] will be ignored, and words like [alpha, bravo, charlie] will be identified as features. If we begin with a test, our expectations will look like the following.

class FeatureServiceTests extends GroovyTestCase {

    void testShouldExtractFeatureFromDocument() {
        def sampleDocument = "Groovy is really groovy man."
        def service = new FeatureService()
        def feature = service.getFeature(sampleDocument)
        def expectedFeature = ["groovy", "really", "man"]

        assertEquals(expectedFeature, feature)
    }

}

The test implies that only words that are unique and have more than three characters within a given document will be extracted as a set of lowercase words. This is a utility method for extracting features that can be used to determine their probability of occurring within a document that belongs to a specific category of documents. Since I am implementing this document classifier in Grails, I am using the convention of naming the feature utility class as a service. The implementation of FeatureService is as follows.

class FeatureService {

    boolean transactional = true

    def getFeature(String doc) {
        def feature = []
        def words = doc.split(/\W/)*.toLowerCase().unique()
        words.each {word ->
            if (word.size() >= 3) {
                feature << word
            }
        }
        return feature
    }

}

Walking through the code, line 1 defines the class name. Kind of standard, unless you come from Java, in which case there is no need to define the visibility of the class using public, etc. You can if you want, but the Groovy compiler will just ignore it.

Line 3 was generated by Grails. It contains a property called transactional.

Line 5 contains the method signature for getFeatures(). There is no need to state the return type of the method, but you can if you want.

Line 6 defines an empty list in which we'll add features to when we find them.

Line 7 uses a regular expression to split the string into a list of words. All of the words are converted to lowercase, and only the unique set of words are kept. This line demonstrates Groovy's ability to chain methods. The '*." operator means apply the toLowerCase() method to each item in the list that is returned by the split operation.

Lines 8 to 12 show a closure that is being used to filter out words that are less than 3 characters in length. Only words that have 3 or more characters are added to the feature list using the left-shift operator (<<). This is where a Perl "unless" keyword would be useful in the Groovy language, as it would reduce the if statement to a single line. It would also read better, along the lines of "add word to feature list unless size of word is less than 3". There is demand for this keyword, so we'll just have to wait and see if it makes it into Groovy.

Finally, line 13 returns the feature list. You don't need to provide a return statement in Groovy, but in this case it is necessary as the last variable in the method is returned by default. I prefer to explicitly state what the method returns, because doing otherwise could introduce unexpected behaviour into your code.

This code example is quite brief, but it should give you a taste of what Groovy has to offer.

Written by Nick

July 26th, 2008 at 12:57 am

Posted in Programming

Tagged with ,

Sydney Groovy Group

with one comment

Today I decided to start up a special interest group for Groovy and Grails developers in Sydney. If you are interested in Groovy or would like to be a presenter then please join up at Groovy Sydney. You can register your Groovy talk on the Presentation Topics page, and I will organise for you to present at the next meeting. The Groovy Sydney group will meet on a monthly basis at the ThoughtWorks office, followed by drinks at a nearby pub.

Groovy is a dynamic language that I have been ignoring until now for no particular reason. I first heard about it when I was doing consulting work in Brisbane last year. One of the client developers of a large bankasurance company gave a pretty good presentation on Groovy. But back then I was ignorant and caught up in the Ruby on Rails hype.

The thing about Groovy that won me over was that you can start off by writing your code in Java, and then refactor to make your code groovier. It reduces the learning curve required to be productive in a new programming language, which I believe to be quite novel.

Groovy makes sense in the enterprise as it allows you to leverage your existing Java based systems. You can deploy a Groovy application in your expensive J2EE application servers, therefore maximising your return on investment in infrastructure costs. For example, Grails — a Rails-esque web application framework for Groovy — can be deployed as part of a Spring application. Essentially you can implement a lot of your integration business logic in Java, and use Grails to quickly create frontend CRUD functionality, which is tedious to do in Spring alone. Groovy is a tool worth having for any Java developer looking for productivity gains.

Written by Nick

July 15th, 2008 at 2:15 pm

Posted in Programming

Tagged with ,