Groovy-Grails
Grails: The View Layer [GUM]
by Colin on Feb.04, 2010, under Groovy-Grails
This past month, I did a presentation at the Groovy Users of Minnesota which I called Grails: The View Layer. We took our time delving into the Groovy Server Pages, how Grails utilizes Sitemesh and some of the more obscure tags related to Sitemesh. Currently, Grails’ Sitemesh integration is not very well understood by the community at large and I wanted to spend some time on it since Sitemesh is such a powerful part of the Framework.
I was hoping to spend some more time polishing this slide deck, but hopefully this presentation skeleton is helpful to the community as it is. I am hoping to give this talk again at Gr8Conf in the USA this upcoming April and spend some more time creating more concrete and digestible examples.
Grails user-specific configurations
by Colin on Nov.26, 2009, under Groovy-Grails
I asked a question on the GUM (Groovy Users of Minnesota) User list about how to achieve a user/machine specific config.
I didn't have much time to figure it out but this is what I ended up finding out:
Grails 1.1.1 create-app generates a Config.groovy with this as the first few lines that would have told me what I need to know if I actually took the time to read it:
// locations to search for config files that get merged into the main config
// config files can either be Java properties files or ConfigSlurper scripts
//
// grails.config.locations = [ "classpath:${appName}-config.properties",
// "classpath:${appName}-config.groovy",
// "file:${userHome}/.grails/${appName}-config.properties",
// "file:${userHome}/.grails/${appName}-config.groovy"]
//
// if(System.properties["${appName}.config.location"]) {
// grails.config.locations << "file:" + System.properties["${appName}.config.location"]
// }
So in my case all I had to do was put this in Config.groovy:
if (new File("${userHome}/.grails/${appName}-config.groovy").exists()){
grails.config.locations = ["file:${userHome}/.grails/${appName}-config.groovy"]
}
which allowed me to override properties by doing something like this in my ~/.grails/${appName}-config.groovy :
username = "sa"
password = "sekret"
// environment specific settings
environments {
development {
dataSource {
dbCreate = "create-drop" // use your imagination...
}
}
}
I also ran across a little gem that you can do the same type of config merging with your BuildConfig.groovy by implementing a ~/.grails/settings.groovy file. (yes its hardcoded rather than a config.locations property in BuildConfig.groovy – see BuildSettings.groovy for more)
Now I really wish there was a way to set defaults for things like server.port in the configs.
Thanks, Ted Naleid, Scott Vlaminck, and Robert Fischer for helping me find what I was looking for!
Grails BOF recording at SpringOne2GX
by Colin on Oct.24, 2009, under Groovy-Grails
SpringOne2gx was a blast this year. It was great to get to know many members from the community!
I was able to record the Grails BOF (Birds Of a Feather) session at SpringOne2gx this year: Download it Here (80MB)
Big thanks to SpringSource and No Fluff Just Stuff for putting together an awesome conference!
Props to Dropbox for allowing me to share this recording.
VMWare acquiring SpringSource which Acquired G2One
by Colin on Aug.10, 2009, under Groovy-Grails
Wow, Big news for the Groovy and Grails Community! VMWare has announced that it is acquiring SpringSource. Rod Johnson, the founder of SpringSource and Initial author of the Spring Framework also posted his thoughts on SpringSource’s blog calling it ‘SpringSource – Chapter Two’. I don’t think that too many of us saw this one coming. Now its time to wait until Oracle acquires VMWare If Marcel Overdijk’s prophecy is true
I’m not that familiar with SpringSource’s offerings, but It does seem like some of VMWare’s products are a natural extension to the goals that SpringSource is trying to accomplish with their Build / Run / Manage mantra. The two companies don’t really compete, but VMWare + Grails seems like a good combo to me
Jerome Gagner blogged about how VMWare should throw in some terracotta for some extra spice to take on (read ‘out’) Windows Azure.
I must say that PaaS offerings look really appealing to me as a developer. Even though I *can* manage machines and hardware, I don’t want to have to take on the risks and responsibilities. I’m not quite sure what they are going to accomplish together but VMWare + Grails + SpringSource Technologies as a PaaS solution sounds good to me.
Grails Growl-like notifications in Linux (Ubuntu, 9.04)
by Colin on May.24, 2009, under General, Groovy-Grails, Linux, Ubuntu
When I was developing on OSX, a fellow developer Ted Naleid tipped me off to a script that does Growl notifications for Grails events that Marc Palmer had written. The Growl notifications were handy, but now that I’ve been working on Linux, I’ve definitely missed them.
I first used a tool called Mumbles, which attempted to be a clone of Growl, but I later realized that the built in notification system is probably the way to go. After I learned of Ubuntu 9.04 (Jaunty Jackalope) had some major visualization enhancements to the notifications, I thought that it was definitely the way to go.
This is what I currently have with Ubuntu 9.04:


Implementing this is very simple, you simply create an _Events.groovy file in your ~/.grails/scripts directory (create it if it doesn’t exist) with the following contents (modified from the Growl Script):
eventStatusFinal = { msg ->
libNotify('Final status', msg)
}
eventStatusUpdate = { msg ->
libNotify('Status', msg)
}
eventCreatedFile = { fileName ->
//libNotify('Created file', fileName)
}
eventStatusError = { message ->
libNotify('Error', message)
}
eventExiting = { code ->
libNotify('Exit', "Return code $code")
}
eventCreatedArtefact = { type, file ->
libNotify('Created artefct', "$type with name $file")
}
eventCompileStart = { kind ->
//libNotify('Compiling', "Compiling $kind")
}
eventCompileEnd = { kind ->
//libNotify('Compilation complete', "Compiled $kind")
}
eventPluginInstalled = { pluginName ->
libNotify('Plugin installed', pluginName)
}
// Do the notification
void libNotify(title, message) {
def cmd = [
'notify-send',
title,
message,
'-i',
'grails'
]
cmd.execute()
}
It is simply using Groovy to execute "notify-send $title $message -i grails". if you don’t have notify-send, it is part of libnotify so sudo apt-get install libnotify-bin will get you what you need. If I get some time I’d like to find a way to take advantage of a Java Dbus implementation to talk to the notification system without having to go through libnotify.
If you want mumbles notifications just do something like this:
void mumblesNotify(title, message) {
def cmd = [
"mumbles-send",
"-l",
title,
message
]
cmd.execute()
}
Occasionally I’ll get a failure that there are too many files open (using .execute() in Groovy) and that should be cleared up by using a Java implementation of the DBus notifications.
Let me know what you think. Anything that could be done better?
Groovy and Grails IDE Shootout
by Colin on Feb.11, 2009, under Groovy-Grails
Last night at the Groovy Users of Minnesota (GUM) meeting we did an IDE shootout where we covered Groovy and Grails support in the more popular IDEs.
Jesse O’neill-Oine from Refactr started us off with TextMate.
I (Colin Harrington) presented on Eclipse and Netbeans:
Hamlet D’arcy teamed up with Matt Abrams & Bob Schultz to close out the night with Jetbrains‘ IntelliJ-IDEA.
Ironically IntelliJ-IDEA 8.1 was released the very next day. Hamlet has some good tips on his blog about Intellij-IDEA.
This is an ever improving topic and changes very rapidly, so If we missed anything just drop us a comment
Special thanks to Guillaume Laforge, Petr Hejl, Sven Haiges of the Grails Podcast as well as everyone who has contributed to the community via blogposts, documentation updates, etc.
Enjoy.
GORM :: override a setter on a Grails Domain
by Colin on Jan.08, 2009, under Groovy-Grails
Rather than implement properties in the Java Language, we have a convention called a Java Bean. This basically means that properties are implemented with getter and setter methods with a PascalCase property name in the method among a few other simple conventions.
Grails makes it incredibly easy to manage domain classes since it is inherently domain-centric. When you need to enhance your Domain classes at the core of your application, you have an option of implementing your own getters and setters. I love that by default you do not have to implement your own setters, but you have the power to do so if you wish; the principle of sensible defaults. Here is an example of a Book Object with two properties, author and isbn.
class Book {
String author
String isbn
}
Consider the case where a Book is in your Database with the ISBN of 978-1430219262 and a user tries to search for "9781430219262". Unless you do some searchable magic, the user will not find the book. A simple solution fo the issue would be to never store ‘-’ in the databse. to make this happen you could easily remove the dash in the setter. So your domain would look like this:
class Book {
String author
String isbn
void setIsbn(String i) {
isbn = i.replace('-','')
}
}
When I first tried this, I failed a few times before I got it right. Maybe I was just spoiled with Groovy’s groovyness, but I started out writing
def setIsbn(i){ ... } and when that didn’t work: void setIsbn(i){ ... } which was being called, but never actually set the property. Then I had a forehead smacking moment where I realized that the method signature must precisely match the signature of a JavaBean setter like public void setPropertyName(Type propVal) { ... } In my case I had to make sure that the method was public (public by default), has a return type of void (which is not the default behavior of a closure), and the parameter passed in was of the same type as the property (String)
And then I blogged about it — the fourth day.
GSF :: Groovy Server Faces?
by Colin on Nov.09, 2008, under Groovy-Grails
Has anyone tried to make Java Server Faces (JSF) more groovy?
Not having done anything with JSF directly, I’m not sure what could be groovified, but I’d imagine that Groovy + JSF might make JSF more attractive to a certain type of developer. I’m familiar with the some of the .NET component paradigms and can imagine what it would be like in Java
From the little that I have heard/read, I understand that some of the pain in JSF is related to XML configuration. Groovy does XML quite beautifully and could provide some much needed value to that space. Any other areas that Groovy + JSF would shine? Am I completely off base? Again, I’m not an expert in JSF, but it may warrant a question to the Groovy User list.
Groovy Elvis Operator?:
by Colin on Oct.30, 2008, under Groovy-Grails
What is this Elvis Operator I vaguely recall? I’ll get to that just bear with me for a minute.
In Java I’ve seen too many null checks like the following:
If (something != null) {
val = something
} else {
val = defaultValue
}
Its handy to have the Groovy Truth so we don’t have to do null checks. Instead of writing if (something != null) { ... } we write if (something) { ... }
Well this type of branching logic is precisely why we have the ternary operator in both Java and Groovy. I’m surprised that the ternary operator is neglected by many developers. It turns our 4 lines of if/else logic into a single line like:
val = something ? something : defaultValue
The syntax and logic for the ternary operator is the same in Groovy as it is in Java; (Condition) ? Value-If-True : Value-If-False I’m not going to get into a lesson on the ternary operator and you can certainly read more here.
When using the ternary operator I had to repeat the variable something twice to do a simple check; This isn’t groovy and it definitely doesn’t lend itself to the principles of DRY! *Queue the Elvis operator*
Instead of writing: val = something ? something : defaultValue
We write: val = something ?: defaultValue
A more clear example would be as follows:
def rockstar
def defaultrockstar = rockstar ?: "Elvis Presley"
assert defaultrockstar == "Elvis Presley"
*Thank you Satish for the example
InfoQ also has an excellent example under the section Syntax Additions :: Elvis Operator.
It is nothing too special but It ends up being closer to how we think about code. Apparently the Elvis Operator was added in Groovy 1.5 and is called the ‘Elvis Operator’ due to its resemblance of Elvis’ trademark hair.
I find the Elvis operator useful, but I still find myself frequently repeating myself when dealing with the same variable.
def rockstar
rockstar = rockstar ?: "Elvis Presley"
If we have gone this far with the Elvis Operator, why not go the extra step and introduce something like long-eyed-elvis ?= or call it the Rick Astley Operator
def rockstar
rockstar ?= "Elvis Presley"
This would be effectively the same as:
rockstar = rockstar ? rockstar : "Elvis Presley"
or
rockstar = rockstar ?: "Elvis Presley"
One more for Good measure … rockstar.
More Reading on the Elvis Operator:
- http://maas-frensch.com/peter/2007/12/19/how-elvis-showed-me-a-neat-way-of-using-operators-in-ruby/
- http://www.codecommit.com/blog/scala/implementing-groovys-elvis-operator-in-scala
- http://jfkbits.blogspot.com/2008/02/call-by-name-yo-elvis.html
- http://docs.codehaus.org/display/GROOVY/Operators
?;-)
Grails (Jetty) and crossdomain.xml
by Colin on Jul.13, 2008, under Groovy-Grails
This last April I did a presentation at the Twin Cities Code Camp on Microsoft Silverlight and SOA with a Grails server. I ended up writing a simple Grails application that used several web services to communicate to an in-browser Silverlight application. I specifically wanted to show a Silverlight application interacting with non Microsoft Technologies. I developed the Grails application on Linux on a different physical machine than what I used to develop the Silverlight application.
One of the Issues I ran into was that I was unable to make requests to the XML Web Services in the Grails application. It puzzled me for a minute until a quick Google search turned up a simple issue: I needed a crossdomain.xml policy file (or the clientaccesspolicy.xml). Flash/Flex users run into this all the time and thus most of what you will find is Flash centric. What is the crossdomain.xml file? Well its a way of restricting the domains that can access services. Its basically a white-listing of domains that are allowed to access the services. The browser and in-browser applications are supposed to respect the crossdomain.xml, and sometimes the Services (server-side) may protect themselves. You can think of it as a robots.txt for Web services.
Great, I knew what the problem was, now how do I fix it? I tried a few things, deploying to tomcat, but that didn’t work for me while I was actively developing the application. Once I understood a little more about Grails and Jetty, I realized that I could just modify the Jetty server that launched when invoking grails run-app. I simply had to add another context to Jetty, and bingo it worked. Here is what I did:
I found Grails’ RunApp.groovy script (the one that gets invoked on grails run-app) which was located at $GRAILS_HOME\scripts\RunApp.groovy. (%GRAILS_HOME%\scripts\RunApp.groovy for you Windows folk
). I had to simply create another context much like the Grails application context was being created. Here is a stripped down example of what RunApp.groovy looked like. (modifications in Bold)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/**
* Gant script that executes Grails using an embedded Jetty server
*
* @author Graeme Rocher
*
* @since 0.4
*/
...
grailsContext = null
rootContext = null
...
target( configureHttpServer : "Returns a jetty server configured with an HTTP connector") {
...
setupWebContext()
setupRootWebContext()
server.setHandler( webContext )
server.addHandler( rootContext )
...
}
target( setupRootWebContext: "Sets up the Secondary Root Context"){
rootContext = new WebAppContext("${basedir}/web-app-root","/")
}
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Most of the magic is in the rootContext = new WebAppContext("${basedir}/web-app-root","/") line. Notice that I had to create a new folder ‘web-app-root’ which resided alongside web-app (I think I used web-app for a while too). So this context responds to everything in the "/" domain which is the root of the site. Once I put my crossdomain.xml file in that folder, I could access http://localhost:8080/crossdomain.xml and the services were then accesible via Silverlight — Yay!
I’m sure there are better ways of doing this, but this is what I did to get the job done. Thanks to JT Dev for his most recent post, which reminded me that I was going to blog about this. I basically did Solution #2 in his blog post on creating multiple jetty contexts. Where was this post back in March? Thanks JT for tipping me off to the Static Resources Plugin!