log4p

Peter Maas’s Weblog

Archive for August, 2007

Grails 0.6 Released

Today Graeme and the Grails team have released a significant new version of Grails: 0.6.

One of the more interesting bits added in this release is the addition rich conversation support (Spring Web Flow under the hood) called Grails Flow. Apart from Grails flow the release notes contain the following updates:

  • Joint Groovy/Java Compilation
  • Support for Spring scopes to allow scoped services
  • Improved support for REST with automatic XML/JSON marshalling and RESTful URL mappings
  • New Config DSL for configuration not possible by convention
  • Refreshed scaffolding interface and branding
  • Support for Sitemesh inline decorators
  • Controllers can now call tag libraries as methods
  • New GSP tags
  • Massive improvements to speed of start-up time, unit tests and generation tools

Congratulations to the Grails team! I’ll be giving 0.6 a go in a short while!

No comments

Unittesting e-mail sending using Spring

In previous projects I mostly skipped writing tests for sending mail. Mostly due to the fact that there is a dependency on a working SMTP server. This time I decided to invest some time in finding a solution for this problem.

It didn't have to look very far to find Wiser. Wiser is a very simple fake SMTP server designed for unit and system testing applications. You basically start it up, send mail to it and read the queue of messages it received.

Using it in unit test is indeed simple. First setup the server, and reconfigure mail senders in the Spring context:

  1. @SuppressWarnings("unchecked")
  2. @Override
  3. protected void onSetUp() throws Exception {
  4.   super.onSetUp();
  5.   wiser = new Wiser()
  6.   wiser.setPort(2525);
  7.   wiser.start();
  8.          
  9.   Map<String, JavaMailSenderImpl> ofType =   
  10.     getApplicationContext().getBeansOfType(org.springframework.mail.javamail.JavaMailSenderImpl.class);
  11.  
  12.   // reconfigure mailsenders in the spring context
  13.   for (Entry<String, JavaMailSenderImpl> bean : ofType.entrySet()) {
  14.     log.info(String.format("configuring mailsender %s to use local Wiser SMTP", bean.getKey()));
  15.     JavaMailSenderImpl mailSender = bean.getValue();
  16.     mailSender.setPort(2525);
  17.     mailSender.setHost("localhost");
  18.   }
  19. }

Now you are ready to run a test:

  1. public void testSendMailStrings() {
  2.   mailService.sendMail("test-sender@test.nl", "test-reciever@test.nl", "testing the mailservice", "testing the mail service, body");
  3.  
  4.   assertEquals(1, wiser.getMessages().size());
  5.   WiserMessage m = wiser.getMessages().get(0);
  6.   assertEquals("test-sender@test.nl", m.getEnvelopeSender());
  7.   assertEquals("test-reciever@test.nl", m.getEnvelopeReceiver());
  8.   try {
  9.     MimeMessage message = m.getMimeMessage();
  10.     assertEquals("testing the mailservice", message.getSubject());   
  11.     assertEquals("testing the mail service, body", (String)message.getContent());
  12.   } catch (MessagingException me) {
  13.     fail(String.format("MessagingException [%s] should not occur", me.getMessage()));
  14.   } catch (IOException ioe) {
  15.     fail(String.format("IOException [%s] should not occur", ioe.getMessage()));
  16.   }
  17. }

And after this, make sure to stop the server so it can be started again for consequent tests:

  1. @Override
  2. protected void onTearDown() throws Exception {
  3.   wiser.stop();
  4. }

Works like a dream!

6 comments

Grails – Soap

Since working with, or creating WebServices is something webdevelopers will probably do regularly (or stumble upon in the very near future) I decided to have a look at Grails' support for SOAP.

First thing I wanted to see was how to expose a Grails service via Soap. Due to the excellent documentation at the Grails website this proved to be really simple:

Setup
  1. download the XFire plugin here
  2. install the plugin by running "grails install-plugin /path/to/grails-XFire-x.x.x.zip" from the root of your project
Create a service
  1. run "grails create-service Task" from the root of your project
  2. Implement it and configure it for XFire remoting:

    1. class TaskService {
    2.     static expose=['xfire'] // expose remotely using xfire
    3.    
    4.     boolean transactional = true
    5.    
    6.     def String[] findTasksBySubject(String s) {
    7.         def c = Task.createCriteria()
    8.         def results = c{
    9.             like("subject", "%${s}%")
    10.         }
    11.  
    12.         return results*.subject
    13.     }
    14. }

    • Notice the *. (spread-dot) operator? It collects results from call the consequent method on each item in the list, cool!
    • Notice the Hibernate Criteria Builder, more info here
    • Notice the 'transactional' propery, setting it to true results in all methods of a service are wrapped in a transaction.
  3. Start your application, and point your browser to: http://localhost:8080/ptodo/services/task?wsdl
    which gives you the WSDL describing your service!
  4. done!

Of course there is no point in having a WebService without a client... which is only 3 lines of Groovy away. From your favorite Groovy shell, run (after installing the SOAP libs):

  1. groovy> import groovy.net.soap.SoapClient
  2. groovy> def proxy = new SoapClient("http://localhost:8080/ptodo/services/task?wsdl")
  3. groovy> proxy.findTasksBySubject("XFire")
  4. groovy> go
  5.  
  6. ===> [Check the XFire plugin]

Almost instant gratification!

2 comments

Grails – Render method & Markup builder

During Graemes' demo of Grails at javasummercamp he briefly pointed out the fact that one can implicitly use the Groovy MarkupBuilder (Similar to the Markaby DSL for Ruby) within the render method of an action for generating markup.

Which makes writing an RSS feed for you application really easy:

  1. def feed = {
  2.   def results = Task.list(max: 10, sort: 'id', order: 'desc')
  3.   render(contentType: 'application/rss+xml') {
  4.       rss(version: '2.0') {
  5.           channel{
  6.               title('recent tasks')
  7.               description('A feed of the 10 most recent tasks')
  8.               link('/task/list')
  9.               results.each { task ->
  10.                   item{
  11.                       title(task.subject)
  12.                       description(task.description)
  13.                       link("/task/view/${task.id}")
  14.                       pubDate(new Date()) // might want to put something useful in here
  15.                   }
  16.               }
  17.           }
  18.       }
  19.   }
  20. }

Which will result in something like this:

  1. <rss version='2.0'>
  2.   <channel>
  3.     <title>recent tasks</title>
  4.     <description>A feed of the 10 most recent tasks</description>
  5.     <link>/task/list</link>
  6.     <item>
  7.       <title>Create RSS feed with the markup builder</title>
  8.       <description>After investigating the markupbuilder, use it to
  9.       create a simple RSS feed</description>
  10.       <link>/task/view/2</link>
  11.       <pubDate>Sun Aug 26 15:06:43 CEST 2007</pubDate>
  12.     </item>
  13.     <item>
  14.       <title>Investigate MarkupBuilder</title>
  15.       <description>Investigate the MarkupBuilder</description>
  16.       <link>/task/view/1</link>
  17.       <pubDate>Sun Aug 26 15:06:43 CEST 2007</pubDate>
  18.     </item>
  19.   </channel>
  20. </rss>

Wonderful isn't it?

Apart from this, it might be useful to know that Grails has build-in builders for JSon as well!

2 comments

Proficts’ Javasummercamp on Rails/Grails/Java

Graeme presenting, Charles setting on the front rowYesterday I visited Proficts' Java Summercamp called "Rails en Grails en Java: Nieuwe talen op de JVM". Which in essence should have been a small seminar
on the topic of new languages on the JVM. In reality Charles Nutter presented JRuby, and its' current state and Graeme Rocher did a presentation on Groovy and Grails.

Both presentations resembled previous presentations (Finalist JRuby evening, Javapolis) I visited closely. Difference being that there was a bit more time to get into a tiny bit of detail.

First, let me walk you through the program:

13:00 Walter van Berkel (introduction)
Introduction of the organizing company. A "please come and work for us" presentation
13:30 Charles Nutter (JRuby)
Charles starts of the with the obligatory "who's got any experience with Ruby?".
Most people in the audience have nog hands-on experience with Ruby.

So, Charles starts of with explaining the basics of Ruby. Types, inheritance, closures, modules... a bit
dull if you do know a bit about Ruby.

On to the demo's

Demo: JFrame from JRuby using Netbeans 6
If you've seen Ruby calling into Swing before it's getting less impressive, people in the audience where getting interested
Demo: Interactive Java from jIrb
Reminded me of the fact that it is cool that JRuby can use JVM thread (Thread.new), which is actually quite nice.
Demo: 'Profligacy'
Another Swing demo, the LEL expressions used to define the interface where quite nice
Demo: Cheri builder framework
Another Swing demo; yes it can be done...
Demo: Rails on JRuby
90% of the audience was supposedly involved in webdevelopement. A Rails demo should have won them over. Charles didn't really manage to do this; he only did a really basic 2005 style scaffolding demo... bummer; but then again he really isn't a Rails guy... he's a JRuby guy.

Het demoed the use of the Rome RSS liberary to create an RSS feed using JRuby.
The deployement related part of the presentation managed to grab my attention though.
I knew of GoldSpike and that it is possible to create WAR files from Rails applications, but still cool.
I hadn't seen the GlassFish V3 preview Gem, which instantly runs your rails app on GlashFish. Really cool!

Demo: ActiveHibernate
I browsed through the ActiveHibernate examples just last week and decided that it is far to immature to call it a framework yet.
It managed to crash-and-burn horrible during the presentation; proving my point. Might be something some day... but not just yet.
16:00 Graeme Rocher (Grails - Next generation apps. Done quick.)
Graemes' presentation was structured quite similar to the presentation Charles gave. An introduction to the Groovy programming language, and on to the demos!

Demo: Scaffolding
Due to the pleasant look of models in GORM, and the fact that Grails' scaffolding automatically generated widgets for associations this demo was a bit
more up to date. Also the tag part, which triggered my interest in Grails at Javapolis managed to rouse people a bit.
Demo: Rendering / Builders
Graeme started of with using the XML builder for converting the object graph to XML, nice! Af this he demoed the 'render as' methods of Grails for rendering object graphs as XML and JSON. Cool! I'll write a post on this in the near future.
Back to GORM: the criteria builder:

  1. Book.withCriteria{
  2.   like(title, "bla")
  3. }

Cool as well!

Demo: Grails and WebFlow
Since Grails is based on Spring MVC the embracing of WebFlow in the new 0.6 release was to be expected. WebFlow is a conversational state engine.
The code looked, eh.. groovy... to bad the demo didn't run.

Conclusion
After the presentations I (and, as I understood from organizer Danny) hoped to get into a little debate on the use of scripting languages on top of the JVM. Not all Java developers came to the point where they bother about scripting languages just yet; the audience was actually more interested in asking detail questions about Rails and Grails. "Yes, Grails might have support for migrations after 1.0 has been released", "Rails can be as secure as you make it". This really made Grails stand out much better then the conventional Rails, but mostly due to the fact the Charles came in to talk about JRuby and Rails was just one of the demo's.

All in all, I had a splendid afternoon... but many Java developers still have a long, long way to go when talking about scripting languages!

1 comment

Grails templating & Ajax

Grails' templating system is cool. There is no doubt about it. It's what I wanted JSP2.0 tagfiles to be. In essence they're not so different from tagfiles in practice their versatility is a fair bit higher.

Templates in Grails reside in the views folder of your project, and are plain gsp files prefixed with an underscore (i.e. /views/task/_task.gsp). The can contain anything a gsp template can.

So, say we have a simple template called _textile.gsp:

  1. <div class="textileText">
  2.     <g:textile text="${text}"/>
  3. </div>

It can be rendered in a view using the render tag like this:

  1. <g:render template="textile" var="text" bean="${task.description}"/>

Or, using an iterator:

  1. <g:render template="textile" var="text" collection="${task?.comments}" />

Verry nice, you'll probably say... but I can easily do that using a JSP tag as well. True. Enter the fact that you can call a template from your controller as well:

  1. def textilePreview = {
  2.     render(template: "textile", var: "text", bean: params.text)
  3. }

This is specifically useful when Ajax is put into the equation, since it creates a simple framework to create templates to be used for re-rendering parts of the page after the page has loaded:

  1. <!-- snip -->
  2. <g:remoteTextArea id="description" action="textilePreview" update="descPreview" paramName="text" name='description' cols="240" value="${task?.description}"/>
  3.  
  4. <div id="descPreview">
  5.     <g:render template="textile" var="text" bean="${task.description}"/>
  6. </div>

The remoteTextara (an adapted version of the standard remoteField tag) fires Ajax calls to the textilePreview action, and the response is writen in de 'descPreview' div (specified by the 'update' attribute). Nice!

When I find some time I'll try and put a short video in, screenshots of dynamic updates are just a bit sad ;)

No comments

Groovy and the safe dereference operator

When going through view code generated by Grails I noticed heavy use of the question mark operator when referencing properties. After browsing around I discovered that it is called the 'safe dereference operator'

Sounds more complex then it is, it just makes sure that consequent methodcalls are only executed when the object on which it is called actually exists:

  1. user?.email?.encodeAsHTML()

In the case above the 'email' property will only get read when the 'user' object actually exists and the 'encodeAsHTML()' will only get called when the 'email' property actually has a value. Cool!

No comments

Referencing spring beans from a Grails tag

Today I had a short look at referencing Spring beans from Grails. Since Grails is build on top of Spring this was actually 100% simpler then expected. Grails controllers and taglibs are autowired by name on startup.

Just for the fun I create a simple tag which depends on a Spring bean for converting textile markup into HTML:

The tagfile looks like this:

  1. import com.plink.plextile.*;
  2.  
  3. class TextileTagLib {
  4.     TextParser textileParser
  5.  
  6.     def textile = { attrs ->
  7.         out << textileParser.parseTextile(attrs.text, true)
  8.     }
  9. }

The file (TexttileTagLig.groovy in my case) is placed in the taglib subfolder. Closures in classes placed here will be available as tags in the g namespace your gsp pages.

In the code above you can clearly see the power of grails, writing tags in this way is really easy and nice. The attrs attribute of the 'textile' closure contains all attributes passed to the tag, we will use the text attribute.

The interesting part is the 'textileParser' attribute. This will be automatically injected by Spring, so all we have to do is define it in the resources.xml file in the spring directory:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.        xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  6.    
  7.     <bean id="textileParser" class="com.plink.plextile.TextParser"/>
  8. </beans>

And modify the 'show.gsp' template in the view directory to use the tag:

  1. <g:textile text="${task.description}"/>

And this is the result:

Textile inputted in the textarea of the formRendered as HTML (notice the ordered list)

No comments

IntelliJ IDEA 7m2: Groovy/Grails support

IntelliJ IDEA 7m2
From the corner of my eyes I noticed something in the latest IntelliJ release: a Groovy and Grails plug-in.

The screenshots on the Jetbrains website showing of Smart type inference, Cross-resolution between Groovy and Java classes and Smart code navigation assistance with structure view, class and usage make me want do download and use IntelliJ right away.

Now... during the past year I have tried to use IntelliJ a couple of time but never really deemed IntelliJ worth the investment. Responses on the related thread on theserverside do however trigger some curiosity:

Eclipse is a tool that is FREE and Great.
Intellij is a tool that is a Great Value and Awesome.
---
IntelliJ IDEA is the best IDE for developers.
I think Eclipse is more suite for the IDE provider.
---
Why use IntelliJ when there are awesome products like eclipse?

Easy: iPod vs other mp3 players. They both do the same thing, just one is a pleasure to use :)

I really might need to give IntelliJ another try....

No comments

Book: The definitive guide to Grails


Today I received some formal backing for my investigations into the Grails framework. The mailman delivered 'The Definitive Guide to Grails' by Graeme Keith Rocher which I asked Finalist to order for me (hey, can't win battles without books).

I've read the first couple of paragraphs, and flipped through the book... looks really useful on first sight. Let's hope it will live up to its' expectations!

No comments

Next Page »