Archive for the ‘gr8’ Category
Do you know Everything About Groovy and Grails? Gr8 Copenhagen Coming up Soon
It’s tough. Keeping up with a framework (Grails) on top of a fairly new, quickly evolving language (Groovy) which in turn is built using evolving frameworks (Hibernate, Spring, SiteMesh and via plugins Quartz, Lucene and many others) in a language – Java – which continues to develop (if only at a glacial pace). I notice on the mailing lists that even the top luminaries in the field are occasionally flummoxed by a question. It’s just not possible to know absolutely everything about Groovy and Grails. The good news is that while an individual may not know everything, as a community we know a lot more. The mailing lists are a good resource, but as the community grows you don’t always get an answer to your questions on the lists. What to do?
The answer for me is to do what I’ve done in every other domain I’ve been involved with – get involved with the community. (I’m relatively new to Groovy and Grails, but I’m pretty involved in the Domain Specific Modeling and ColdFusion communities). Helping out on the mailing lists and contributing to plugins is a great way to get started, but it’s hard to beat the face to face interactions you get at user groups and (especially) at conferences. That’s why I decided to go to gr8 in the US, am presenting on DSLs in Sydney, New York and (hopefully) London this month, and will be attending gr8 in Copenhagen next month (even though I can only manage a day as I’m presenting at the BCS SPA conference on DSL design on the Wednesday).
I was lucky enough to attend Gr8 last year. It was an amazing chance to get to know many of the key developers in the community, to build up a set of resources so that if we do ever get stuck on a technical challenge we can get on IM and often get an answer or idea from someone in minutes instead of hours or days of futzing around. Why do I mention this? Well, Gr8 conference is the only dedicated Groovy and Grails conference in Europe and a great opportunity to learn about a whole range of projects within the Groovy ecosystem – including Grails, Griffon, Spock, Gradle and Gaelyk. More than that, it’s a chance to meet up with other developers dealing with the same adoption, implementation and technical challenges that you work with every time you develop a Groovy based project.
There is still time to register for the conference, so think about how much it costs when you’re stuck on a project for a day trying to figure things out, and I hope you can get a cheap flight, a modest hotel and a ticket to the conference into the budget. It’s not cheap, especially with the market right now, but the only thing more expensive than going to the conference? Working on a project in Groovy/Grails and being stuck *not* having gone to the conference for the amazing technical content and great networking.
Hope to see you there! (If you see me, please say “hi”) – I’ll be the jetlagged one drinking too much Red Bull
gr8 conference in the US on Friday
I’m really looking forward to attending the gr8 conference in Minneapolis this Friday. I have been doing more and more Groovy and Grails projects recently and am looking forward to get to know the broader US community (the Copenhagen conference last year was great – but there weren’t that many US attendees).
I’ll be writing an article for Groovy Mag on the conference, so if you are presenting and would like to be interviewed briefly, I’ll be in the conference hotel Thursday evening and all day Friday (I’m flying back to NYC first thing Saturday) so make yourself known (a tweet to @peterbell is probably the easiest option) and I look forward to meeting you!
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.
