There is a great article up on InfoQ demonstrating how to use Grails with an EJB3 compliant domain model. The article is by Jason Rudolph author of another excellent article on using Grails with legacy database systems.
Thanks for another great contribution Jason!
Thought's about software, Grails, Java, web development and anything else that comes to mind.
Tuesday, August 22, 2006
Monday, August 21, 2006
Closures in Java: Is it too late?
So the interesting news broke that their is finally a proposal for closures in Java. My immediate feeling? Well for one the verbosity of the syntax proposal concerns me deeply, it is one of those things that unless it was thought of from the start will always be a problem to retrofit back into the language. The implications here is that we have a less than ideal proposal for the syntax when you compare it to say, Groovy's or Ruby's equivalent.
Is it too late now? My feeling is yes, Java has been around for a decade now. It has jumped several iterations to Java 5 (with Java 6 coming shortly) and the APIs have progressed hugely. The implications of adding closures would be huge, you would have to go back and revisit ALL the Java APIs. I mean, if closures had been around since the beginning the collections API would be entirely different. As would other things like the way we deal with transactions and file I/O.
Don't get me wrong I think it is great that they are considering it, even if it is a decade too late, but it will take a long time for the real effects to be felt until the APIs are made closure-aware.
Is it too late now? My feeling is yes, Java has been around for a decade now. It has jumped several iterations to Java 5 (with Java 6 coming shortly) and the APIs have progressed hugely. The implications of adding closures would be huge, you would have to go back and revisit ALL the Java APIs. I mean, if closures had been around since the beginning the collections API would be entirely different. As would other things like the way we deal with transactions and file I/O.
Don't get me wrong I think it is great that they are considering it, even if it is a decade too late, but it will take a long time for the real effects to be felt until the APIs are made closure-aware.
Friday, July 28, 2006
Mac OS X: Another switcher in the bag
Well after a period of sustained resistence, I finally could cope no longer and am writing this particular entry on my new MacBook via safari. I've had it for a couple of days now and having no real prior experience with Macs besides playing with them in the Mac store it has been nothing short of a revelation.
Yes I had read Cedric's comments prior to my Mac experience and although he raises some valid points, I have to say after 3 days with the machine I'm not sure what took me so long to make this decision.
The experience starts when you get the package with the usual emaculate packaging, from then as soon as you turn on the machine yo notice the attention to detail. Yes some may call the welcome in a million languages cheesy, but you know that somebody out there has spent a lot of time making sure this is a great product. Then you go through the start-up phase and everything "just works". It hooked up to my wireless router with no problems, no fighting with networking settings and drivers like in Windows. Updates were then automatically installed and I was ready to go.
The interface is quite simply light years ahead of Windows and I'm not sure even Vista (yes I've tried the betas) comes anywhere near it. Video is extremely slick with QuickTime and looks simply stunning on the glossy screen and the amount of value you get with the included iLife suite (plus the super cool Front Row) is awesome. After adding the machine to my Windows workgroup it automatically saw the other windows machines on my network and I could start copying data onto it.. no problems.
I then started installed my beloved IDEA (which I had to abandon for Eclipse for a period on Windows because the Sun VM persistently crashed forcing me to fall back to JRocket which I couldn't get to work with IDEA) using the remarkable install process: Download dmg, it automatically (after showing a "are you sure" dialog) loads a window with an IDEA logo in it, Drag-and-drop the IDEA logo to your Applicaiton folder and you're done! No progress bars, no install wizards, amazing. And of course because jdk1.5 comes with Tiger, again all Java apps including Grails "just worked".
One of Cedric's concerns was task switching and I am also a former Task Switch Pro user on Windows, but I gotta say I don't miss it! Expose simply blows all other task switching systems out the window. I'm constantly using it and was quite amazed at one point when I had a QuickTime video playing which shrunk along with the others windows without the video jerking or getting confused. You could continue to watch the video whilst monitoring other processes (like your ant build ;-).
One of the first things I installed was the much vaunted QuickSilver. This application is amazing, I installed the Gmail plugins and can search for an image, resize it, and attach it to an email automatically addressed to somebody in Address book all with a few keystroke combinations. I find the combination of QS and SpotLight mean I very rarely open Finder (like Explorer on windows). No more browsing heirarchies of files looking for the right one, they're all accessible immediately via powerful search combined with expressive QS actions.
So, what don't I like or what do I miss from Windows? Well not a great deal actually. I kind of miss the Windows maximize button as the "zoom" in Mac OS X is just not the same thing and takes some getting used to. Other than that there is not much to miss from the Windows world, everything I need and use is available for the Mac and if I'm desperate I can run Windows via Parallels. I'm really happy with my decision to switch and there is no going back now, not that I would want to!
Yes I had read Cedric's comments prior to my Mac experience and although he raises some valid points, I have to say after 3 days with the machine I'm not sure what took me so long to make this decision.
The experience starts when you get the package with the usual emaculate packaging, from then as soon as you turn on the machine yo notice the attention to detail. Yes some may call the welcome in a million languages cheesy, but you know that somebody out there has spent a lot of time making sure this is a great product. Then you go through the start-up phase and everything "just works". It hooked up to my wireless router with no problems, no fighting with networking settings and drivers like in Windows. Updates were then automatically installed and I was ready to go.
The interface is quite simply light years ahead of Windows and I'm not sure even Vista (yes I've tried the betas) comes anywhere near it. Video is extremely slick with QuickTime and looks simply stunning on the glossy screen and the amount of value you get with the included iLife suite (plus the super cool Front Row) is awesome. After adding the machine to my Windows workgroup it automatically saw the other windows machines on my network and I could start copying data onto it.. no problems.
I then started installed my beloved IDEA (which I had to abandon for Eclipse for a period on Windows because the Sun VM persistently crashed forcing me to fall back to JRocket which I couldn't get to work with IDEA) using the remarkable install process: Download dmg, it automatically (after showing a "are you sure" dialog) loads a window with an IDEA logo in it, Drag-and-drop the IDEA logo to your Applicaiton folder and you're done! No progress bars, no install wizards, amazing. And of course because jdk1.5 comes with Tiger, again all Java apps including Grails "just worked".
One of Cedric's concerns was task switching and I am also a former Task Switch Pro user on Windows, but I gotta say I don't miss it! Expose simply blows all other task switching systems out the window. I'm constantly using it and was quite amazed at one point when I had a QuickTime video playing which shrunk along with the others windows without the video jerking or getting confused. You could continue to watch the video whilst monitoring other processes (like your ant build ;-).
One of the first things I installed was the much vaunted QuickSilver. This application is amazing, I installed the Gmail plugins and can search for an image, resize it, and attach it to an email automatically addressed to somebody in Address book all with a few keystroke combinations. I find the combination of QS and SpotLight mean I very rarely open Finder (like Explorer on windows). No more browsing heirarchies of files looking for the right one, they're all accessible immediately via powerful search combined with expressive QS actions.
So, what don't I like or what do I miss from Windows? Well not a great deal actually. I kind of miss the Windows maximize button as the "zoom" in Mac OS X is just not the same thing and takes some getting used to. Other than that there is not much to miss from the Windows world, everything I need and use is available for the Mac and if I'm desperate I can run Windows via Parallels. I'm really happy with my decision to switch and there is no going back now, not that I would want to!
Tuesday, July 18, 2006
Groovy/Grails Seminar & Grails 0.2 Release
Little late in blogging about this as I've been a little busy recently, but the Groovy & Grails seminar went splendidly well. The audience were fanstastically enthusiastic and asked some really good questions which prompted some excellent discussion. Overall a great success and I look forward to the next one.
Thanks again for SkillsMatter for hosting it, I had the pleasure of putting some faces to names whilst I was there which was great. The slides that Dierk and I presented can be found here: http://www.skillsmatter.com/groovy-grails-seminar
Shortly after the seminar we decided to put out Grails 0.2 which is numerous improvements (see the news on the Grails site for details) and features. Thanks to all those who contributed to the release!
PS For the observant out there you will notice that the slides I presented look suspiciously similar to the ones I delivered at JavaOne ;-)
Thanks again for SkillsMatter for hosting it, I had the pleasure of putting some faces to names whilst I was there which was great. The slides that Dierk and I presented can be found here: http://www.skillsmatter.com
Shortly after the seminar we decided to put out Grails 0.2 which is numerous improvements (see the news on the Grails site for details) and features. Thanks to all those who contributed to the release!
PS For the observant out there you will notice that the slides I presented look suspiciously similar to the ones I delivered at JavaOne ;-)
Friday, June 30, 2006
Upcoming Groovy/Grails Seminar in London
If you're up for being in London on the 13th of July we're holding a Groovy & Grails seminar at the office's of Open Source training company SkillsMatter. Dierk Koenig, author of the upcoming book Groovy in Action by Manning, will be there presenting Groovy and yours truely will be giving a presentation on Grails. Pop along if you're interested!
Wednesday, June 21, 2006
Grails + Legacy DB + Hibernate XML
There is a simply splendid 4-page(!) article written by Jason Rudolph taking you step-by-step with screenshots and all to get a scaffolded Grails application working with a legacy MySQL database using Hibernate XML mapping.
This really demonstrates the power that Grails has to offer in terms of being simple on the surface, but having all the power of Hibernate underneath. Note that Jason could equally have written his domain model and Java and used annotations to achieve the same effect. See the page on Grails' Hibernate integration in the user docs for more info.
This really demonstrates the power that Grails has to offer in terms of being simple on the surface, but having all the power of Hibernate underneath. Note that Jason could equally have written his domain model and Java and used annotations to achieve the same effect. See the page on Grails' Hibernate integration in the user docs for more info.
Monday, June 05, 2006
Grails & EJB3 Entity beans
One of the features that I mentioned at JavaOne that got people all excited was Grails' support for EJB3 entity beans. Grails comes with it's own ORM solution built on-top of Hibernate called GORM, but because of this relationship with Hibernate Grails domain models can also be written in Java.
One way to do this is to use the EJB3 annotation support in Hibernate which will of course allow you to use all the power the API offers in terms of mapping onto legacy systems. Clearly this is all not that exciting so far, what is really exciting is that even though the EJB3 entities you've created are written in Java and mapped using Java persistence annotations you can still use all those fantastic dynamic finder/persitence methods to manipulate your domain model from a Grails controller or service class!
Some examples of these in action are listed below, Grails uses the properties of the domain class itself (combined with the wonderful Criteria API) to implement the finders:
This is one of the awesome features of Groovy's Meta Object Protocol (MOP), it allows you to add new methods, properties,constructors etc. to any existing Java class, it doesn't have to extend GroovyObject or have any knowledge of the Groovy runtime environment. Think of it as AOP without the byte code manipulation.
Taking this approach is quite appealling at it allows the blended development I mentioned in the talk. Mixing dynamic and static typing is the way to go in my opinion. The debate between these two is a bit of a red herring. This way you have all the power of static typing with its refactoring capability in IDEs, plus the ability to use a dyanmic framework like Grails as the view/controller layer in your web application.
You can also then re-use your domain model across tiers or from regular servlets or via a Swing interface very simply because it is still in Java. The main target for Grails has always been to create a framework with the essence of Rails, but taking Java integration to a new level. Features like this are exactly what is helping us achieve this very goal.
One way to do this is to use the EJB3 annotation support in Hibernate which will of course allow you to use all the power the API offers in terms of mapping onto legacy systems. Clearly this is all not that exciting so far, what is really exciting is that even though the EJB3 entities you've created are written in Java and mapped using Java persistence annotations you can still use all those fantastic dynamic finder/persitence methods to manipulate your domain model from a Grails controller or service class!
Some examples of these in action are listed below, Grails uses the properties of the domain class itself (combined with the wonderful Criteria API) to implement the finders:
def a = new Author(name:'Stephen King').save()
def b = new Book(author:a, title:'The Stand').save()
def results = Book.findAllByTitle("The Stand")
results = Book.findAllByTitleLike("Harry Pot%")
results = Book.findAllByReleaseDateBetween( firstDate, secondDate )
results = Book.findAllByReleaseDateGreaterThan( someDate )
results = Book.findAllByTitleLikeOrReleaseDateLessThan( "%Something%", someDate )
// find by relationship
results = Book.findAllByAuthor( Author.findByName('Stephen King') )
This is one of the awesome features of Groovy's Meta Object Protocol (MOP), it allows you to add new methods, properties,constructors etc. to any existing Java class, it doesn't have to extend GroovyObject or have any knowledge of the Groovy runtime environment. Think of it as AOP without the byte code manipulation.
Taking this approach is quite appealling at it allows the blended development I mentioned in the talk. Mixing dynamic and static typing is the way to go in my opinion. The debate between these two is a bit of a red herring. This way you have all the power of static typing with its refactoring capability in IDEs, plus the ability to use a dyanmic framework like Grails as the view/controller layer in your web application.
You can also then re-use your domain model across tiers or from regular servlets or via a Swing interface very simply because it is still in Java. The main target for Grails has always been to create a framework with the essence of Rails, but taking Java integration to a new level. Features like this are exactly what is helping us achieve this very goal.
Wednesday, May 24, 2006
Grails: JavaOne 2006 Slides Available
The slides that I presented at the JavaOne 2006 conference are now available to download from the Grails site. Alternatively here's a direct link.
Thanks to all of those that attended, it was a blast :-)
Thanks to all of those that attended, it was a blast :-)
Grails & Oracle: First Grails tutorial on Oracle site
Nice to see Oracle re-affirming their committment to Grails by posting the excellent Grails on Oracle 10g tutorial written by Tug Grall onto the main Oracle developer website.
The tutorial walks you through how to setup Grails with the Oracle DB and Application Server including advanced configuration to use OracleAS shared libraries. Great stuff!
The tutorial walks you through how to setup Grails with the Oracle DB and Application Server including advanced configuration to use OracleAS shared libraries. Great stuff!
Tuesday, May 23, 2006
Grails: Using Acegi Security for authentication
The great thing about Grails is that although on the surface it is simple and easy to develop with, underneath there is all the power of Spring & Hibernate.
As an example to perform authentication with Grails you could use action interceptors as described in the controllers documentation or alternatively if you want the power of declaritive security that a framework like Acegi for Spring offers then the underlying Spring configuration is there. In fact somebody has already done it and written a neat little walk through on how to go about configuring Acegi to work with Grails.
Power and simplicity, the perfect combination :-)
Codehaus Update: The distributations are available to download again, the images on the site are still broken, but the mailing lists are up! CVS is still down at the moment, but I've received assurances that it will be operational again soon.
As an example to perform authentication with Grails you could use action interceptors as described in the controllers documentation or alternatively if you want the power of declaritive security that a framework like Acegi for Spring offers then the underlying Spring configuration is there. In fact somebody has already done it and written a neat little walk through on how to go about configuring Acegi to work with Grails.
Power and simplicity, the perfect combination :-)
Codehaus Update: The distributations are available to download again, the images on the site are still broken, but the mailing lists are up! CVS is still down at the moment, but I've received assurances that it will be operational again soon.
Saturday, May 20, 2006
Grails: Back from JavaOne / Codehaus Status
Well I'm back from JavaOne which went fantastically well (despite a minor hickup in the Eclipse demo!). Grails was well received and there seemed to be a lot of interest which is excellent. I met some interesting people, like members of the Hibernate and Spring teams and many of the IDE developers like those from JDeveloper, NetBeans etc. showed an interest in developing plug-ins for Grails which is excellent news.
I will be posting the slides I presented at JavaOne shortly, in the meantime though just a bit of a status update with regards to the Codehaus servers. It is damn annoying that the server went down over JavaOne and I don't want those who attended the session to lose interest.
Currently though the mailing lists, CVS, and the website are down. The Codehaus team are working as hard as they can to restore the site, I will post further updates when all services are working again, in the meantime if you want to get hold of Grails you can still download the snapshot builds from the Canoo build server and the Wiki is still available for the documentation.
I will be posting the slides I presented at JavaOne shortly, in the meantime though just a bit of a status update with regards to the Codehaus servers. It is damn annoying that the server went down over JavaOne and I don't want those who attended the session to lose interest.
Currently though the mailing lists, CVS, and the website are down. The Codehaus team are working as hard as they can to restore the site, I will post further updates when all services are working again, in the meantime if you want to get hold of Grails you can still download the snapshot builds from the Canoo build server and the Wiki is still available for the documentation.
Monday, May 15, 2006
Grails: Grails has Oracle's backing
Hello from the Wine Country! I'm currently in Sonoma north of San Francisco and will be heading to JavaOne in a couple of days! In the meantime the huge news is that we are getting more major players behind Grails. Every major open source project needs backing from the big players in the industry and Oracle have made a commitment (Thanks tug!) to get behind Grails which is fantastic news.
Its not quite clear at this point what that commitment will entail (I will be holding conversations at JavaOne), but the fact that such a huge organisation is backing Grails is a clear sign that Grails is making an impact and has the potential to succeed in the enterprise market.
In the meantime interest continues to gather pace with more committers and more interest so if you're coming to JavaOne remember to sign-up for the 2 sessions on Grails and see you there!
Its not quite clear at this point what that commitment will entail (I will be holding conversations at JavaOne), but the fact that such a huge organisation is backing Grails is a clear sign that Grails is making an impact and has the potential to succeed in the enterprise market.
In the meantime interest continues to gather pace with more committers and more interest so if you're coming to JavaOne remember to sign-up for the 2 sessions on Grails and see you there!
Thursday, May 11, 2006
Off to JavaOne 2006
Well I'm packing my bags and am off to do some site seeing before popping into the JavaOne 2006 conference. If you havn't signed up for the Grails session and are interested in attending get on over there and do so! :-)
We should have the 0.2 release of Grails out shortly after JavaOne with several improvements and new features, but if you can't wait for that checkout the 0.2 snapshots on the downloads page.
See you there!
We should have the 0.2 release of Grails out shortly after JavaOne with several improvements and new features, but if you can't wait for that checkout the 0.2 snapshots on the downloads page.
See you there!
Friday, April 28, 2006
Grails: Interview on JavaPosse
There is a podcast interview with yours truely up on JavaPosse discussing my experiences with Groovy, what makes it so powerful and how Grails fits into the bigger picture of J2EE development.
Thanks to Dick and all the JavaPosse guys for taking their time out to chat to me, it was a most enjoyable experience.
PS I was a bit nervous in the beginning and I think it shows!
Thanks to Dick and all the JavaPosse guys for taking their time out to chat to me, it was a most enjoyable experience.
PS I was a bit nervous in the beginning and I think it shows!
Monday, April 24, 2006
Grails: Ruby on Rails feeling the heat
Up until now I have not wanted to be drawn into a Grails vs Rails debate, clearly not wanting to start a flame war with the Ruby community, but it seems the Ruby/Rails people are doing that job perfectly well without my intervention and feel rather threatened by Grails as they keep bringing it up in interviews and comments on blogs.
In the latest podcast on the Ruby on Rails website they have an interview up with Tim Bray. They talk about Rails and the future of dynamic languages, and they brought up the topic of Grails in which the interviewer said and I quote:
"I heard that some guys had done a Groovy on Rails or Grails framework and didn't quite get it right."
Now, I encourage said interviewer to qualify his statement and point me to a reference where it says we havn't got it quite right. Clearly, you havn't tried Grails my dear boy and making such statements without the facts to back you up is really rather silly, and typical of the response from the Ruby community.
I follow all Grails news quite closely and not one user has said we havn't got it right in fact all the users on our mailing list that have taken up Grails feel we have got it very right with comments like Grails is "The Holy Grail" of Java web development and that its productivity is on par with Rails and for Java developers even more so because they can fully utilise their existing API knowledge.
So far there has yet to be a negative post about Grails from a Java developer, I'm sure there will be one, but I'm still waiting.. so the question is: are the Rails people feeling the heat?
The fact that they even mentioned Grails in this interview and have not mentioned any other Rails-like frameworks is a sign that they are worried and they should be. Grails takes Java integration to a new level. A level that will never be reached by the likes on JRuby on Rails, which really only serves as a useful proof-of-concept.
Good luck guys, Grails may have only just had a 0.1 release, but it has a growing following, greater integration with Java and an aggresive project plan and for the first time you have real competition.
In the latest podcast on the Ruby on Rails website they have an interview up with Tim Bray. They talk about Rails and the future of dynamic languages, and they brought up the topic of Grails in which the interviewer said and I quote:
"I heard that some guys had done a Groovy on Rails or Grails framework and didn't quite get it right."
Now, I encourage said interviewer to qualify his statement and point me to a reference where it says we havn't got it quite right. Clearly, you havn't tried Grails my dear boy and making such statements without the facts to back you up is really rather silly, and typical of the response from the Ruby community.
I follow all Grails news quite closely and not one user has said we havn't got it right in fact all the users on our mailing list that have taken up Grails feel we have got it very right with comments like Grails is "The Holy Grail" of Java web development and that its productivity is on par with Rails and for Java developers even more so because they can fully utilise their existing API knowledge.
So far there has yet to be a negative post about Grails from a Java developer, I'm sure there will be one, but I'm still waiting.. so the question is: are the Rails people feeling the heat?
The fact that they even mentioned Grails in this interview and have not mentioned any other Rails-like frameworks is a sign that they are worried and they should be. Grails takes Java integration to a new level. A level that will never be reached by the likes on JRuby on Rails, which really only serves as a useful proof-of-concept.
Good luck guys, Grails may have only just had a 0.1 release, but it has a growing following, greater integration with Java and an aggresive project plan and for the first time you have real competition.
Tuesday, April 18, 2006
Grails: The Render method and Ajax
Users of Ruby on Rails will be familiar with the 'render' method which allows rendering of responses from a controller. Grails has a similar mechanism, for example rendering text is as simple as:
You can of course also render templates and views via the method (for more complete documentation see here), but what makes Grails' render method that little bit different is its support for markup building.
With other Java frameworks I've used I ended up with loads of partial views implemented as JSP or velocity views. Each with the sole responsibility of rendering some XML or JSON. With Grails this is rarely needed for pure XML responses (note, I would never condone defining layout in this way this is purely for data oriented XML rendering). Rendering XML is made infinitely more simple:
The above results in the following XML snippet being rendered to the response:
When you combine this with how Grails controllers reload automatically on changing it makes writing ajax responses a breeze. But, there is more! Grails has inbuilt support for OpenRico so if you want to write Ajax responses in Ricos required format this can be done as follows:
Rico will then automatically look-up your 'bookUpdater' instance and delegate the response to it passing the contained XML to the updater for handling.
I don't normally like talking about unimplemented features, but thought it might be worthwhile just to highlight the power of the builder concept in Groovy as I don't believe that many grasp the potential of builders and their usages. One of the upcoming features in Grails is a JSON builder which will be available via the render method so say I wanted to render JSON instead of XML? We just change the content type defined in the render method:
And the resulting output would be JSON instead of the XML without any change to the structure of the builder code itself:
render 'hello world!'
or
render(text:'world ',contentType:'text/xml')
You can of course also render templates and views via the method (for more complete documentation see here), but what makes Grails' render method that little bit different is its support for markup building.
With other Java frameworks I've used I ended up with loads of partial views implemented as JSP or velocity views. Each with the sole responsibility of rendering some XML or JSON. With Grails this is rarely needed for pure XML responses (note, I would never condone defining layout in this way this is purely for data oriented XML rendering). Rendering XML is made infinitely more simple:
def results = Book.list()
render(contentType:'text/xml') {
books {
for(b in results) {
book(title:b.title)
}
}
}
The above results in the following XML snippet being rendered to the response:
<books>
<book title="The Shining" />
<book title="Along came a Spider" />
</books>
When you combine this with how Grails controllers reload automatically on changing it makes writing ajax responses a breeze. But, there is more! Grails has inbuilt support for OpenRico so if you want to write Ajax responses in Ricos required format this can be done as follows:
render(builder:'rico') {
object(id:'bookUpdater') {
books {
for(b in results) {
book(title:b.title)
}
}
}
}
Rico will then automatically look-up your 'bookUpdater' instance and delegate the response to it passing the contained XML to the updater for handling.
I don't normally like talking about unimplemented features, but thought it might be worthwhile just to highlight the power of the builder concept in Groovy as I don't believe that many grasp the potential of builders and their usages. One of the upcoming features in Grails is a JSON builder which will be available via the render method so say I wanted to render JSON instead of XML? We just change the content type defined in the render method:
render(contentType:'text/json') {
books {
for(b in results) {
book(title:b.title)
}
}
}
And the resulting output would be JSON instead of the XML without any change to the structure of the builder code itself:
{
books : [
{ title: 'The Shining' },
{ title: 'Along came a spider' }
]
}
Monday, April 17, 2006
Grails.org Live
Thanks to John Wilson of the Groovy development team who was on the ball enough to snap up the domain when it became available Grails has a new web home at www.grails.org!
Grails: Getting Started on Oracle 10g
Just got back from my easter break with the family and its great to see such fantastic tutorials being posted about Grails already including this one on how to get Grails up and running with Oracle 10g Express Edition.
Not only does it go through how to setup the database side of things, but it also talks you through deployment on OracleAS via a Grails WAR and improved deployment options. Great stuff.
Not only does it go through how to setup the database side of things, but it also talks you through deployment on OracleAS via a Grails WAR and improved deployment options. Great stuff.
Monday, April 03, 2006
Grails: Tag Libraries & The Power of Closures
When we started developing Grails we wanted to support a dynamic view technology that allowed scriptlets in Groovy instead of Java, but without falling into the trap of having scriptlets intermingled with HTML code a trap that many Java developers have spent years trying to avoid.
Historically though JSP custom tags have always been a bit of a pain to write, they're designed to cover every variation of tag under the sun, hence the API is complicated and the tag lib descriptors verbose. Grails is all about simplicity, so how do we avoid introducing this level of complexity into our Grails applications. The answer came in the form of anonymous code blocks or closures.
I would say 90% of the tags that are written for JSP out there fall into one of three categories: simple, logical or iterative. There are those more complex tags that have relationships to each other via nesting, but the vast majority are of the aforementioned type and Grails is about making the most common cases easy, but still allowing the flexibility to scale to the more complex (thats why we still support JSP).
So what have closures done to make custom tags easier? Well Grails allows you to define a custom tag as a JavaBean property. No descriptors, no configuration, and everything is reloaded at runtime so no need to restart that application server. So lets look at an example from the tag library that ships with Grails (simplified for clarity):
Each tag library is simply a class that ends with the convention "TagLib". The above example contains an "eachError" tag that loops through each error contained within the "bean" attribute and invokes the "body" of the tag. Note how the body of the tag itself is a closure and hence callable, the attributes are a map. To use this tag we simple call it from our GSP no need to import the tag library or anything, the error itself is available using Groovy's implicit 'it' variable which was passed to the body closure:
Now thats pretty neat and simplistic, but this is where using closures for defining tags becomes really powerful. How about we want to re-use our "eachError" tag else where? Say we want to implement a default rendering tag called "renderErrors" that renders our errors as an HTML list. Well we can re-use the "eachErrors" tag to accomplish this:
The above code creates a new MarkupBuilder instance which is used to generate an HTML list re-using the eachError tag defined previously, it actually uses a third Grails tag called "message" to retrieve the message for the error code. To call the "renderErrors" tag we simply do:
Grails users can of course customise the inbuilt tags and add brand new ones simply by adding new tag library classes in the "grails-app/taglib" directory. So there you have it, custom tags have never been easier, and your markup can remain scriptlet free without the need to invest huge amounts of time creating a custom JSP tag library.
Historically though JSP custom tags have always been a bit of a pain to write, they're designed to cover every variation of tag under the sun, hence the API is complicated and the tag lib descriptors verbose. Grails is all about simplicity, so how do we avoid introducing this level of complexity into our Grails applications. The answer came in the form of anonymous code blocks or closures.
I would say 90% of the tags that are written for JSP out there fall into one of three categories: simple, logical or iterative. There are those more complex tags that have relationships to each other via nesting, but the vast majority are of the aforementioned type and Grails is about making the most common cases easy, but still allowing the flexibility to scale to the more complex (thats why we still support JSP).
So what have closures done to make custom tags easier? Well Grails allows you to define a custom tag as a JavaBean property. No descriptors, no configuration, and everything is reloaded at runtime so no need to restart that application server. So lets look at an example from the tag library that ships with Grails (simplified for clarity):
class ValidationTagLib {
@Property eachError = { attrs, body ->
def errors = attrs.bean.errors
if(errors) {
errors.each { body(it) }
}
}
}
Each tag library is simply a class that ends with the convention "TagLib". The above example contains an "eachError" tag that loops through each error contained within the "bean" attribute and invokes the "body" of the tag. Note how the body of the tag itself is a closure and hence callable, the attributes are a map. To use this tag we simple call it from our GSP no need to import the tag library or anything, the error itself is available using Groovy's implicit 'it' variable which was passed to the body closure:
<g:eachError bean="${myBean}">
<p style="color:red;">${it.defaultMessage}</p>
</g:eachError >
Now thats pretty neat and simplistic, but this is where using closures for defining tags becomes really powerful. How about we want to re-use our "eachError" tag else where? Say we want to implement a default rendering tag called "renderErrors" that renders our errors as an HTML list. Well we can re-use the "eachErrors" tag to accomplish this:
@Property renderErrors = { attrs, body ->
def markup = new groovy.xml.MarkupBuilder(out)
markup.ul() {
eachError(attrs) { err ->
li( message(code:err.code) )
}
}
}
The above code creates a new MarkupBuilder instance which is used to generate an HTML list re-using the eachError tag defined previously, it actually uses a third Grails tag called "message" to retrieve the message for the error code. To call the "renderErrors" tag we simply do:
<g:renderErrors bean="${myBean}"/>
Grails users can of course customise the inbuilt tags and add brand new ones simply by adding new tag library classes in the "grails-app/taglib" directory. So there you have it, custom tags have never been easier, and your markup can remain scriptlet free without the need to invest huge amounts of time creating a custom JSP tag library.
Wednesday, March 29, 2006
Grails 0.1 Released
Yes, that time has come, the first 0.1 release of Grails is out and I'm really pleased all or our hard toil has resulted in such a quality release. Grails has come a long way, I'm currently developing my first live project with it and it is a joy to use. There is still much to do though and we have some exciting features planned.
Over the coming weeks I will be posting on this blog about some of the features of Grails that I believe make it unique and not just another Rails clone. So stay tuned, the Grails journey has only just begun. :-)
Over the coming weeks I will be posting on this blog about some of the features of Grails that I believe make it unique and not just another Rails clone. So stay tuned, the Grails journey has only just begun. :-)
Subscribe to:
Posts (Atom)