<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gridshore &#187; grails</title>
	<atom:link href="http://www.gridshore.nl/tag/grails/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Use Grails and Axon to create a CQRS application (part I)</title>
		<link>http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/</link>
		<comments>http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 22:02:49 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[axon]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1025</guid>
		<description><![CDATA[<p>Allard has been working on a new framework to make it easier to create a CQRS application. CQRS is short for Command Query Responsibility Segregation. An architecture that separates data sources for storing state and querying data. The query datasource should be easy to use when creating screens. The framework Allard created is the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/axon_logo.png" alt="axon_logo.png" border="0" width="55" height="55" align="left" />Allard has been working on a new framework to make it easier to create a CQRS application. CQRS is short for Command Query Responsibility Segregation. An architecture that separates data sources for storing state and querying data. The query datasource should be easy to use when creating screens. The framework Allard created is the <a href="http://www.axonframework.org/">Axon Framework</a>. This framework makes it a lot easier to use commands, events, event sourcing. If these terms are not known to you, I suggest you start reading the reference manual that comes with axon.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/grailslogo.png" alt="grailslogo.png" border="0" width="163" height="43" align="right" />What does <a href="http://www.grails.org/">grails</a> do in this picture. Isn&#8217;t grails about rapid application creation? Well, yes. It is a good platform to rapidly create web applications using the groovy language and still be able to use existing libraries. Personally I really like the Gorm library of grails. I think that gorm would be an excellent choice to wrap the query datasource. Of course the gsp technology and the groovy language are nice to have when working with the web applications as well.</p>
<p>In this blog post I&#8217;ll discuss the integration between grails and axon. How can we create an application with grails that makes use of Axon to implement CQRS. I&#8217;ll discuss the way to create commands and send these to axon. I&#8217;ll also discuss responding to events coming from axon. First I have to show some aspects of a grails project that you need to know before you can use Axon. I&#8217;ll try to take you with me when I take the steps to create a good integration between Axon and Grails.</p>
<p><span id="more-1025"></span><br />
<h2>Sources</h2>
<p>The sample I am using is the same sample that is provided by axon with a flex client. The AddressBook is used to show the different possibilities of axon and a client. You can create contacts, and register addresses of a certain type for contacts. You can register home, work and holiday addresses.</p>
<p>You can find the sources of the sample at github:</p>
<pre>
<a href="http://github.com/jettro/axon-addressbook-grails">http://github.com/jettro/axon-addressbook-grails</a>
</pre>
<h2>Configure grails to use Axon</h2>
<p>Grails has a pretty elegant way to configure libraries to be used by the project. You can make grails look for libraries in remote maven repositories as well as your local repository. I need to enable the local repository since I am working with a SNAPSHOT version of axon at the moment of writing.</p>
<p>Each normal grails project contains a folder grails-app/conf. In this folder is a file called BuildConfig.groovy. This file contains the build configuration, you did not see that one coming did you? In this file there is a closure called <em>grails.project.dependency.resolution</em>. Within this closure you can configure the repositories and the dependencies. As I said before you need to uncomment the mavenLocal() and add the following two lines to the dependencies.</p>
<pre class="brush: groovy; title: ; notranslate">
compile 'org.axonframework:axon-core:0.5-SNAPSHOT'
runtime 'com.thoughtworks.xstream:xstream:1.3.1'
</pre>
<p>I did not get the grails project to work in a way that SNAPSHOT dependencies are updated. So if I compile a new version of axon, I manually delete the library in the grails cache. The libraries are stored in the ivy cache on your computer. In my case the jars are in the folder:</p>
<pre>
&lt;user_home>/.ivy2/cache/org.axonframework/axon-core/jars/axon-core-0.5-SNAPSHOT.jar
</pre>
<h2>Structure of the project</h2>
<p>If you create a normal grails application you usually stick to the conventional project setup. Within the grails-app folder you have folders for domain classes, controllers, services, and others. </p>
<h3>The domain model</h3>
<p>When creating a CQRS application the domain becomes a different beast. It is the domain that commands act upon and the events are generated by the domain. For now let us call the domain from CQRS perspective the core-domain and the grails domain classes the query domain. The query domain resides in the normal grails location. Each grails project also contains a src folder with the groovy and java classes. This is where we will store the core domain.</p>
<p>A very important thing to stick in your brain is that the controllers must not use the standard way of grails to save domain objects. If you would do that, you only update the query database and no commands are created and send to the Axon backend.</p>
<h3>Grails services and axon commands</h3>
<p>We interact with axon by making use of command objects. To make this easy from the grails perspective we create a service class around the command creation. This makes it easier to create a transactional scope and to have just one location where we actually send data to axon. This service is more like a proxy to the Axon command bus.</p>
<h3>Grails controllers</h3>
<p>The controllers are normal grails controllers, they make use of services to send data to the backend and they use gorm to query the data.</p>
<h3>Axon event listeners</h3>
<p>The event listeners are used to receive updates about the core domain and reflect this in the query domain. The listeners make extensive use of gorm to update data in the query domain.</p>
<p>The following image gives you an idea about the directory layout of the project.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-04-06-at-18.48.39.png" alt="Screen shot 2010-04-06 at 18.48.39.png" border="0" width="331" height="554" /></div>
<h2>Scaffolding</h2>
<p>One of the nice options of grails to create applications very fast is to use scaffolding. When using axon this is still possible, but only to do the first steps very fast. I recommend creating your own views and controllers when you know what you want and you need to create better useable screens. You cannot use the scaffolding controllers. They would only use the query domain. We need to call the services from the controllers. I do generate the controllers and then adjust them to my needs.</p>
<p>To get an idea what I reused from the generated controllers, let us have a look at the changes I made to the generated controller methods. For now I did not change views, so they are still using the scaffolding versions. Beware that this is not a final solution. To give you an idea, registering an address for a contact means that you have to manually copy the uuid of the contact to the create new address screen. Of course I will change this as well, but that will be the topic of a next blog post.</p>
<p>As a rule of thumb, all methods that actually change data need to be altered.</p>
<pre class="brush: groovy; title: ; notranslate">
def save = {
    def contactEntryInstance = new ContactEntry(params)
    if (contactEntryInstance.validate()) {
        def uuid = contactCommandHandlerService.createContact(contactEntryInstance.name)
        def foundContact = ContactEntry.findByIdentifier(uuid)

        flash.message = &quot;${message(code: 'default.created.message', args: [message(code: 'contactEntry.label', default: 'ContactEntry'), foundContact.name])}&quot;
        redirect(action: &quot;show&quot;, id: foundContact.id)
    }
    else {
        render(view: &quot;create&quot;, model: [contactEntryInstance: contactEntryInstance])
    }
}
</pre>
<p>Line 4 show that we use the service instead of the query domain object. In line 5 we do use the query domain object to find the created contact.</p>
<h2>Configuring the event and command bus using grails and spring</h2>
<p>Grails uses a lot of spring udner the hood. But they also give you a very easy way to use spring yourself as well. Grails comes with a special domain specific language for configuring spring. You can find the file <em>resources.groovy</em> in the grails-app/conf/spring folder. In this file we configure the event bus, the command bus, the event listener and the command handlers. The following code block shows the beans, it should be straightforward and not to hard to understand.</p>
<pre class="brush: groovy; title: ; notranslate">
beans = {
    contactRepository(ContactRepository) {
        eventBus = ref(&quot;eventBus&quot;)
        eventStore = ref(&quot;eventStore&quot;)
    }

    contactEventListener(ContactEventListener, ref(&quot;eventBus&quot;))

    createContactCommandHandler(CreateContactCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))
    updateContactCommandHandler(UpdateContactCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))
    removeContactCommandHandler(RemoveContactCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))
    registerAddressCommandHandler(RegisterAddressCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))

    // axon beans
    commandBus(SimpleCommandBus)

    eventBus(SimpleEventBus)

    eventStore(FileSystemEventStore, ref(&quot;xstreamSerializer&quot;)) {
        baseDir = &quot;file:/Users/jcoenradie/temp/axonrepo&quot;
    }

    xstreamSerializer(XStreamEventSerializer)
}
</pre>
<p>Creating a bean is easy, some of the beans are direct axon classes. The contactRepository, contactEventListener and all the command handlers are not. These are groovy classes that reside in the src directory.</p>
<h2>Axon components in groovy</h2>
<p>I am not going to write extensively about Axon. The website from Axon does a much better job. I do want to mention the most important components and show some of the groovy code to make it work.</p>
<h3>Sending data using commands</h3>
<p>The data send is in the command objects. The commandBus is used to dispatch the commands. Each command must have a registered command handler. Axon provided a special mechanism to use annotations to register handlers. For now I register the handlers manually. Let us have a look at the handler for contact creation. The spring configuration already shows that the handlers use the contactRepository as well as the commandBus.</p>
<pre class="brush: groovy; title: ; notranslate">
class CreateContactCommandHandler implements CommandHandler&lt;CreateContactCommand&gt; {
    ContactRepository contactRepository

    def CreateContactCommandHandler(contactRepository, commandBus) {
        this.contactRepository = contactRepository;
        commandBus.subscribe(CreateContactCommand.class, this)
    }

    Object handle(CreateContactCommand command) {
        ContactAggregate contact = new ContactAggregate(command.newContactName)
        contactRepository.save contact
        return contact.identifier.toString()
    }
}
</pre>
<p>As you can see we need to implement the interface <em>CommandHandler</em>. In the constructor we subscribe the handler with the command bus. Now focus on the handle method. We create the contact aggregate and store it in the repository by calling the save method.</p>
<h3>Core domain</h3>
<p>Now the contact is created, but we also must update our query database. To understand what happens there, we must have a look at the core domain class. The following code block shows the constructor and that it applies an event for a contact being created.</p>
<pre class="brush: groovy; title: ; notranslate">
    ContactAggregate(String name) {
        apply(new ContactCreatedEvent(name))
    }
</pre>
<h3>Event listener</h3>
<p>Now that we have the events, we want to listen for them and update our query database. When creating the event listener, we need to provide the eventBus. In the constructor of the listener we register the listener with the eventBus. The handle method receives the events. In this method we check if we support the provided event. If we support it, we call one of the available doHandle methods that make use of overloading to determine the right method. The following code block shows the handle method and two of the doHandle methods.</p>
<pre class="brush: groovy; title: ; notranslate">
void handle(Event event) {
    println &quot;Contact event listener recevied an event : ${event.class.simpleName}&quot;
    if (event.class in [ContactCreatedEvent, ContactNameChangedEvent, ContactDeletedEvent, AddressAddedEvent]) {
        doHandle(event)
    } else {
        println &quot;Event not supported&quot;
    }
}

private void doHandle(ContactCreatedEvent event) {
    def contact = new ContactEntry(name: event.name, identifier: event.aggregateIdentifier.toString())
    contact.save()
}

private void doHandle(ContactNameChangedEvent event) {
    ContactEntry foundContact = ContactEntry.findByIdentifier(event.aggregateIdentifier.toString())
    foundContact.name = event.newName
    foundContact.save()
}
</pre>
<p>The ContactEntry is the query domain object. See how we query for an existing contact and how we store the new or updated contact in the query database.</p>
<h2>Summary</h2>
<p>That is about it for now. I have showed you some basic Axon components in groovy. I introduced you to the concept of a state datastore and a query datastore. Next to that I also told you about the commands. I did not tell you anything about the datastore used for storing the state. The sample makes use of the file based event sourcing datastore. Check the Axon documentation to find out more.</p>
<p>In the following blog posts I will improve the sample by making better screens and controllers. i will also talk more about the axon options. Try to use annotations to see if that makes the event listeners and the command handlers easier to understan.</p>
<p>Hope to see yo back.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F04%2F08%2Fuse-grails-and-axon-to-create-a-cqrs-application-part-i%2F&amp;title=Use%20Grails%20and%20Axon%20to%20create%20a%20CQRS%20application%20%28part%20I%29&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Doing more with groovy</title>
		<link>http://www.gridshore.nl/2010/04/05/doing-more-with-groovy/</link>
		<comments>http://www.gridshore.nl/2010/04/05/doing-more-with-groovy/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 18:19:09 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[gradle]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[grape]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1021</guid>
		<description><![CDATA[<p>I have big plans with groovy. After playing around with grails and doing some groovy scripting I was sure. I want more groovy. To be able to do more with groovy, I needed to learn more about groovy. One way to do this is to start reading and experimenting. This blog post discusses a [...]]]></description>
			<content:encoded><![CDATA[<p>I have big plans with groovy. After playing around with grails and doing some groovy scripting I was sure. I want more groovy. To be able to do more with groovy, I needed to learn more about groovy. One way to do this is to start reading and experimenting. This blog post discusses a few experiments as well as some of the learning sources.</p>
<p><span id="more-1021"></span>
<p>The best learning source for me consists of a number of manning books:</p>
<ul>
<li><a href="http://www.manning.com/gsmith/">Grails in Action</a></li>
<li><a href="http://www.manning.com/koenig2/">Groovy in Action (2nd edition)</a></li>
</ul>
<p>The first thing I did was creating some scripts, I mainly copied some sources from others. I also wrote a blog post about the groovy goodness:</p>
<p><a href="http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/">http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/</a></p>
<p>Again I was amazed by the way groovy is used to obtain a webpage and print the contents of the page. The following code block shows the script.</p>
<pre class="brush: groovy; title: ; notranslate">
#!/usr/bin/env groovy
def NEW_LINE = System.getProperty(&quot;line.separator&quot;)
def address = &quot;http://www.applenieuws.nl/?feed=rss&quot;
def urlInfo = address.toURL()
println &quot;URL: ${address}${NEW_LINE}&quot;
println &quot;URL Text: ${urlInfo.text}${NEW_LINE}&quot;
println &quot;Host/Port: ${urlInfo.host}/${urlInfo.port}${NEW_LINE}&quot;
println &quot;Protocol: ${urlInfo.protocol}${NEW_LINE}&quot;
println &quot;User Info: ${urlInfo.userInfo}${NEW_LINE}&quot;
println &quot;File: ${urlInfo.file}${NEW_LINE}&quot;
</pre>
<p>But since you are reading this I guess you are already interested in groovy. This post is not for experts in groovy. It is more focussed on people trying to find out if groovy is going to help them work more effectively or just for the fun of it.</p>
<h2>Integration</h2>
<p>I love the integration of groovy and java. You can implement a java interface with groovy. You can call a groovy class from java code. One of the things you are able to do is use spring annotations like @Autowired and @Component in groovy. The following code block shows a listener that can function within an Axon application to receive events. Nice stuff isn&#8217;t it?</p>
<pre class="brush: groovy; title: ; notranslate">
@Component
class GroovyAddressListener implements org.axonframework.core.eventhandler.EventListener {

  @Autowired
  GroovyAddressListener(SimpleEventBus eventBus) {
    eventBus.subscribe this
  }

  void handle(Event event) {
    if (event instanceof AddressRegisteredEvent) {
      println &quot;a new address in city ${event.address.getCity()} is received.&quot;
    }
  }
}
</pre>
<p>If you are not familiar with the Axon Framework, check the website <a href="http://www.axonframework.org">www.axonframework.org</a>. I am also planning a blog post around a sample I am creating with a tight integration of Axon and Grails.</p>
<p>Due to the easy integration of groovy and java, people that like groovy create wrappers around existing java libraries to make them better useable. On of those examples is the <a href="http://groovy.codehaus.org/modules/http-builder/">HttpBuilder project</a>. This is a project that wraps the apache http client.</p>
<h2>Building groovy</h2>
<h3>Using maven</h3>
<p>What is with software that it needs to be build. In java land we have maven. Nowadays (maven 3), maven is even powered by groovy. If you want to integrate groovy with java, a maven build seems very logical. There is a good maven plugin for building groovy. Checkout the following page to learn about the maven configuration.</p>
<p><a href="http://btilford.blogspot.com/2010/02/groovy-170-and-gmaven-12-multi-module.html">http://btilford.blogspot.com/2010/02/groovy-170-and-gmaven-12-multi-module.html</a></p>
<p>If you want to compile groovy classes into java classes and use them in your own application, you need to add the groovy library to your classpath. The groovy maven plugin itself is easy to configure. The following code block shows an example that makes use of the groovy maven plugin.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.codehaus.gmaven.runtime&lt;/groupId&gt;
        &lt;artifactId&gt;gmaven-runtime-1.7&lt;/artifactId&gt;
        &lt;version&gt;1.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
        &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
        &lt;version&gt;1.7.0&lt;/version&gt;
    &lt;/dependency&gt;
&lt;dependencies&gt;
&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.codehaus.gmaven&lt;/groupId&gt;
            &lt;artifactId&gt;gmaven-plugin&lt;/artifactId&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;generateStubs&lt;/goal&gt;
                        &lt;goal&gt;generateTestStubs&lt;/goal&gt;
                        &lt;goal&gt;compile&lt;/goal&gt;
                        &lt;goal&gt;testCompile&lt;/goal&gt;
                    &lt;/goals&gt;
                    &lt;configuration&gt;
                        &lt;providerSelection&gt;1.7&lt;/providerSelection&gt;
                    &lt;/configuration&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<h3>Using grails</h3>
<p>Cannot get easier than this, just create a project and use the grails commands. Grails also makes it very easy to add libraries to the project. These libraries can be used in the normal grails classes: domain, controller, service. But you can also use them in your own groovy classes. I use this extensively in the grails/axon integration sample.</p>
<p>In your grails project go to the directory <em>grails-app/conf</em>. There you can find the BuildConfig.groovy. Within this file you can find the dependencies. The following code block gives you an example to include the axon framework as a compile time dependency and xstream as a runtime dependency. To be able to use this you have to uncomment the <em>mavenLocal()</em> in de dependencies part of the same file.</p>
<pre class="brush: groovy; title: ; notranslate">
  dependencies {
    compile 'org.axonframework:axon-core:0.5-SNAPSHOT'
    runtime 'com.thoughtworks.xstream:xstream:1.3.1'
  }
</pre>
<p>Of course you could obtain libraries from other maven repositories, but since we use the snapshot that is not available in a repository we use the local maven repository.</p>
<p>The complete dependency model of grails is pretty extensive and a bit to much to discuss in detail.</p>
<h3>Using Gradle</h3>
<p>If you are only doing groovy, maven might not be the best choice. Even if you are combining java and groovy some people say maven is not the right choice. I think it is a matter of taste although I do think maven is pretty verbose. An alternative in groovy landscape is <a href="http://www.gradle.org/">Gradle</a>. Gradle uses convention over configuration. It needs less lines of code than ant (without custom libraries) and gives more freedom than maven. Maybe the best about grails is that it does not use xml, but it uses groovy instead.</p>
<p>Peter Ledbrook is doing a good job in using gradle to build grails projects. Read his blog post : <a href="http://www.cacoethes.co.uk/blog/groovyandgrails/building-a-grails-project-with-gradle">http://www.cacoethes.co.uk/blog/groovyandgrails/building-a-grails-project-with-gradle</a>. Personally I do think this is one step to far. For me the grails build system is good enough. I also had a lot of tooling problems when combining gradle and grails in intellij. I did not get the classpath like I wanted to. Using the mechanism as described in the grails part of build works for me. I do think they borrowed some good ideas (dependency management) from gradle.</p>
<h3>Grapes</h3>
<p>The last tool you can use when running groovy I would like to mention is <a href="http://groovy.codehaus.org/Grapes+and+grab()">Grapes</a>. I like the idea for dependency management in scripts. There is a very easy way to add libraries to your classpath by using the grab mechanism. I like the example as published on the page about the <a href="http://groovy.codehaus.org/HTTP+Builder">groovy Http builder</a>. I am not going to reprint the example here. It all has to do with the grab annotation. The following line only shows the grab command.</p>
<pre>
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
</pre>
<p>So even in a command line script you can now use libraries managed by Grapes.</p>
<p>That is it for now, more to follow the next months.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F04%2F05%2Fdoing-more-with-groovy%2F&amp;title=Doing%20more%20with%20groovy&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/04/05/doing-more-with-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Still doing grails</title>
		<link>http://www.gridshore.nl/2010/01/10/still-doing-grails/</link>
		<comments>http://www.gridshore.nl/2010/01/10/still-doing-grails/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 11:07:31 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[grails-ui]]></category>
		<category><![CDATA[rss]]></category>
		<category><![CDATA[searchable]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=984</guid>
		<description><![CDATA[<p></p> <p>This is the third post in a series of post about grails. In this series I am describing an application I am creating with grails. It is a scheduling application for scheduling people on projects. You can find the previous posts here:</p> http://www.gridshore.nl/2009/12/20/starting-with-grails/ http://www.gridshore.nl/2010/01/04/continuing-with-grails/ <p>In this post I will discuss the following topics:</p> [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" alt="F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" border="0" width="134" height="117" align="right" /></p>
<p>This is the third post in a series of post about grails. In this series I am describing an application I am creating with grails. It is a scheduling application for scheduling people on projects. You can find the previous posts here:</p>
<ul>
<li><a href="http://www.gridshore.nl/2009/12/20/starting-with-grails/">http://www.gridshore.nl/2009/12/20/starting-with-grails/</a></li>
<li><a href="http://www.gridshore.nl/2010/01/04/continuing-with-grails/">http://www.gridshore.nl/2010/01/04/continuing-with-grails/</a></li>
</ul>
<p>In this post I will discuss the following topics:</p>
<ul>
<li>Creating meeting notes using the grails-ui rich text editor</li>
<li>Create a search using the searchable plugin on the meeting notes</li>
<li>Introducing rss to subscribe to new meeting notes</li>
</ul>
<p><span id="more-984"></span><br />
<h2>Meeting notes</h2>
<h3>Create the basics</h3>
<p>For the meeting notes we want a large text field that can contain html to make it look better. We start of with the domain object. We give it three fields: a weekNr a User and the notes. The notes field must become a Text field in the database and a textarea on the screen. To accomplish this, we add a mapping element with the following contents as well as the constraints to make it an html textarea element. (Yes I know this feels strange)</p>
<pre class="brush: groovy; title: ; notranslate">
class MeetingNotes {
    int weekNr
    User user
    String notes
    static constraints = {
        notes(blank:false, widget:&quot;textarea&quot;)
    }
    static mapping = {
        notes type:&quot;text&quot;
    }
}
</pre>
<p>Next step is the controller, for now we add the scoffold property and configuration to add it to the navigation. The next code block shows the first implementation.</p>
<pre class="brush: groovy; title: ; notranslate">
class MeetingNotesController {
    def scaffold = true

    static navigation = [
            group: 'tabs',
            order: 110,
            subItems: [
                    [group: 'tabs', action: 'create']
            ]
    ]
}
</pre>
<p>The create screen now looks like this:</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-09-at-17.16.59.png" alt="Screen shot 2010-01-09 at 17.16.59.png" border="0" width="500" height="490" /></div>
<h3>Use the rich text editor</h3>
<p>In include the rich text editor, we generate the views and make changes to those. Than we change the create.jsp in views/meetingnotes. We start by removing the navigation. Than we add the following line to the head element.</p>
<pre>
&lt;gui:resources components="richEditor"/&gt;
</pre>
<p>Then we just need to make a small change to the gsp. Look for the line with <em>g:textArea</em>. We replace this input item with the following line.</p>
<pre>
&lt;gui:richEditor id='notes' value='add your weekly notes here ....'/&gt;
</pre>
<p>This results in the following screen:</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-09-at-18.01.22.png" alt="Screen shot 2010-01-09 at 18.01.22.png" border="0" width="500" height="490" /></div>
<p>The same changes need to be made to the edit.gsp. I also removed the navigation from the other gsp&#8217;s. Time to move on, now we are going to include the searchable plugin and make the weekly meeting notes searchable.</p>
<h2>The searchable plugin</h2>
<p>Let us start with the basics and install the plugin, configure the MeetingNotes domain class to be searchable, and look at the generated search screen. You can find these steps as well in the <a href="http://www.grails.org/Searchable+Plugin+-+Quick+start">quick start</a> from the plugin documentation.</p>
<pre>
grails install-plugin searchable
</pre>
<p>Now the hard part to make our MeetingNotes searchable, we have to add the following line to the MeetingNotes domain class.</p>
<pre>
static searchable = true
</pre>
<p>For real, that is it. Now you can browse to the controller that serves the search.</p>
<p>I have created three items that all contain data, the following screen shows the standard search controller. Only two items will be returned if I look for the project name cqrs4j</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-10-at-09.59.29.png" alt="Screen shot 2010-01-10 at 09.59.29.png" border="0" width="500" height="490" /></div>
<p>That is all nice, but it does not really integrate with our site. Therefore we want to make a controller that does the search thing and an input box beneath the header menu.</p>
<p>First I add a line to the UrlMappings that maps the /search request to the SearchableController that comes out of the box. Check the file UrlMappings.groovy in the conf folder.</p>
<pre>
"/search" (controller:"searchable")
</pre>
<p>Now we will override the view of that comes with the plugin and make it look more like our own. This page, <a href="http://www.grails.org/Searchable+Plugin+-+SearchableController+and+view">Controller and view</a>, describes how you can do that. I copied the index.gsp from the path ${user.home}/.grails/1.2.0/projects/MyScheduling/plugins/searchable-0.5.5/grails-app/views/searchable/index.gsp to the same location in my own application. Then I alter that index.gsp, add the template, remove some styling and I have a better looking page. I also copied the form into the main.gsp layout so we have a search box on each page. The following screendump shows the result.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-10-at-10.49.38.png" alt="Screen shot 2010-01-10 at 10.49.38.png" border="0" width="500" height="488" /></div>
<p>There you have it, basic search implemented in our own application. Looking really integrated.</p>
<p>There is topic that I also want to mention, this is suggestions. You know them from google and more advanced search solutions. You know what, we have an advanced search now as well. We just have to configure that we want to use suggestions. With this option configured, the results page shows a link to try the search again with suggestions. As an example try to search for <em>holday</em>, you get no results, try the suggestions and you get the following screen.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-10-at-11.02.28.png" alt="Screen shot 2010-01-10 at 11.02.28.png" border="0" width="500" height="488" /></div>
<p>To do this, we change the searchable part of the MeetingNotes into the following lines:</p>
<pre class="brush: groovy; title: ; notranslate">
    static searchable = {
        spellCheck &quot;include&quot;
    }
</pre>
<p>The search plugin has a lot of options and functionality. I urge you to have a look at the <a href="http://www.grails.org/plugin/searchable">plugin page</a>.</p>
<h2>Rss feed</h2>
<p>A very often method used to be informed for new items is rss. I want to create a feed for all meeting notes. That way people get notified when a new Meeting Note is created. To create the feed, I use the <a href="http://www.grails.org/plugin/feeds">feeds plugin</a>.</p>
<p>Again it all starts with the installation of the plugin. The plugin makes use of the framework Rome. So if you are familiar with that, this should not be to hard. Not that it is hard if you do not have the knowledge.</p>
<pre>
grails install-plugin feeds
</pre>
<p>Now adding the feed consists of two parts. The first part is to add a feed method to the MeetingNotes controller. The second part is two add the special html tag, which is done using a grails tag.</p>
<pre>
&lt;feed:meta kind="rss" version="2.0" controller="meetingNotes" action="feed"/&gt;
</pre>
<pre class="brush: groovy; title: ; notranslate">
    def feed = {
        render(feedType:&quot;rss&quot;, feedVersion:&quot;2.0&quot;) {
            title = &quot;Meeting Notes feed&quot;
            link = &quot;${grailsApplication.config.grails.serverURL}/meetingNotes/feed&quot;
            description = &quot;All meeting notes that have been written per week&quot;
            MeetingNotes.list().each() { note -&gt;
                entry(&quot;weekNr : ${note.weekNr}&quot;) {
                    link = &quot;${grailsApplication.config.grails.serverURL}/meetingNotes/show/${note.id}&quot;
                    &quot;Meeting notes for week number ${note.weekNr} by ${note.user.userRealName}&quot; // return the content
                }
            }
        }
    }
</pre>
<p>The code is so easy I hardly need to explain anything. One thing that had a problem at the moment is hard wiring the name of the server to get the feed from. The only trick I want to point out is the way to construct the link (line 4 and 8). We use the special mechanism to read parameters from the config that can be environment specific. The <em>grails.serverURL parameter</em> is by default configured in the Config.groovy configuration file.</p>
<p>In safari I now have the following result.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-10-at-12.00.01.png" alt="Screen shot 2010-01-10 at 12.00.01.png" border="0" width="500" height="426" /></div>
<p>That is it for this post. I am still amazed by how easy things are using grails. Most of the time I spend on getting the ui done. In the next post I will not introduce new plugin, but I will focus on getting the solutions better. Add validation, better configured access control, internationalization. Those kind of topics.</p>
<p>Hope to see you back.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F01%2F10%2Fstill-doing-grails%2F&amp;title=Still%20doing%20grails&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/01/10/still-doing-grails/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Continuing with grails</title>
		<link>http://www.gridshore.nl/2010/01/04/continuing-with-grails/</link>
		<comments>http://www.gridshore.nl/2010/01/04/continuing-with-grails/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 16:26:00 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=975</guid>
		<description><![CDATA[<p> <p>In my previous post Starting with grails, I wrote a long story about creating a new application with grails. I introduced some plugins and gave some hints and tips about working with grails from a starter perspective. As I move on, I will write down other things I have done.</p> <p>Some of the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" alt="F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" border="0" width="134" height="117" align="right" />
<p>In my previous post <a href="http://www.gridshore.nl/2009/12/20/starting-with-grails/">Starting with grails</a>, I wrote a long story about creating a new application with grails. I introduced some plugins and gave some hints and tips about working with grails from a starter perspective. As I move on, I will write down other things I have done.</p>
<p>Some of the things you can find in this post are:</p>
<ul>
<li>Using <a href="http://developer.yahoo.com/yui/grids/">yahoo ui grid</a> for laying out the page</li>
<li>Creating a second navigation menu</li>
<li>Mail integration for the contact form</li>
<li>Implement access control, so only known users can use the application.</li>
</ul>
<p><span id="more-975"></span><br />
<h2>Yahoo Grid</h2>
<p>Laying out a page is not easy. Especially not when you want to facilitate resizing of all browsers. Why would you want to develop stylesheets yourself if you can get a good one for free. I decided to use yahoo grids to layout the base components of my pages. It fits very well with sitemesh and of course grails.</p>
<p>If you want to learn more about what yahoo grid is, check the following page. I personally like the <a href="http://yuiblog.com/assets/pdf/cheatsheets/css.pdf">cheatsheet</a> they provided a lot.</p>
<p>Yahoo grids is all about stylesheets, you can link to the stylesheets located at yahoo servers. To do that add the following line to the main template. You can find the main template in grails-app/views/layouts/main.gsp</p>
<pre>
&lt;link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.0r4/build/reset-fonts-grids/reset-fonts-grids.css/"&gt;
</pre>
<p>Than you need to think about the layout of your page. I want a page that uses the maximum space. In the header I want a logo and the navigation. The body consists of two columns, one for the main content and the other for messages, special actions using ajax controls, and other things I can think of.</p>
<p>The main layout items are in the maain.gsp that I mentioned before. The body element is split into two elements, one for the actual content using the sitemesh g:layoutBody. The other contains the flash message and flash error message. For these classes I included some styling in the web-app/css/main.css.</p>
<h2>Adding a second menu</h2>
<p>I also want a menu with items like about and contact. So we go back to the navigation plugin. Now I have create a new menu group called sitemenu. For now there are two controllers adding items to this menu, the Contact and About controller. Now we need to change the style of this menu, we make it float right and change some of the styling. To do this, we add the following lines to the main.css mentioned earlier.</p>
<pre class="brush: css; title: ; notranslate">
#sitemenu .navigation li a { background-color: #fff }
#sitemenu .navigation li.navigation_active a { background-color: #fff; color:#555; text-decoration:underline}
#sitemenu .navigation li.navigation_active a:hover { background-color: #fff;}
#sitemenu .navigation li a:hover { background-color: #999; }
#sitemenu .navigation li a { color: #555; }
#sitemenu .navigation li a:hover { color: #555; text-decoration:underline}
#sitemenu .navigation li { border: 1px solid #fff; background-color: #fff }
</pre>
<p>The next code block shows the changed main.gsp, for now only the part containing the header</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;doc3&quot;&gt;
  &lt;div id=&quot;hd&quot;&gt;
    &lt;div id=&quot;sitemenu&quot;&gt;
      &lt;nav:render group=&quot;sitemenu&quot;/&gt;
    &lt;/div&gt;
    &lt;div id=&quot;grailsLogo&quot; class=&quot;logo&quot;&gt;&lt;a href=&quot;http://grails.org&quot;&gt;&lt;img src=&quot;${resource(dir: 'images', file: 'grails_logo.png')}&quot; alt=&quot;Grails&quot; border=&quot;0&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
    &lt;div id=&quot;menu&quot;&gt;
      &lt;nav:render group=&quot;tabs&quot;/&gt;
      &lt;nav:renderSubItems group=&quot;tabs&quot;/&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div id=&quot;bd&quot;&gt;
  &lt;/div&gt;
  &lt;div id=&quot;ft&quot;&gt;
  &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>That is step one in creating a better looking application. The following screendump gives you an idea where we are right now.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-12-25-at-11.38.06.png" alt="Screen shot 2009-12-25 at 11.38.06.png" border="0" width="869" height="662" /></div>
<p>Next up is the create scheduling items screen.</p>
<h2>Improving form layout of create scheduling items screen</h2>
<p>Let me state up front, this is not easy. I am not the king in stylesheets, so don&#8217;t take this as the best example. I had a hard time limiting the length of the autocomplete boxes. I ended up limiting the div surrounding the input box. For the date picker I had a simular problem. By default position elements left and top are not zero. Also a padding is not nice in this form. Therefore I added a style block into the html. Not ideal, you would want to have this in a central place, but I do not know how to do this. If someone has suggestions, please place a comment to this post.</p>
<p>The following screendump shows what it looks like right now with one of the date pickers popped open.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-12-25-at-12.25.14.png" alt="Screen shot 2009-12-25 at 12.25.14.png" border="0" width="870" height="771" /></div>
<h2>Adding logo</h2>
<p>The grails logo is nice, but not what you want to have in your application. Changing it is very easy. Just open the main.gsp in the views/layout folder. Create a logo and probably a favicon.ico and put them in the web-app/images folder. Find the link in the header of the template with the shortcut icon. If you named the ico file the same you do not have to change a thing. For the logo you need to find the div with the id grailslogo. See how the function resources is used to create the src of the img tag.</p>
<p>If you do not know how to create an ico file, check this website: <a href="http://www.favicon.cc/">favicon.cc</a></p>
<h2>Mail integration</h2>
<p>The contact form can be used to send a mail to responsible users of the system. To be able to send the mail, we are going to use the mail plugin. Installing it is easy with the command:</p>
<pre>
grails install-plugin mail
</pre>
<p>Configuration of the plugin is done in the Config.groovy. You can set the mail.host and the default.from properties. The mail service is injected in the Controllers and can be injected in the services by declaring a mailService property. You can send messages inline by providing a closure with the properties. Another mechanism is by using a template or a view. When sending the mail from a service you do not have the current request. Then you can still use the views, do provide the absolute paths if you use the service to generate the mail. It is also possible to take the template from a plugin, check the <a href="http://www.grails.org/plugin/mail">page of the mail plugin</a>.</p>
<p>In my example I am using the controller to send a mail and the template for an html mail. I also use a trick with system properties to prevent my password to be send to GIT. Let us focus on the configuration first. The following code block shows the configuration of mail using a gmail account. Check the System.getProperty usage for obtaining the userid and the password</p>
<pre class="brush: groovy; title: ; notranslate">
grails {
    mail {
        host = &quot;smtp.gmail.com&quot;
        port = 465
        username = System.getProperty(&quot;gmail.userid&quot;) + &quot;@gmail.com&quot;
        password = System.getProperty(&quot;gmail.password&quot;)
        props = [&quot;mail.smtp.auth&quot;:&quot;true&quot;,
                 &quot;mail.smtp.socketFactory.port&quot;:&quot;465&quot;,
                 &quot;mail.smtp.socketFactory.class&quot;:&quot;javax.net.ssl.SSLSocketFactory&quot;,
                 &quot;mail.smtp.socketFactory.fallback&quot;:&quot;false&quot;]
    }
}
</pre>
<p>In the contact/index.gsp I created a form with a few fields. The submit is send to the mail method of the ContactController. Like I said, the mailService is available to all controllers. The following code block shows how to send the mail.</p>
<pre class="brush: groovy; title: ; notranslate">
    def mail = {
        if (params.yourname) {
            sendMail {
                to &quot;jettro@gridshore.nl&quot;
                subject &quot;Contact Form&quot;
                html g.render(template: &quot;contactMailTemplate&quot;,
                        model:[remark:params.remark,yourname:params.yourname,yourmail:params.yourmail])
            }
            flash.message = &quot;Thank you for your remark, will get back to you if desired!&quot;
        } else {
            flash.error = &quot;Could not send a message, no name!&quot;
        }
        redirect (controller:&quot;contact&quot;)
    }
</pre>
<p>Check the way to make an html mail using a template and model parameters. More examples are available at the plugins page. We use a template to generate the mail. Easy stuff or not? Remember from that grails introduction that you need to prepend a template with an &#8220;_&#8221;, so we create contact/_contactMailTemplate.gsp. The following code block shows this file.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;%@ page contentType=&quot;text/html&quot; %&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Welcome Aboard&lt;/title&gt;
  &lt;style type=&quot;text/css&quot;&gt;
  body {
    font-family: &quot;Trebuchet MS&quot;
  }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Howdy!&lt;/h1&gt;
&lt;p&gt;
  We have a remark from : &lt;strong&gt;${yourname}&lt;/strong&gt; with &lt;strong&gt;${yourmail}&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
  ${remark}
&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Of course this is not the end of the line, we need to add form validation, maybe a better confirmation screen. You name it, but that is not making the mail integration harder. It will be the same.</p>
<h2>Access control</h2>
<p>There are multiple plugins to do authentication/authorization or access control. I have a history with the spring security project, therefore I will use the <a href="http://grails.org/plugin/acegi">acegi or spring security plugin</a>. I do have to warn you that this is not the easiest plugin available. But security is not easy. The plugin comes with some nice shortcuts to create the required classes. I am not going to be very thorough in my description of the plugin, since it is still kind of a beginners blog post.</p>
<p>Some things you should know about the security plugin:</p>
<ul>
<li>You can use a map, spring xml configurtation as well as annotations to configure security</li>
<li>You need three domain classes: User, Role and RequestMap</li>
<li>You can secure url patterns using the admin screens of your application.</li>
</ul>
<p>Now let us start securing our application. First install the plugin. Then we generate the domain classes.</p>
<pre>
grails install-plugin acegi
grails create-auth-domains nl.gridshore.scheduling.User nl.gridshore.scheduling.Role nl.gridshore.scheduling.Requestmap
</pre>
<p>Now we start the application and nothing really changed since we have not secured anything yet. Next up is securing the creating of new Persons. This should only be possible by a user with admin rights. For now we are going to create three roles, the viewer, the admin and the sysadmin.</p>
<p>To be able to add roles, we need to add the Role controller. We also need the Requestmap controller. We already had the user controller.</p>
<p>Now you can use the following urls to add roles and Requestmap items. I have added some code to the bootstrap class. I did have a problem with the Requestmap items, they were not updated. I had to restart the container to make them actually work. During development you cannot recreate the database each time without loosing the items. Therefore you really need the Bootstrapper. The following lines of code create the roles as well as the Requestmap items.</p>
<pre class="brush: groovy; title: ; notranslate">
def roleAdmin = new Role(authority:&quot;ROLE_ADMIN&quot;,description:&quot;admin&quot;)
roleAdmin.save()
def roleSysAdmin = new Role(authority:&quot;ROLE_SYSADMIN&quot;,description:&quot;sysadmin&quot;)
roleSysAdmin.save()

def securePerson = new Requestmap(url:&quot;/person/**&quot;,configAttribute:&quot;ROLE_ADMIN&quot;)
securePerson.save()
def secureProject = new Requestmap(url:&quot;/project/**&quot;,configAttribute:&quot;ROLE_ADMIN&quot;)
secureProject.save()
</pre>
<p>When adding a new user I came to the conclusion that the defautl scaffolding screens do not work appropriately. Therefore I create the screens and controller of the User and other security related classes using the special script.</p>
<pre>
grails generate-manager
</pre>
<p>Now everything works fine, I removed the navigation from the generated screens and the create user screen looks like the following image. Check the way the roles can be added to a user. Good stuff. My final steps are creating an admin user and a sysadmin user and securing the user, requestmap and role screens as well. That is all pretty straightforward.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-01-04-at-17.19.01.png" alt="Screen shot 2010-01-04 at 17.19.01.png" border="0" width="860" height="714" /></div>
<h2>Final remarks</h2>
<p>We covered some big topics. Made the application look better. Implemented security using the spring security plugin. We also made a contact form using the mail plugin. In the next blogpost I will write about the search plugin and some optimizations to the current code base and maybe google charts.</p>
<p>If you have comments, tips, improvements feel free to contact me.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F01%2F04%2Fcontinuing-with-grails%2F&amp;title=Continuing%20with%20grails&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/01/04/continuing-with-grails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Starting with grails</title>
		<link>http://www.gridshore.nl/2009/12/20/starting-with-grails/</link>
		<comments>http://www.gridshore.nl/2009/12/20/starting-with-grails/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 15:25:56 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[google chart]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[grails-ui]]></category>
		<category><![CDATA[navigation]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=955</guid>
		<description><![CDATA[<p> <p>In this blog post I am writing down the steps I took to create a new grails application. Maybe it can be of help to other that want to start using grails.</p> <p>In short I am going to create an application that you can use to schedule people on projects. We used to [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" alt="F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" border="0" width="134" height="117" align="left" />
<p>In this blog post I am writing down the steps I took to create a new grails application. Maybe it can be of help to other that want to start using grails.</p>
<p>In short I am going to create an application that you can use to schedule people on projects. We used to have an excel sheet to do this, but I really do not like this. So I am writing an application for it. Grails is ideal for these kind of projects.</p>
<p>I am, of course, going to use some nice grails plugins, I will mention them all and give some details about the steps I took to make them run. Some of the plugins are:</p>
<ul>
<li>DBUtil</li>
<li>Navigation</li>
<li>grails-ui</li>
<li>joda-time</li>
</ul>
<p>Comments, questions and feedback are of course welcome.</p>
<p><span id="more-955"></span><br />
<h2>First steps</h2>
<p>A grails application starts with creating the application. For some reason I still like to do this on the command line. I do not use the excellent intellij to do this. But I will use it extensively for the remainder.</p>
<pre>
grails create-app MyScheduling
</pre>
<p>Next step is adding it to a source repository. I am getting more enthusiastic about using git, so I create a repository at github. You can find my sources here:</p>
<p><a href="http://github.com/jettro/MyScheduling">http://github.com/jettro/MyScheduling</a></p>
<p>One of the things I like about git is the .gitignore file. A very clean way to prevent certain files from being added to the repository. The following shows the contents of my .gitignore file.</p>
<pre>
# used to ignore certain files by git
# mac osx files
.DS_Store
# intellij files
.idea/*
*.ipr
*.iws
# (grails) generated files
target/*
out/*
stacktrace.log
</pre>
<p>enough about git, let us move on to the nice parts about grails.</p>
<h2>Starting with the domain</h2>
<p>At the beginning I start with only a few domain classes.</p>
<ul>
<li>Person &#8211; the people we want to schedule on projects</li>
<li>Project &#8211; well it is a project</li>
<li>User &#8211; the ones that actually are allowed to use the application</li>
</ul>
<p>There is not a lot of information in these domain objects for now. I use intelllij to create the domain classes, but command is easy as well, <em>grails create-domain-class nl.gridshore.scheduling.Person</em>There is a many to many relationship between projects and persons. I also created the controllers for the three domain classes with just one line of code in each class.</p>
<pre>
def scaffold = true
</pre>
<p>This line makes all the views available, you can now start the application and browse to the homepage. I use intellij to start the application but <em>grails run-app</em> will work fine as well.</p>
<p>THe following is a tip that you can use when creating your domain model.</p>
<h2>DBUtil plugin</h2>
<p>this plugin can be used to look at the data and the datamodel of an in memory database, which is the default for new applications. To me this is a must have plugin.</p>
<pre>
grails install-plugin db-util
</pre>
<h2>Navigation</h2>
<p>I make use of the navigation plugin, you can find the information about the plugin here:</p>
<p><a href="http://www.grails.org/Navigation+plugin">http://www.grails.org/Navigation+plugin</a></p>
<p>We start of by introducing the navigation to our won (non-scaffolding) controllers. So we create a HomeController. Next we tell the navigation plugin to include the home controller in the navigation. We have to add one line to the controller.</p>
<pre>
static navigation = true
</pre>
<p>Yep, it is that easy. We also need to create the index.gsp in views/home. Now enrich our template with the navigation component, therefore we open up the main.gsp in views/layouts. There is two things we need to do, first add a header part to include styling and scripts. Then we add a <em>div</em> with the menu elements.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;&lt;g:layoutTitle default=&quot;Grails&quot;/&gt;&lt;/title&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir: 'css', file: 'main.css')}&quot;/&gt;
  &lt;link rel=&quot;shortcut icon&quot; href=&quot;${resource(dir: 'images', file: 'favicon.ico')}&quot; type=&quot;image/x-icon&quot;/&gt;
  &lt;g:layoutHead/&gt;
  &lt;nav:resources group=&quot;tabs&quot;/&gt;
  &lt;g:javascript library=&quot;application&quot;/&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;spinner&quot; class=&quot;spinner&quot; style=&quot;display:none;&quot;&gt;
  &lt;img src=&quot;${resource(dir: 'images', file: 'spinner.gif')}&quot; alt=&quot;Spinner&quot;/&gt;
&lt;/div&gt;
&lt;div id=&quot;grailsLogo&quot; class=&quot;logo&quot;&gt;&lt;a href=&quot;http://grails.org&quot;&gt;&lt;img src=&quot;${resource(dir: 'images', file: 'grails_logo.png')}&quot; alt=&quot;Grails&quot; border=&quot;0&quot;/&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div id=&quot;menu&quot;&gt;
  &lt;nav:render/&gt;
&lt;/div&gt;
&lt;g:layoutBody/&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If you are following along and you are like me seeing an almost white page without any navigation what soever, check if you have added the meta tag for sitemesh to your gsp. Go to our homepage or to the url: <a href="http://localhost:8080/MyScheduling/home">http://localhost:8080/MyScheduling/home</a>. You should now see the following screen:</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-12-19-at-10.53.47.png" alt="Screen shot 2009-12-19 at 10.53.47.png" border="0" width="749" height="360" align="center"/></p>
<p>Of course we also want to be able to create persons from the home page controller. So we add other controllers to the menu as well. Let us start with the person controller. In my first try the Person button was placed before the Home button, that is not what I want. So we add ordering to the menu. This can be done by assigning an array with configuration options to the static navigation declaration. As you might have expected, the name of the property to configure is called <em>order</em>.</p>
<p>Next up is subnavigation, let us add a submenu item for adding a new person. The following code shows how to do just that.</p>
<pre>
    static navigation = [group:'tabs',order:10]
</pre>
<p>We now need to add the generation of the submenu to our template as well. Add the following line to the main.gsp right belof the nav:render tag.</p>
<pre>
&lt;nav:renderSubItems/&gt;
</pre>
<p>And the subnavigation for person becomes</p>
<pre class="brush: groovy; title: ; notranslate">
    static navigation = [
            group:'tabs',
            order:150,
            title:'person',
            subItems:[
                    [group:'tabs',action:'create',title:'create']
            ]
    ]
</pre>
<p>The following screen is the result:</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-12-19-at-11.13.46.png" alt="Screen shot 2009-12-19 at 11.13.46.png" border="0" width="756" height="440" /></div>
<p>As you can see, we have the default scaffolding buttons as well, so we have to remove the navigation from the scaffolding screens. More on that later, for now I want to add one latest thing and that is i18n messages or labels. This is not the easiest thing, you need to use the groups thing or it won&#8217;t work. But other than that it is again pretty painless.</p>
<p>Let us move on to the next topic, more ui, we will continue with the grails ui plugin</p>
<h2>The grails-ui plugin</h2>
<p>The <a href="http://www.grails.org/plugin/grails-ui">grails ui plugin</a> contains a lot of different ui components. For now we focus on the autocomplete component, the date picker and the datatable component. We are going to create a screen that accepts a start date, an end date, and the amount of hours per week for a certain person and project. The person and project will use the autocomplete component and the date will use the date picker. Finally all the created ScheduleItems will be presented in a data table. First we install the grails ui plugin. I think you know how by now. If you are using intellij on the mac command+option+k.</p>
<p>Before this to be created screen has use, we need to introduce a few new things. We create a new domain class ScheduleItem with the week number, the amount of hours per week and of course the project and the person. Then we also create a service to create a schedule item, the ScheduleItemService. Of course we also need the controller to present the data and accept the form.</p>
<p>Before I start introducing the gui components I want to stress that you must not forget to add the following tag to each header of the page with the components you use on that page.</p>
<pre>
&lt;gui:resources components="dataTable,autoComplete,datePicker"/&gt;
</pre>
<h3>The datatable component</h3>
<p>This component consists of a controller component and a tag for a gsp page. The controller component is called using an ajax request and returns JSON. Things like filtering and pagination are supported out of the box thanks to the very easy grails way of doing queries. The following code block shows the controller code.</p>
<pre class="brush: groovy; title: ; notranslate">
    def scheduleItemDataAsJSON = {
        def list = []
        def allItems = ScheduleItem.list(params)
        response.setHeader(&quot;Cache-Control&quot;, &quot;no-store&quot;)
        allItems.each {
            list &lt;&lt; [
                id:it.id,
                person:it.person.toString(),
                project:it.project.toString(),
                weekNr:it.weekNr,
                nrHours:it.nrHours
            ]
        }
        def data = [
                totalRecords: ScheduleItem.count(),
                results: list
        ]
        render data as JSON
    }
</pre>
<p>As you can see in line 3 we use the gorm stuff to query the ScheduleItems. Than we create the list with items, check that we actually return the nested properties for person and project. If you forget to do this you will see something like [object Object] in the table. Finally we prepare the data object with the list of items an a count of the total items. This data is than returned as JSON.</p>
<p>Next up is the gsp part, the following code block shows the dataTable in action. I do want to explicitly tell you not to forget to add a component (div or the body) with the class yui-skin-sam. This is a requirement for the components to work. The total code than becomes.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div class=&quot;yui-skin-sam&quot;&gt;
  &lt;gui:dataTable
          id=&quot;scheduleItemDatatable&quot;
          draggableColumns=&quot;true&quot;
          columnDefs=&quot;[
            [key:'id', sortable:true, resizeable: true, label:'ID'],
            [key:'person', sortable:true, resizeable: true, label:'Person'],
            [key:'project', sortable:true, resizeable: true, label: 'Project'],
            [key:'weekNr', type:'number', sortable:true, resizeable: true, label: 'Week Nr'],
            [key:'nrHours', type:'number', sortable:true, resizeable: true, label: 'Nr Hours']
          ]&quot;
          paginatorConfig=&quot;[
            template:'{PreviousPageLink} {PageLinks} {NextPageLink} {CurrentPageReport}',
            pageReportTemplate:'{totalRecords} total records'
          ]&quot;
          controller=&quot;scheduling&quot;
          action=&quot;scheduleItemDataAsJSON&quot;
          resultsList=&quot;results&quot;
          rowExpansion=&quot;false&quot;
          rowsPerPage=&quot;15&quot;/&gt;
&lt;/div&gt;
</pre>
<p>The code is pretty easy to understand, check the controller and action method. The following screen dump shows the result.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-12-20-at-14.37.14.png" alt="Screen shot 2009-12-20 at 14.37.14.png" border="0" width="764" height="529" /></div>
<h3>Autocomplete</h3>
<p>In the overview screen of ScheduleItems we push the create button. In that screen we have the autocomplete and the datePicker. The datepicker is so easy I will not really go into it. Let us focus on the autocomplete. Again we have a controller part and a gsp part. I have taken the easy way, I provide all options from the controller. Using ajax is almost the same idea as the dataTable component. Still I want to limit these kind of requests. The following code block shows the controller to provided the options for the autocomplete.</p>
<p>    def create = {<br />
        def persons = Person.list()<br />
        def projects = Project.list()</p>
<p>        [projects: projects, persons: persons]<br />
    }</p>
<p>Now we have all the persons and projects available in the gsp view component. The code is pretty easy when not using ajax.</p>
<pre class="brush: xml; title: ; notranslate">
  &lt;div style=&quot;width:300px&quot;&gt;
    Person : &lt;span class=&quot;yui-skin-sam&quot;&gt;&lt;gui:autoComplete id=&quot;person&quot; options=&quot;${persons*.name}&quot;/&gt;&lt;/span&gt;
    Project : &lt;span class=&quot;yui-skin-sam&quot;&gt;&lt;gui:autoComplete id=&quot;project&quot; options=&quot;${projects*.name}&quot;/&gt;&lt;/span&gt;
  &lt;/div&gt;
</pre>
<p>The following image shows the form, yes I know, I need to spend time on the layout of the screen.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-12-20-at-14.45.04.png" alt="Screen shot 2009-12-20 at 14.45.04.png" border="0" width="761" height="643" /></div>
<p>For accepting the form submission we also need some code. The next code block shows the code that reads the form and calls the service.</p>
<pre class="brush: groovy; title: ; notranslate">
    def newScheduleItem = {
        def personName = params.person
        def projectName = params.project
        def nrHours = params.nrhours.toInteger()
        def weekNr = params.weeknr.toInteger()

        flash.message = &quot;New item is created for person ${personName} and project ${projectName}&quot;
        scheduleItemService.createScheduleItem(personName, projectName, weekNr, nrHours)
        redirect(action: &quot;create&quot;)
    }
</pre>
<p>That is it for the grails-ui plugin, let us move on to the next plugin.</p>
<h2>Joda time</h2>
<p>Groovy comes out of the box with a better Date object than standard java. Still joda time is the way to go. Therefore we will introduce the <a href="http://www.grails.org/plugin/joda-time">joda time plugin</a>. One of the reasons I need it, is that I want to work with week numbers. Joda time has out of the box support for this. So we install joda time.</p>
<p>For persisting dates, we need to tell grails to use the special joda time versions. Therefore we need to add special config lines to the Config.groovy.</p>
<pre class="brush: groovy; title: ; notranslate">
grails.gorm.default.mapping = {
   'user-type' (type: PersistentLocalDate, class: LocalDate )
}
</pre>
<p>If you have dates in your domain objects and you use scaffolding, you need to change the scaffolding templates so joda time will keep on working. The following command does just that.</p>
<pre>
grails install-joda-time-templates
</pre>
<p>Now let us try to use the startDate and endDate in the SchedulingController to create entries for every week in that period. For that to work we must make a change in the interface of the service. We now use LocalDate from joda time. We also change the input field of the datepicker. We add the attribute formatString. That way joda time can very easily convert the string into a real LocalDate.</p>
<p>The important part in the SchedulingController is converting the strings into dates.</p>
<pre class="brush: groovy; title: ; notranslate">
        def startDateStr = params.startDate
        def endDateStr = params.endDate
        if (startDateStr &amp;amp;amp;&amp;amp;amp; endDateStr) {
            LocalDate startDate = new LocalDate(startDateStr)
            LocalDate endDate = new LocalDate(endDateStr)
            scheduleItemService.createScheduleItems(personName, projectName, nrHours,startDate,endDate)
        } else {
        }
</pre>
<p>The last part is the service that actually calculates the weeks. Before hand I warn you that this code is not optimal yet. You cannot pass the year with the weeks. If someone has a smarter way of doing this, please comment or make a suggestion using mail, github or using other means.</p>
<pre class="brush: groovy; title: ; notranslate">
        def currentDate = startDate
        for (int i=startDate.weekOfWeekyear;i&lt;endDate.weekOfWeekyear;i++) {
            currentDate = currentDate + Period.weeks(1)
            doCreateScheduleItem(person, project, i, numberHours)
        }
</pre>
<h2>Final remarks</h2>
<p>This blog post is reaching it&#8217;s end. Not that I am done, I will write more posts the coming weeks. The final thing I want to show is something weird with the home page. At the moment pages cannot deal with not having navigation configured. Therefore the default homepage is broken. I want to use this to show you how you can change the mapping to the default homepage. I want to show the /home as the default page. To do just that we need to change the mapping. Open the UrlMappings in the conf folder. Look for the mapping of &#8220;/&#8221; and change that line into the following line:</p>
<pre>
      "/"(controller:"home", action:"index")
</pre>
<p>I am still pretty amazed ahout how easy it is to work with grails. What I have done so far took me about 6 hours. In that time I also wrote this blog post. Not bad for someone that does not have a lot of experience with grails. In my next blog posts I will go into the security part, validation, google charts and searchable plugin. Hope you liked it and hope to see you back.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F12%2F20%2Fstarting-with-grails%2F&amp;title=Starting%20with%20grails&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/12/20/starting-with-grails/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Doing grails, yes I like it</title>
		<link>http://www.gridshore.nl/2009/11/09/doing-grails-yes-i-like-it/</link>
		<comments>http://www.gridshore.nl/2009/11/09/doing-grails-yes-i-like-it/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 07:30:54 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[google appengine]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[intellij]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=920</guid>
		<description><![CDATA[<p>Last week I attended a groovy &#038; grails training by SpringSource. My first introduction into grails is about 2 years a go. I attended a talk at the spring experience. Back than I liked it, tried it, but did not really use it. By now a lot has changed, most of all very good [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" alt="F0720E8F-2336-4FEE-BB96-7F8FA9B9FD9C.jpg" border="0" width="134" height="117" align="left" />Last week I attended a <a href="http://www.springsource.com/training/grv001">groovy &#038; grails training</a> by SpringSource. My first introduction into grails is about 2 years a go. I attended a talk at the spring experience. Back than I liked it, tried it, but did not really use it. By now a lot has changed, most of all very good tool integration by <a href="http://www.jetbrains.com/idea/nextversion/">intellij</a>. Last week I had the change to go to a training, now I am motivated to start using grails more often.</p>
<p>This post I will talk you through a grails application I have created for a project of mine. I also take you through some of the things I learned last week. Finally I&#8217;ll show you that you can create a google app engine application using grails. There are ways to create grails applications, I&#8217;ll show you how to do it using the latest intellij 9 beta release.</p>
<p><span id="more-920"></span><br />
<h2>Training</h2>
<p>As mentioned in the introduction I attended the spring source groovy and grails training. The training was given by Peter Ledbrook, author of <a href="http://www.manning.com/gsmith/">grails in action</a>. I am not going to give a detailed description of the training. I did like the training, it gave a good overview of the possibilities of grails as well as the groovy language. And yes, I am now very interested in the options of groovy. Especially for creating web based applications with grails, groovy just shines. Not sure when I should use groovy and when normal java. Have to explore to find out. Some of the things I liked about groovy are:</p>
<ul>
<li>Assignment of parameters that are evaluated immediately ${age} or when used ${->age}</li>
<li>Using negative indexes in arrays: [1 .. -2] strips of the first and last item from an array</li>
<li>Groovy truth, explicit use of values in a comparison. null, 0, &#8220;&#8221; and [] are all false in a comparison</li>
<li>Closures, still hard to determine when to use a closure and when a method. But closures are used very often in groovy.</li>
<li>Out of the box test integration with things like: MockFor, Expando, and as a plugin GMock.</li>
</ul>
<p>Of course we learned a lot more than this, check the training or the book yourself if you want more. Next up was grails. I did look at grails before at grails, but tool support was pretty limited back than, and the plugins were not really widely available. A lot has changed since than. SpringSource came out with grails support in SpringSource Tool Suite, and Intellij has grails support as well. To be honest, intellij was much more productive than STS. Actually STS was almost not useable. Since it was the first release with grails support it will most probably improve the coming releases. Intellij worked very nice out of the box (I did use the beta version of intellij 9. Some of the features I liked during the training are:</p>
<ul>
<li>Gorm, I must mention this Groovy/Grails Object Relational Mapping framework first. This is very important for grails and why it is so productive. I just love these dynamic finders (more later).</li>
<li>Plugin architecture, the easy of installtion and usage of plugins is very nice. I like the db-util plugin for its simplicity and the help when working with internal memory databases. A killer plugin during development.</li>
<li>Scaffolding, for auto responding to CRUD like operations.</li>
<li>flash parameter to be used for adding something to the session for just one request. Ideal for passing messages.</li>
<li>Using templates, ideal for doing ajax calls and reuse of small view elements.</li>
</ul>
<p>Oke time to get our hands dirty, next up is a short introduction in the sample I am going to create. Than some code (which is acutally not that much)</p>
<h2>The application to create</h2>
<p>For a customer at <a href="http://www.jteam.nl">JTeam</a>, we have a large amount of servers that we need to prepare. The actual preparation is mostly done by the hosting provider. Sometime we have no idea what the status is of some servers. We started to use an excel sheet to communicate the status among our team. This is not ideal and I decided to create a small grails application for this. It&#8217;s all very basic, but useable.</p>
<p>Every server has a status, some comments and an external ip address. Each server is also part of a number of vlans and belongs to an environment (dev,test,accep,prod).</p>
<h2>The code</h2>
<p>The code is available online at github. Yes I know, it is not at google code. I got extra motivated to start using git since the training. Peter was working so flexible with his source code, I want that too. The best way to learn something is by doing it. Therefore I create a git repository at github. You can find out more at the following url. There is a very easy way to download the complete source code without using git, check the page.</p>
<p><a href="http://github.com/jettro/MyServerPark">http://github.com/jettro/MyServerPark</a></p>
<h2>The basics</h2>
<p>Starting a grails project is very well documented on the grails website. Except for one controller, the OverviewController, all controllers use: def scaffold = true. Which means I don&#8217;t write any code. Also not view components. I did create some domain classes that have relationships with each other. The next sections cover the different elements of the application.</p>
<h3>The domain model</h3>
<p><img src="http://www.gridshore.nl/wp-content/uploads/DomainModelServerpark.png" alt="DomainModelServerpark.png" border="0" width="555" height="376" align=" center" /></p>
<p>Some things to know about the domain model:</p>
<ul>
<li>belongsTo is used to declare a relationship of many-to-one, the next line gives an example for Comment. This gives the comment a property server.</li>
<p>static belongsTo = [server:Server]</p>
<li>The comment class also gives meta data about the mapping and the type used for the database as well as constraints. In the example we create a field for larger amounts of text.</li>
<pre class="brush: groovy; title: ; notranslate">
class Comment {
    String name
    String content

    static belongsTo = [server:Server]

    static mapping = {
        content type: &quot;text&quot;
    }

    static constraints = {
        name(blank:false, maxSize:50)
        content(blank:false, widget:&quot;textarea&quot;)
    }
}
</pre>
<li>The previous code block also shows one of the things that might be a bit strange. With <strong>widget:&#8221;textarea&#8221;</strong> you indicate the type of field to be used at the front end. Might be a bit strange in a domain model.</li>
<li>A one-to-many relationship is also easy to implement, check the following line from Environment:</li>
<p>static hasMany = [servers:Server]
</ul>
<p>Check the code for more examples of relationships.</p>
<h3>Scaffolding controllers and views</h3>
<p>Grails makes use of scaffolding, this can be static and dynamic. In the static case, code is being generated and can be altered. The dynamic case is evaluated runtime. In this project I tried to use dynamic scaffolding as much as possible. Usability might not always be what you want. In that case you should use static scaffolding or create something yourself. I managed to do well with the scaffolding on dynamic (except for the google app engine sample). But let us focus on the customer controller.</p>
<h2>The overview controller</h2>
<p>Grails makes use of convention over configuration. This is also true for controllers and views. The overview controller listens to the /overview url and points to the overview.gsp file. The following code block gives the complete OverviewController groovy class.</p>
<pre class="brush: groovy; title: ; notranslate">
class OverviewController {
    def show = {
        redirect(uri:&quot;/server/show/${params.id}&quot;)
    }

    def comments = {
        def currentServer = Server.findById(params.id.toLong())
        def allComments = Comment.withCriteria {
            server {
                eq(&quot;id&quot;,currentServer.id)
            }
        }
        render(template:&quot;/shared/comment&quot;,model:[comments:allComments, server:currentServer])
    }

    def index = {
        def environments = Environment.list()
        [environments:environments]
    }
}
</pre>
<p>There are three methods in the controller. The show does a redirect to the show method of the server controller. The index returns list of all environments and uses the view index.gsp. The comments method is a different cup of thee. This responds to an ajax call and returns a fragment. focus on the last line for now. You can see we use the render call. This makes use of a template. Using the render call, we obtain the html and push it back to the client. The section about views will give a bit more detail. Next up are the dynamic finders</p>
<h3>Dynamic finders</h3>
<p>The previous code block gives a few examples of finders. In index we obtain all the environments with <strong>Environment.list()</strong>. This is the most basic finder. Another finder is in the comments method. There we obtain the server by an id. The call is findServerById and you provided an id. Another calls could be: findByFunction, findByFunctionLike &#8220;%database%&#8221;, findByFunctionIlike &#8220;%DataBase%&#8221;. You can also make combinations with And/Or and multiple parameters. Pretty cool.</p>
<p>The comments method also shows the Criteria API for looking up all comments for a specific server. These type of queries, limited by a related item, are not supported by the dynamic finders.</p>
<h3>Gsp for views</h3>
<p>Creating the views is not very hard. If you want to learn how it works, I suggest generating the scaffolding views. I want to focus on something that is just a little bit more advanced. Ajax calls. In my project I want to obtain all comments for a server using an ajax call. In the overview page we use a special tag from grails, the remoteLink. This tag does an ajax call to the server and prints the result in the div with provided id.</p>
<p>&lt;g:remoteLink action=&#8221;comments&#8221; params=&#8221;[id:server.id]&#8221; update=&#8221;comments&#8221;&gt;comments&lt;/g:remoteLink&gt;</p>
<p>As you can see, we provide the <strong>server.id</strong> and we update the div with id <strong>comments</strong>.</p>
<p>This does not work out of the box, you must specify the prototype javascript library to be included. You can do this in the file:</p>
<p>views > layouts > main.gsp</p>
<p>Add the following line:</p>
<p>&lt;g:javascript library=&#8221;prototype&#8221; /&gt;</p>
<p>Now everything should be fine and you can test the application. A command like grails run-app should be enough.</p>
<h2>Documentation</h2>
<p>If you want more information about grails, try the following references:</p>
<ul>
<li><a href="http://grails.org/doc/1.1.x/">http://grails.org/doc/1.1.x/</a></li>
<li><a href="http://groovy.codehaus.org/groovy-jdk/">http://groovy.codehaus.org/groovy-jdk/</a></li>
<li><a href="http://www.manning.com/gsmith/">http://www.manning.com/gsmith/</a></li>
<li><a href="http://www.jetbrains.com/idea/nextversion/index.html">http://www.jetbrains.com/idea/nextversion/index.html</a></li>
<li><a href="http://www.springsource.com/training/grv001">http://www.springsource.com/training/grv001</a></li>
<li><a href="http://www.springsource.com/products/sts">http://www.springsource.com/products/sts</a></li>
</ul>
<h2>Grails and google app engine</h2>
<p>Grails uses plugins for all additional functionality. There is also a plugins available for google app engine. There is already good documentation available for this plugin. Therefore I keep this short. The following code block shows the commands. For more information, check the website of the plugin:</p>
<p><a href="http://grails.org/plugin/app-engine">http://grails.org/plugin/app-engine</a><br />
<br/></p>
<pre>
# grails create-app share-this
# grails uninstall-plugin hibernate
# grails install-plugin app-engine
choose jpa when asked
# export APPENGINE_HOME=&lt;path to your sdk install of google app engine&gt;
# grails app-engine run
# grails set-version 1
# grails app-engine package
# $APPENGINE_HOME/bin/appcfg.sh update ./target/war
# grails install-plugin gorm-jpa
</pre>
<p>Than I used intellij to create some domain classes and controllers. Take the following into consideration.</p>
<ul>
<li>Put domain classes in a package or it won&#8217;t work</li>
<li>Put Controller classes in the same package</li>
<li>generate views, the auto scaffolding seems not to work.</li>
</ul>
<p>You can look at the result here : <a href="http://share-this.appspot.com/">http://share-this.appspot.com/</a>. It could well be that the app does not start the first time, a refresh might help. I&#8217;ll have a look at this in the future. There is a problem with the CPU consumption and my grails application.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F11%2F09%2Fdoing-grails-yes-i-like-it%2F&amp;title=Doing%20grails%2C%20yes%20I%20like%20it&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/11/09/doing-grails-yes-i-like-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

