Archive for the ‘gr8’ Category
Getting Groovy: What’s Next after gr8conf?
I had a great time at gr8conf earlier this week, and feel like I did a reasonable job of blogging a summary of the sessions (some more than others – sorry Griffon fans!) So, what’s next?
Well, I’m definitely going to be doing some more work in Groovy and Grails and I’ll continue to add my experiences to this blog (so remember to add it to your feed reader if you haven’t already!). I’ll also be posting some content on Domain Specific Languages that’s relevant to Groovy devs, and next week I’ll be doing a series on “Getting with Git” for Groovy/Grails developers who’ve noticed the trend and want to know how to kick their subversion habit and join us in the world of distributed vcs’s!
I had a great time meeting everyone at gr8conf this year, and look forward to seeing you all again next year!
The Gr8 Conference: Industrial strength Groovy
Paul King presented the final session of the conference. He has worked on a number of fairly large, Agile projects using Groovy and Grails and wanted to share some thoughts on best practices for building large Groovy and Grails applications. (His slides are available online)
Topics
- Testing/mocking JUnit, TestNG, EasyB, Spock, Instinct, MockFor, Gmock, EasyMock
- DI: Spring, Guice
- Coverage: Cobertura
- Code STyle: CodeNarc, IntelliJ
- Duplication: Simian
- Documentation: GroovyDoc
- Builds: Ant, Gant, GMaven, Gradle, Hudson
- Modularization: Grapes, OSGi
Groovy
- Out of the box it runs junit3, junit4 (if in class path), testNG
- Check out GMock and also expandometaclass mocking in grails
Paul provided an introduction to the common testing and mocking frameworks including JUnit, TestNG, EasyMock and GMock. He also introduced Instinct – a test framework he’s done some work with, and then talked briefly about Spock and EasyB – two interesting frameworks for capturing and running functional/acceptance tests.
Spock vs EasyB
- Spock is a BDD inspired framework that gives devs tools to make their lives easier
- EasyB is a great way to capture requirements and build the acceptance tests
- EasyB scenarios can be stories, and can leave them blank to make them descriptive stories. Then start adding closure code and can put in selenium, etc
DI In Dynamic Languages
In static languages, Dependency Injection is almost essential to create testable code. Without it, hard coded references to “new” objects can’t be replaced (I suppose you could come up with work arounds using test-aware object factories, but really, DI is the way to go). In Groovy (and most other dynamic languages) there are a number of tricks you can use to get the ability to stub/mock out objects without using a DI framework. For example, the object.metaClass.Constructor can be overloaded to point to a specific instance or do something else, so you can get some of testability benefits of DI in Groovy without having to use Spring or Guice. That said, as projects get larger there are still real benefits to using a DI framework. Paul provided a quick overview of two of the most common Java DI frameworks – Spring and Google Guice.
He then went on to look at code coverage using Cobertura, suggested that 100% coverage is a “necessary but not sufficient condition” (I’ll agree that it’s not sufficient – whether 100% coverage of all of your code is necessary, I’ll leave for another time and place!).
He spent some time looking at the ability to enforce code styles with Code Narc (such as setting maximum lines per method or class) and some of the IDE capabilities of IntelliJ for improving the style of your code. His suggestion was that you should allow your code checking tool to break the build, but should only put rules you’re willing to enforce 100% – otherwise you’ll just get more and more warnings and genuine coding issues will get lost in the noise in the reports.
He also introduced a tool called Simian for checking your code base for duplication. It supports Groovy, is free for OSS projects, $99 (Australian) for a single user (with restrictions) or $499 (Australian) per project for larger teams.
He talked briefly about GroovyDoc (which for Java devs familiar with JavaDoc is pretty much what you’d expect), and then went on to look at using Groovy within Ant to script your Ant files, and using Ant within Groovy to fire off Ant scripts from Groovy. He also recommended Gant – a layer on top of the Groovy Ant builder (Ant uses XML config, so a builder is a natural way to script it in Groovy), discussed GMaven (a Groovy Maven wrapper) and Gradle which is focused on bringing the benefits of dependency management (think Maven or Ivy), but in a Groovier style.
Continuous Integration
An important part of any non-trivial project is CI – especially with dynamic languages where you have to rely more heavily on tests because the compiler catches many fewer errors. There are a number of different CI servers such as CruiseControl, Continuum and TeamCity (commercial), but Paul presented on Hudson which is my favorite as it’s free, widely used, and much easier to get started with and to configure than Cruise.
Hudson has:
- Gant plugin – Can invoke Gant build script as the main build setup
- Gradle plugin – Allows hudson to invoke Gradle build scripts as the main build step
- Grails plugin – to invoke Grails tasks as build steps
- Hudsons CLI and the Groovy shell – Have access to runtime in Groovy so can ask what plugins, what is state of info inside it, etc.
Paul also briefly discussed modularization using either Grapes or OSGi.
It was a great overview of the various elements of pulling together a professional set of tools for testing and building Groovy and Grails apps.
The Gr8 Conference: Creating a Griffon Front End
On the final afternoon of gr8conf, Jim Shingler provided an introduction to Griffon – a system for creating Java wing apps in a very Grails like way. Griffon is “a Grails-like Rich Internet Framework” and Jim did a great job of showing how to install it, create a hello world project and get it up and running in about 10 minutes.
He then proceeded to take the Twitter client that Graeme had created earlier during the conference and to provide a rich Swing front end using very little code. The project is still in the early days (it’s currently a 0.1.1 release), but it was extremely impressive to see just how quickly you could build an application using it.
Right now I have my work cut out with getting up to speed with Groovy and Grails, but if you have any interest in building swing apps I’d thoroughly recommend checking out Griffin, and I plan to find some time before next years conference to play with this and post some more thoughts.
The Gr8 Conference: Using IntelliJ IDEA
After Graeme was done, Vaclav Pech did a half hour overview of some of the many features available for working with Groovy and Grails in IntelliJ IDEA, an IDE from JetBrains.
Given that you typically use Groovy and Java together, the theme of the presentation was the importance of making it easy to go between the two of them and to provide a consistent experience between them. There were lots of nice features like the ability to run Groovy and Java tests together, the ability to preview interfaces, generate stubs for extending java interfaces, etc. It even has support for teaching the IDE about specific dynamic methods so if (for instance), you mix or even inject via AST transformations a particular method into an object at runtime, you get tell IDEA that the class will have that method at runtime and it will provide some IDE support for that. There was also support for various refactorings, the ability to do command line Grails operations within the IDE and so on.
There is no question that currently, IntelliJ is the premier IDE for working with Groovy and Grails (although it’s also clear that SpringSource is working hard to make the Eclipse experience more usable than it currently is). Personally I find that for ad-hoc work, using TextMate on a Mac is ideal, but I’ve already picked up a personal license for IntelliJ (in the scheme of things, if you can’t invest $250 in improving your productivity, you’re probably not charging enough for your code!) and am slowly working through learning all of the keyboard shortcuts required to become really proficient in an IDE. I can see that as I start to work on larger projects it’ll really help with productivity.
Anyone used to using an IDE with a statically typed language like Java or C# is going to get a little surprised when they see the limitations imposed by working with a dynamic language. For example, I can’t even reliably “rename method”, because in a dynamic language, you can concatenate a string literal with the name of a method and use that to call the method, so it isn’t possibly to reliably rename all method references. There are some possible approaches that help with some of the issues using dynamic as well as static code analysis (you have a running copy of the application and use that to introspect it) but for a Java developer it is going to seem like a bit of a change of pace (luckily I mainly program in dynamic languages so I have little sense of what I’m missing!).
It was a good overview of some of the capabilities of the premier IDE for Groovy and Grails development, although a number of people I spoke to would have preferred a slightly slower pace, cutting down on the number of features covered to give us a bit of a better sense of how to use the features. Nobody would expect to become proficient in an IDE after a half hour demo, but by (for example) showing some of the features using the menus rather than using the keyboard shortcuts, it would have probably done a better job of presenting the features of the tool even though obviously nobody would actually develop that way.
The Gr8 Conference: The Grails Plug-in System – Plug in to Productivity
After Graeme’s talk on building a Twitter clone in Grails, we took a short break and then returned to another presentation by Graeme – this time on the process of writing plug-ins for Grails. The core message of this presentation was that you don’t need to be a Grails guru to write plug-ins. Even if you’re just writing applications for your own use, you should consider using plug-ins to modularize them.
Grails Plugins
Grails is designed to wire together different libraries and to make them easy to use. Out of the box, Grails uses plugins: controllers, gsp, GORM for Hibernate persistence. etc. In total there are 10-11 plug-ins in the default Grails applications you get when generating them using create-app to provide the core grails experience. In this sense, Grails can be seen as a “platform for runtime configuration”.
There is a Grails runtime with the concept of a grailsapplication (with a class that models that), along with an application content and then a bunch of plugins. For example the quartz plugin (for scheduling tasks) actually adds a new notion called a “job” to Grails to the grailsapplication object. So you can extend the grailsapplication object.
The Extension Points:
There are a number of different extension points that you can leverage when building a Grails plugin.
- Build system – additional command line scripts.
- Spring application context - for sensible defaults and configs. Spring has concept of message driven beans that plugins can auto configure.
- Dynamic method registration – Adding methods automatically to certain classes of objects. For example, GORM adds save, list, delete and other persistence methods to domain objects.
- Auto reloading – for example the JMS plugin listens for change events to services and reconfigures message driven bean on changes.
- Container config (web.xml) – Grails generates the web.xml. Can participate in the generation
- Adding new artifacts - Can add new artifacts and artifact types. New concept like a job in quartz, or just create controllers (like the searchable plugin does).
What is a Plugin?
- Just like a normal Grails project
- The only difference is the presence of a <pluginname>GrailsPlugin.groovy file
- Use “grails create-plugin [plug-in name]” to create one – that’s it!
A plugin is just a regular Grails project and can be developed like one.
The plugin descriptor:
class LoggingGrailsPlugin {
def version = 0.4
def dependsOn = [core: "1.0 > *"]
}
Packaging your Plug-in
It’s also easy to package up a plugin:
grails package-plugin
cd ../my-project
grails install-plugin ../logging/grails-blog-0.4.zip
or remotely like:
grails install-plugin http://myserver/grails-blog-0.4.zip
Plugins and application modularity
Grails app plus . . .
- messaging, security, search, blog, wiki, maps, etc
All main app does is to provide a set of plugins
Adding Basic Artifacts
- A plugin can add new tag libs, controllers and services simply by creating them in the plugin project
- Since a plugin project is just like any project, you can just create and run one
Turning the twitter app into a plugin:
- Start by factoring out the domain into a plugin
grails create-plugin twitter-domain
Look at the TwitterDomainGrailsPlugin.groovy it creates
Copy domain to plugin and delete
Then cd into twitter-domain and grails package-plugin it
grails create-plugin twitter-iphone
grails install -domain ../twitter-domain/grails-twitter-domain-1.0.zip
add [dependson:TwitterDomain: "0.1" , iWebKit: "0.4"]
Note: When create plugin project, doesn’t auto install any of the grails plugins like Hibernate, so may need to grails install-plugin Hibernate – otherwise it’ll say “can’t find property “save”".
Note: dependencies are transitive, so install twitter-iphone, if it depends on iWebKit, it’ll install that automatically.
More advanced use cases (beyond the basics)
Can provide bean defs in def doWithSpring – e.g. setting “time to live” higher in production for EhCacheFactoryBean
See the Grails user guide for a description of the Spring Domain Specific Language
Plugins allow you to manipulate the underlying Spring context based on the environment, the conventions and the state of other plugins.
Can enhance behavior with doWithDynamicMethods to add to the application.domainClasses.each {} and then (for example_ domainClass.metaClass.constructor can be overwritten)
or add domainClass.metaClass.static.load = {long id -> template.load(delegate.getClass() , id)}
See the metaprograming guide on the Groovy website.
There are some issues re: template rendering and static resources in plugins, so they do require just a little more thought than an app – but not much.
Plugins already available
- Test: Selenium, fitnesse, code coverage, etc
- Rich Grails: Flex, GWT, GrailsUI (YahooUI), etc
- Secure Grails: Spring, JSecurity, OpenID, etc
- Integrate Grails, Search, Jasper Reports, JMS, etc
Check them out at http://grails.org/plugins – can comment, search, etc.
Summary
- Plugins are crucial to the grails story
- Everyone is a plugin developer – not just the gurus
- Plugins help to create modular applications
- Plugins automate configuration through convention over configuration
The Gr8 Conference: Building a Twitter Clone in Grails (or why Grails rocks!)
The second day of the gr8 conference kicked off with a great presentation by Graeme Rocher on Building Twitter in Grails. Rather that giving a blow by blow of the presentation, you should check out a similar earlier presentation he gave yourself. The online presentation is close enough to the one Graeme gave to be better than my written notes. What I do want to do is comment very briefly about why I was so impressed by the presentation.
For anyone following languages and frameworks, it’s pretty easy to get jaded by all the “build an X in Y minutes” presentations. With a little bit of ORM and scaffolding, it’s pretty easy to write a framework that will let you build a simple blog in ten minutes with postings and comments (I wrote my own in two weeks in ColdFusion including extensible model and controller description in XML, a custom data mapper/baby-ORM and lightweight DI/IoC engine – it’s not a terribly hard problem to solve). What really stands out with Grails is that you can get a system with caching and a JMS message queue with transactional capabilities in under an hour!
As I mentioned in my recent GroovyMag article, the real differentiator for Grails (apart from the very simple learning curve for Java developers) is access to proven enterprise Java plumbing under the hood, with Groovy/Grails primarily being a “lipstick layer” to allow you to use Java frameworks without having to put up with the explicit configuration, static typing and lack of dynamic language features.
In an hour, Graeme demonstrated the creation of a simple Twitter client. He implemented a nice AJAX interface for posting and updated, implemented Security using the acegi plugin which wraps Spring (nee acegi) Security, added caching using ehcache, search (with the searchable plugin) using Lucene and Compass, JMS messaging for clearing the cache asynchronously with transactional integrity, and the capacity to access the page using .json or .xml file extensions and he even added a feed plugin to give you an rss feed in just a few lines of code!
Clearly any such demonstration is tied to the strengths of the framework being demonstrated, but it really showed me just how quickly you could mock up an enterprise style app that you could then just add richness to as required to (say) tie into legacy databases or more complex authentication systems. An incredibly impressive demonstration of a very compelling framework!
The sample code from the conference USB stick doesn’t quite work out of the box. You have to bootstrap a default role. In the grails-app/config/Bootstrap.groovy add:
def init = { servletContext ->
new Authority(authority:”ROLE_USER” , description:”Default User Role”).save()
}
and I’m also running into issues with null pointers for the twitter cache (conf/spring/resources.groovy – line 3: twitterCache(org.springframework.cache.ehcache.EhCacheFactoryBean))
however, I’ll have a look at this (I have a feeling anyone with Grails experience would figure this out in about 2 minutes, and I’m pretty sure I’ll be able to figure it out when I get a spare half hour to look at it – hopefully this weekend) and will post a slightly modified version of the code so anyone can download and play with the app. You *should* try this at home – it rocks! Kudos to Graeme & the Grails team!
The Gr8 Conference: Practical DSLs with Groovy
This session by Guillaume LaForge was probably the one I was looking forwards to the most. I do a lot of work with Software Product Lines, Domain Specific Modeling and Domain Specific Languages. I’d seen Neil Ford the other month at No Fluff Just Stuff Boston presenting on using Java, Groovy and Ruby for internal DSLs and I was interested to see what Guillaume would cover. Historically Groovy has been somewhere in the middle of Java and Ruby in terms of support for the kind of syntactic sugar that allows for the creation of business user readable DSLs and I was interested to see both how Guillaume presented the topic and what specific information he’d include.
He started off by introducing the problems that vertical (business – as opposed to horizontal technology DSLs like SQL or RegEx’s) DSLs are designed to solve. They allow for clean separation of business logic from application code, allow Subject Matter Experts/business analysts to read (not necessarily write) the DSLs and allow for business rules to have their own lifecycle independent of the usual re-build, re-deploy lifecycle required when the business logic is encoded in Java.
He mentioned that there are a range of possible notations for DSLs – from the “e4 – e5″ chess notations to the notations used to describe solutions for rubix cubes and sheet music notation. He then also introduced some real world examples of business DSLs such as anti malaria drug resistance simulation, hr employee skill representation, insurance policies risk calculation engine, loan acceptance roles engine for a financial platform, mathematica like lingua for nuclear safety and market data feeds evolution scenarios.
Groovy and DSLs
Groovy has a number of capabilities that make it nicer than Java for implementing business user readable internal DSLs.
- There is no need to write full blown classes – you can use scripts
- Optional typing (def) – cut down on visual noise – in scripts can even omit def
- Native syntax constructs (lists, maps and ranges – can create own custom ranges e.g. monday..friday)
- Optional params (for top level statements) and semicolons so “move(left);” becomes “move left”
- Named arguments: Can mix named and uunnamed – named params are put in a map parameter.
E.g. take 1.pill, of: Chloro after: 6.hours
== def take(Map m , MedicideQuantity mq)
- Custom control structures: when closures are last they can be put “out” of the parenthesus surrounding parameters
unless (account.balance > 100.euros , {account.debit 100 euros})
== unless (account.balance > 100.euros) {account.debit 100 euros}
Signature “def unless (boolean b , Closure c)”
- Operator overloading: -15.euros + 10.dollars, -10.kilomaters – 10.meters, taskA | taskB & taskC
e.g. a + b – just put a.plus(b) method
e.g. a – b – just put a.minus(b) method
e.g. a * b – just put a.multiply(b) method
etc.
Options for crediting an account:
account << 10.dollars
account += 10.dollars
account.credit.10.dollars
depends on users which syntax they prefer . . .
Groovy’s dynamic heart: the MOP – The MetaObject Protocol
All accesses to methods, properties, constructuors, operators, etc can be intercepted thanks to the MOP. While Javas behavior is hard wired at compile time in the class, with groovy, behavior is adaptable at runtime through the metaclass.
Different hooks for changing the runtime behavior:
GroovyObject
getProperty() , setProperty , invokeMethod() , getMetaClass() , setMetaClass()
A GO can have “pretend” methods and properties
MetaClass
Core of the Groovy MOP system
- invokeConstructor
- invokeMethpd
- invokeStaticMethod
- invokeMissingMethod
- getProperty
- setProperty
- getAttribute
- setAttribute
- respondsTo
- hasProperty
- Metaclasses can change the behavior of existing third party classes – even java one.
ExpandoMetaClass
- A DSL for metaclasses!
MoneyAbount.metaclass.constructor = { . . }
Note: 10.euros == 10.getEuros()
Class CurrencyAmount {
Number value
String currency
String toString() { “$value $currency”}
}
Number.metaClass.getEuros = { ->
new CurrencyAmount(value: delegate, currency: “EUR”)
}
10.euros
The delegate variable in closure represents the current instance, and “it” the default parameter
The Builder pattern
This is a great pattern for certain classes of DSLs. You’re probably familiar with the markup builder for XML/HTML, but how about having a builder for HR?
softskills {
ideas {
capture 2
formulate 3
}
. . .
}
knowhow {
languages {
java 4
groovy 5
}
. . .
}
Builders are a mechanism, for creating any tree structured graph – a realization of the GoF builder pattern. It uses hooks like GroovyObject#invokeMethod() to catch all non-existing method calls
Adding properties to Numbers
One of the common approaches when creating a fluent API/DSL in a dynamic language is to add properties to numbers. There are three ways of implementing this in Groovy: create a category, create a custom metaclass or use the ExpandoMetaClass.
- Create a category: A kind of decorator for default MCs. Interesting scope – thread bound and lexical, but doesn’t work across hierarchy of classes (doesn’t work for subclasses).
- Create a custom MetaClass: A full blown MC class to implement and to set on the POGO instance.
- With an expandometaclass: Works for class hierarchy for POJOs and a flag exists to make it work for POGOs too, but the catch is it’s really a global change so beware collisions with other libraries.
Compile time metaprogramming:
Groovy 1.6 now support compile-time metaprogramming via AST transformations. They are compile time, so there is no runtime performance penalty.
There are two kinds of AST transformations available:
- Global – applicable to all compilation units
- Local – applicable to marked (annotated) program elements, using specific market annotations
E.g. added @Singleton and @Delegate
To create a global transformation:
Implement ASTTransformation
Annotate the transformation specifying a compilation phrase
For discovery, create the file META-INF/services/org.codehaus.groovy.transform.ASTTransformation
Add the fully qualified name of the class to that file
Local is same as global, but don’t need to add to meta-inf – just create annotation to specify on which element the transformation should apply.
For example, the Spock framework does this using syntax highjacking with AST transformations to create a BDD framework.
You can pre-compile pogos like pojos in a spring app, but can also load on the fly to decouple the lifecycle of the business rules form that of the application. Also have eval, GroovyShell, or GroovyClassLoaader – most powerful mechanism. Could also visit or change the AST. Scripts and classes can be loaded elsewhere
Groovy DSLs CAN be embedded in groovy classes, but should store elsewhere – database, xml file, etc
Considerations to remember when designing DSL
- Start small with key concepts – beware of over engineering!
- Grow the language progressively, get hands dirty, play with end users
- Let DSL fly – theirs, not yours!
- Tight feedback loop – iterative process
- Stay humble – can’t get it right first time, don’t design alone at your desk – involve the end users from the start!
And if I might add something, check out Eric Evans book on Domain Driven Design. I did an presentation and an interview at ddd.org on using DSM for DDD’ers. I’d also argue that the DSM/DSL community could learn a lot from Erics work on eliciting and developing Ubiquitous Languages – many of which can be executable (making them DSLs).
Maybe play it safe in a sandbox
- Groovy supports usual java security model
- Use metaprogramming tricks to prevent calling or instantiating certain classes
- Create a special GroovyClasLoader AST code visitor to filter only the nodes of the AST you want to keep – e.g. the ArithmeticShell in Groovy’s sample.
- Don’t just test for nominal cases – explicitly test for errors!
- Ensure end users get meaningful error messages
Groovy is often used for mission critical DSLs . . .
That’s the notes I managed to capture from the session. I’d thoroughly recommend catching any of Guillaume’s presentations as in addition to his deep knowledge about Groovy he clearly has a robust understanding of DSM and the practical uses of DSLs. It was a great session both as an intro to DSLs and with lots of detailed information about using Groovy for implementing those languages. I certainly can’t wait to play with Groovy DSLs!
The Gr8 Conference: What’s new in grails 1.1
After Guillaume had provided us an introduction to Groovy, it was Graeme Rochers turn to introduce Grails and to provide information on the latest features in Grails 1.1(.1). Graemes deck wasn’t on the memory stick and I’m writing this on the ‘plane back to New York, so I’m writing this up from my notes and memory, so apologies in advance if I miss anything . . .
Graeme started off by giving us the number of downloads for Grails. In December of 2008, there were 86,000 downloads. To put that into context, Spring only got 90,000 downloads and Hibernate got 50,000 so while the penetration of Spring and Hibernate is clearly much greater, Grails is really starting to get some traction in terms of downloads. There are also now case studies for Wired, LinkedIn, Contegix, Tropicana, SAP and Sky (150 million visitors per month on six servers – and the eighth most responsive website in the UK, above sites like amazon.co.uk).
The main theme for Grails 1.1 is “making integrating grails into your ecosystem easier”.
Stand alone GORM
Firstly, GORM (the Groovy Object Relational Mapper – a productivity layer on top of Hibernate) is now available stand alone if you want to use it outside of grails applications.
With standalone GORM, you declare grails.persistence.Entity classes, so you might have:
package com.music
@Entity
class Album {
String name
Date releaseDate
static hasMany = [song]
}
And then you’d configure the settings using a gorm SessionFactory:
<gorm:SessionFactory
base-package=”com.music”
data-source-ref=”datasource”
. . .
</gorm:SessionFactory>
Plugin Enhancements
In Grails 1.1 there is now support for global plugins so you don’t need to install plugins for every single project if all of your projects use the same shared plugins. So you can now (for example):
grails install-plugin code-coverage –global
There is also support for transitive plugin installs. So, when you install a plugin, it automatically installs any dependencies of that plugin. Also, installing a plugin attaches metadata to the project, so if the project is checked out of svn/git, the plugins are auto-installed. There is also support for uninstalling plugins.
It’s also possible to scope plugins now, so (for example) you’d set your code coverage plugins not to run in production. You can scope plugins by environmen or by lifecycle and individual resources can also be excluded. It is also now possible to configure your own internal repositories for plugins. It is also possible to create direct links to plugin installs (rather than pulling them from a repository), supporting a workflow where you might be developing both plugins and your application simultaneously.
The core message was really that everyone should write plugins – they are a way to modularize your application and are very easy to develop. This was expanded on in a later presentation.
Testing Framework
In grails 1.0 there is little support for mocking out slow resources (such as database calls) for your unit tests. With 1.1 there is a mock api and framework for developing faster running tests. There is a mock implementation of GORM, controllers, command objects, etc. You “grails create-unit-test [name]“, and extend an artifact specific test harness.
Controller Enhancements
There are a number of controller enhancements relating to data binding, duplicate request handling and forwards/includes.
In terms of data binding, there are now more options for binding incoming request parameters to domain classes. For example, you can bind to collection types:
<g:textField name=”books[0].title” value=”the stand” />
You can also binding to a subset of properties:
person.properties["firstName","lastName"] = params
There is also now support for duplicate request handling (to stop users from submitting the same form twice):
<g:form useToken=”true” />
the withForm method then does the rest:
withform {
// good request
}.invalidToken {
// bad request
}
The current request can now forward control to another action:
forward controller:”home” , action:”index”
or obtain the response of another action with an include:
def content = g.include(controller : “home”)
View Enhancements
There is also now support for using JSP tag libs within gsp’s.
Project/Build Enhancements
There is a new api to discover the properties of the current environment. For example, you might:
import grails.util.*
assert Environment.current == Environment.DEVELOPMENT
And inspect project metadata:
assert “1.1.1″ == Metadata.current.getGrailsVersion()
Grails projects can now be Maven projects
mvn grails:create-pom
mvn grails:run-app
mvn package
Grails projects can also now be build with Ant and Ivy.
Additional Enhancements
There is now Spring namespace support in Grails. You can use any spring namespace in BeanBuilder:
xmlns aop:”http://www.springframework.org/schema/aop”
xmlns jee:”http://www.springframework.org/schema/jee”
Grails 1.1.1 now includes support for GAE. Persistence is via JDO/JPA using big table and there is a command line deploy. The process is something like:
grails create-app myapp
cd myapp
grails uninstall-plugin hibernate
grails install-plugin app-engine
grails set-version 1
grails app-engine package
APPENGINE_HOME/bin/appCfg.sh update .target/war
They are working on GORM JPA to make it work with app engine.
Graeme did a great job of introducing the latest enhancements to Grails in just an hour. If you want to know more about where Grails is going next, the roadmap is available at http://grails.org/roadmap.
The Gr8 Conference: What’s new in Groovy 1.6
After Dierks presentation, Guillaume LaForge was up next, providing an overview of the features of Groovy 1.6(.3). He covered a lot of materials – much of which is contained in his recent InfoQ article.
Introducing Groovy
He started with a brief introduction to Groovy. It’s a dynamic language on the JVM, it provides a Meta Object Protocol which allows for meta-programming techniques such as intercepting method calls. It compiles down to byte code, it’s an open source Apache licensed project and has a relaxed grammar derived from Java 5 (most Java code is valid Groovy code). It borrows ideas from other dynamic languages such as Smalltalk, Pyton and Ruby, has Java 5 features out of the box (annotations, generics, static imports, enums, etc) and with a flat learning curve for Java devs and the ability to run on the Google App Engine (check out http://groovyconsole.appspot.com), it’s really quick and easy to get started with.
Groovy is fully OO (no primitives, so you can add methods to numbers and write things like 1.day just like you would in Ruby), there is a joint compiler with the capacity for resolving circular dependencies between Java and Groovy code, it supports Closures, properties (no getters/setters required), optional typing and BigDecimal arithmetic by default for floating point numbers. There are handy APIs for XML, JDBC, JMX, templating and Swing UI’s, a strong ability for writing business user readable Domain Specific Languages, syntax level “builders” and it supports easy operator overloading (if you want to write 10.meters + 20.kilometers, for example).
It supports lists “def numbers = [1,2,3,4]“, maps “def map = [FR: 'France] , BE: ‘Belgium’]” and ranges “def allowed = 18..65″. It allows for regular expressions, and has GStrings which are interpolated strings which allow for placeholder variable replacements “Hello ${FirstName}”. Triple double-quotes also allow you to create multi-line strings without having to concatenate the strings as you would in Java.
One of the key features of Groovy is support for Closures. These are reusable and assignable code blocks (anonymous functions). So for instance, you could write:
def greet = {println “hello ${it}”}
greet(“Guillame”)
You can pass parameters to closures:
def greet = {string name -> println “Hello ${name}”}
and you can pass closures around:
def method(Closure c) { c(“Hello”)}
method(greet)
They take a bit of getting used to, but can provide a great deal of expressiveness in your code as you get the hang of how and where to use them.
One of Groovys other great features is a set of builders. For example, the following script uses a markup builder to generate HTML (it could also be used for XML):
def mkp = new MarkupBuilder()
mkp.html {
head {
title “Groovy in action”
}
body {
div(width: ‘100′) { p(class: ‘para’) {span: ‘best book ever’}}
}
}
}
Groovy 1.6
After providing a brief overview of Groovy, Guillaume then went on to introduce the key improvements in the recently released Groovy 1.6.
Firstly, it’s faster – both at runtime and at compile time. groovyc tests 3-5 times faster than the 1.5 compiler and with advanced call-site caching techniques, he’s seen 150-460% increases in performance over 1.5 (although obviously your milage will vary).
There are also syntax enhancements with support for multiple variable assignment:
def (a , b) = [1 , 2]
def lat , long
(lat , long) = geocode(‘Paris’)
(a,b) = [b,a]
If there are mismatches in the number of elements, extra elements on the left just aren’t assigned to anything. If there are less elements on the left, nulls are put into the additional values on the right hand side of the assignment operator.
With Groovy 1.6 there is also support for optional returns in if/else and try/catch blocks. So you could write:
def method() {if (true) 1 else 0}
Groovy 1.6 also provides full support for Java 5 annotations. It is the only dynamic language to provide this feature.
Compile time meta-programming
Meta-programming is the ability of a program to modify itself. Groovy 1.6 adds support for Abstract Syntax Tree (AST) transformations, which should allow us to get rid of a lot of boilerplate technical code. Groovy supports two kinds of transformations: global transformations, and local transformations that are triggered by annotations.
Out of the box, Groovy 1.6 comes with annotations such as @Singleton, @Immutable, @Lazy, @Delegate, @Nawify, @Category and @Mixin. Each saves you from writing a bunch of boiler plate code and allows you to more clearly express the intent of your code. You can also add your own global or local ASTs. It’s a technique you want to use sparingly as it would be easy to introduce hard to track down bugs where certain combinations of annotations introduced errors when they were used together, but it’s a great technique to have and something I’m going to be playing with and writing about more on this blog.
Guillaume also reviewed a number of other enhancements that have been added to Groovy 1.6. We now have Grape – the “Groovy Advanced Packaging System” which helps you to distribute your applications without having to include dependencies. You just declare the dependencies with @Grab and it’ll get them from Maven or Ivy repositories. @Bindable makes it easier to do data binding in swing, and the swing console application can now be run as an applet, has code indent support, script drag and drop and the ability to add jars to the classpath from the IDE.
The ExpandoMetaClass DSL is another new feature that I’ll be covering in more detail on the blog, but briefly, it’s a DSL for changing the behavior of types at runtime. There is also the support for runtime mixins:
JamesBondVehicle.mixin FlyingAbility
In addition, Groovy 1.6 had JSR-223 bundled, so if you simply can’t get through the day without adding a little Python or PHP to your Groovy, it’s supported out of the box. There is also a JMX builder available (http://groovy.codehaus.org/groovy+jmxbuilder). Finally, the Groovy 1.6 JAR contains OSGi metadata and can be used in OSGi containers (http://groovy.codehaus.org/osgi+and+groovy).
With only on hour to both introduce Groovy and provide an overview of the new 1.6 features, it was a high level presentation, but it was a great introduction to the language and provided a good overview of the latest additions to the language.
The Gr8 Conference: Groovy Usage Patterns
Most of the attendees at the conference would love to use Groovy or Grails for projects, but many companies are still in the evaluation phase. The question Dierk Konig tried to answer in his session was “what are some of the different ways you can introduce Groovy and Grails to client projects?”. He identified seven common patterns for introducing Groovy and/or Grails into projects: superglue, liquid heart, keyhole surgery, smart configuration, unlimited openness, house-elf scripts and the prototype.
1. Super Glue
Java makes a perfect infrastructure layer. With proven frameworks, widget sets and services it can provide a robust underlying layer for applications. Scripting can provide a more flexible and agile application layer on top of the infrastructure layer in Java for pulling together the capabilities of the frameworks into a custom application more quickly than if you were to use Java for the entire application. This approach allows you to build on the strengths of Java but to make it quicker/easier to use for developing applications. It also allows developers to leverage all of their experience in using Java frameworks.
2. Liquid Heart
This is almost the opposite of the super glue pattern. With the liquid heart, you have a well defined application structure developed in Java, but you use Groovy to implement fast changing business rules such as calculation rules for bonus allocations. By creating a clear bounded context, you can then use Groovy to more elegantly express a Ubiquitous Language for implementing the business rules in a particular area of the application. Good candidates for this are areas of the application with complex business rules that change frequently, making them a good candidate for a Domain Driven Design/Domain Specific Language based approach.
3. Keyhole Surgery
Sometimes you just need to be able to see what’s going on with your application and to be able to run code against it that you can modify without having to recompile the entire application. With keyhole surgery, you can create a back door for the live execution of Groovy scripts. This pattern is particularly useful for product support, failure analysis, hot fixes and emergencies.
4. Smart Configuration
If your team is concerned about writing application code in Groovy, often a good starting point is to use it for smart configuration, enhancing configuration with logic and replacing XML files with much more concise and expressive Groovy scripts. By having all of the power of a Turing complete language, you can often express the intent of the configuration much more elegantly and meaningfully than with large XML files.
5. Unlimited Openness
Especially for small to mid-sized green field projects, it can often make sense to go “all script”, creating an application that can be more concise and expressive, whether leveraging Grails or Griffon or just working directly in Groovy. The only proviso I’d throw out with this is that you need to consider the complexity of the application and the maturity and size of your dev team. Larger teams (really more than 3-5 people), relatively new to dynamic languages can get into all kinds of trouble by overusing dynamic language meta-programming features to the point where nobody on the team actually knows how the application works!
6. House-elf Scripts
If you want to get a quick win using Groovy, look at creating ad-hoc scripts. From build automation to installers, service monitoring, reports, statistics, automated documentation, functional tests, html scraping, web remote control, and web services there are lots of ways to get familiarity and to build comfort within your team by implementing these kinds of incidental scripts in Groovy.
7. Prototype
Sometimes you just want to do a feasibility study – a quick spike to try out a technology, UI or set of algorithms. Groovy, Griffon and/or Grails can be perfect for those kind of quick prototypes. And if you write them well there is no reason why you can’t either use them in production or port some/all of the parts of the application to Java down the line. For example, at Canoo, instead of a written RFQ they’ll often just build out a sample application to give the clients a sense of how it would work.
In addition, Dierk mentioned a couple new patterns he’s formalizing. The “lipstick” pattern is an increasingly common pattern of wrapping a Java API with a thin layer of Groovy to make it easier to work with and the “ghost writer” pattern describes the times when you use (for example) annotations and AST transformations to enhance a Groovy API by adding functionality using meta-programming.
The session really did a good job of providing a language for describing different ways of thinking about how to introduce Groovy and Grails into projects and hopefully we’ll be able to start to use this language within the community when describing potential adoption strategies to both give us more ideas on how to start to use Groovy and a more efficient vocabulary for sharing our experiences.