<?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>Steademy Blog &#187; command pattern</title>
	<atom:link href="http://blog.steademy.com/tag/command-pattern/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.steademy.com</link>
	<description>Steademy - steademy for every message</description>
	<lastBuildDate>Mon, 25 Jan 2010 22:19:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Grails command validation</title>
		<link>http://blog.steademy.com/2009/04/13/grails-command-validation/</link>
		<comments>http://blog.steademy.com/2009/04/13/grails-command-validation/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 19:33:13 +0000</pubDate>
		<dc:creator>tmaus</dc:creator>
				<category><![CDATA[Groovy & Grails]]></category>
		<category><![CDATA[command pattern]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[validator]]></category>

		<guid isPermaLink="false">http://blog.steademy.com/?p=111</guid>
		<description><![CDATA[I have setup a small example that demonstrates how to use grails validation on non domain objects using the command pattern. Collecting all required information was not that easy. Forums do not yet cover many G&#038;G related topics, at least if you want to look under the hood of it In general, my blogs target [...]]]></description>
			<content:encoded><![CDATA[<p>I have setup a small example that demonstrates how to use grails validation on non domain objects using the command pattern.<br />
Collecting all required information was not that easy. Forums do not yet cover many G&#038;G related topics, at least if you want to look under the hood of it </p>
<p>In general, my blogs target G&#038;G developers. You should have at least an idea of how to use it, how to setup a project and what a controller is. My code is tested against Grails 1.1</p>
<h3>Short summary</h2>
<p>We are going to setup a simple controller with two closures. The one we use is responsible for logging a user into any platform.<br />
Our controller uses a command to gather  all params and to validate its values. </p>
<h2>The controller</h2>
<p>First thing you should create is the controller.<br />
grails create-controller my<br />
You might now copy and paste the following code into your controller class. </p>
<pre>
<p style="border: 1px solid black; overflow: auto; width: 100%; height: 180px">
<b>grails-app/controllers/MyController.groovy</b>

class MyController {

    def index = { }

    def  run = {
    		MyCommand cmd ->

    		if(cmd.hasErrors()){
    			render(view:"error")
    		}else{
    			render(view:"ok")
    		}
    }
}

class MyCommand {
	String login
	String passwd1
	String passwd2

	static constraints = {
		login(blank:false, size:5..15, validator: {
			it=="foobar"
		})
		passwd1(blank:false, validator: { val, obj ->
			obj.properties['passwd2']==val
		})
	}
}

</pre>
<p>The important closure for the upcoming test is called &#8220;run&#8221;.<br />
As an argument it takes a command object.<br />
The springframework behind the scenes is taking care, that all request params are properly mapped to the command object (MyCommand).<br />
Furthermore the command object&#8217;s constraints are executed prior any other line of code in the &#8220;run&#8221; closure.<br />
A powerful feature if you ask me :O)</p>
<p>The command class itself is in charge of all the validation work. As outlined in the grails docs (very good ones indeed) all domain oriented constraints<br />
can be applied to non domain validation objects as well. </p>
<p>The contraint:</p>
<pre>
<p style="border: 1px solid black; overflow: auto; width: 100%; height: 50px">
login(blank:false, size:5..15, validator: {
	it=="foobar"
})

</pre>
<p>for example adds an error if the param login is null, if its length is smaller 5 chars or greate 15, or if the validator is returning anything else than null.<br />
Adding an error ?<br />
Grails is making extensive use of  spring&#8217;s error handling. Have a look at their excellent docs.<br />
For each error, an error object is added to the command object. The controller checks for errors in the command validation and can redirect back to the form if needed. </p>
<h2>The test class</h2>
<pre>
<p style="border: 1px solid black; overflow: auto; width: 100%; height: 180px">
<b>test/integration/MyControllerTests.groovy</b>

import grails.test.*

class MyControllerTests extends ControllerUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testValidCommand() {
    	def cmd = new MyCommand(login:"foobar", passwd1:"password", passwd2:"password")
    	def cntr = new MyController()
    	cntr.run(cmd)
    	assert "ok" == cntr.modelAndView.view
    }

    void testInvalidCommand() {
    	def cmd = new MyCommand(login:"foobar", passwd1:"password", passwd2:"not-equals")
    	def cntr = new MyController()
    	cntr.run(cmd)
    	//println cmd.errors.allErrors
    	println "field error " + cmd.errors.fieldError
    	assert 'passwd1' == cmd.errors.getFieldError('passwd1').field
    	assert 'validator.invalid' == cmd.errors.getFieldError('passwd1').code
    }
}

</pre>
<p> The test itself is simple. You have to create a command object that you use as the request object when calling the &#8220;run&#8221; closure within the controller.<br />
The way I evaluate an error is ok, but not as good as I wanted it to be.<br />
Grails ships with an enhanced way to handle message codes. Instead of letting the developer create a message key for each error,  Grails makes strong usage of their convention over configuration approach by automatically assigning errors to dedicated message keys.<br />
The error key for the login:blank constraint would be mapped in  <b>grails-app/i18n/messages.properties</b>  as:<i>myCommand.login.blank</i>.<br />
Again the time consuming job of assigning messages keys to errors is omitted. </p>
<p>What I was not yet able to achieve is to fetch the associated error key for a given constraint within a test case.<br />
So, what I am looking for is a line like:</p>
<pre>
assert 'myCommand.login.blank' == cmd.errors.getField('login').???
</pre>
<p>Well, I hope that this blog helped you a bit. Yo may leave a comment or try to reach my directly using the steademy plugin and invite me (tmaus@steademy.com) from within the firefox plugin. </p>
<p>Have a nice day</p>
<p>Thorsten </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.steademy.com/2009/04/13/grails-command-validation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
