<?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>Sword Systems &#187; grails</title>
	<atom:link href="http://swordsystems.com/tag/grails/feed/" rel="self" type="application/rss+xml" />
	<link>http://swordsystems.com</link>
	<description>Cutting Commentary</description>
	<lastBuildDate>Tue, 10 Jan 2012 02:02:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Spring security: CAS + LDAP</title>
		<link>http://swordsystems.com/2011/12/21/spring-security-cas-ldap/</link>
		<comments>http://swordsystems.com/2011/12/21/spring-security-cas-ldap/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 01:44:19 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[Single Sign On]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[SSO]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[cas]]></category>
		<category><![CDATA[ldap]]></category>
		<category><![CDATA[spring-security]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=209</guid>
		<description><![CDATA[After getting straight LDAP authentication to work with the spring-security-ldap plugin, I moved on to the next requirement which was integrating with CAS. Like many projects before us, we need to do authentication through CAS and then follow up authorization (i.e. role checking) through LDAP. The authentication part was easy thanks to the spring-security-cas plugin. [...]]]></description>
			<content:encoded><![CDATA[<p>After getting straight LDAP authentication to work with the <a href="http://www.grails.org/plugin/spring-security-ldap" title="More Parallel Processing in Jenkins Notes" target="_blank">spring-security-ldap</a> plugin, I moved on to the next requirement which was integrating with CAS.  Like many projects before us, we need to do authentication through CAS and then follow up authorization (i.e. role checking) through LDAP.  The authentication part was easy thanks to the <a href="http://www.grails.org/plugin/spring-security-cas" target="_blank">spring-security-cas</a> plugin.  However, there are two mildly annoying issues with the plugin as a whole:</p>
<p>First, once it is installed, you can&#8217;t turn it off (at least, not in development mode).  The value of the <code>cas.active</code> setting is ignored unless you deploy as a war.  There is already a <a href="http://jira.grails.org/browse/GPSPRINGSECURITYCAS-15" target="_blank">bug</a> filed for this and someone has submitted a simple patch.  You can either build the patched plugin, or just tweak the few lines directly in your project&#8217;s copy of the plugin.</p>
<p>The second issue relates to auto-creating user accounts.  I <a href="http://swordsystems.com/2011/12/12/auto-create-user-domain-object-with-spring-security/" title="Auto-create User Domain Object with Spring Security" target="_blank">posted</a> about using an AuthenticationEvent listener to do this last week.  Unfortunately, this will not work with the default configuration of the CAS plugin.  The plugin does not override the <code>userDetailsService</code> so you get the default <code>GormUserDetailsService</code>.  That class will throw a &#8220;user not found&#8221; exception if there is no local user domain object for the given user name.  If you have no need for role information (<code>authorities</code> in spring-security speak), then you can simply plug in a simplistic userDetailsService like this one:</p>
<pre class="brush: groovy; title: ; notranslate">
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.User
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.security.core.authority.GrantedAuthorityImpl

/**
 * Dumb service which just returns a UserDetails object with the username set.
 * @author esword
 */
class EmptyUserDetailsService implements GrailsUserDetailsService {

    /**
     * Taken from GormUserDetailsService: Some Spring Security classes expect at least one
     * role, so we give a user with no granted roles this one which gets past that restriction
     * but doesn't grant anything.
     */
    static final List NO_ROLES = [new GrantedAuthorityImpl(SpringSecurityUtils.NO_ROLE)]

    UserDetails loadUserByUsername(String username, boolean loadRoles) {
        return loadUserByUsername(username)
    }

    UserDetails loadUserByUsername(String username) {
        new User(username, '', true, true, true, true, NO_ROLES)
    }
}
</pre>
<p>You could extend <a href="http://static.springsource.org/spring-security/site/docs/3.1.x/apidocs/org/springframework/security/provisioning/InMemoryUserDetailsManager.html" target="_blank">InMemoryUserDetailsManager</a> if you didn&#8217;t want to re-create the <code>UserDetails</code> all the time, or wrap a <code>GormUserDetailsService</code> to first check if you have a local account and return info from that if so.  I just threw together this class so that I could verify that the rest of the authentication process with CAS worked.</p>
<h2>LDAP Integration</h2>
<p>If you do need role information from LDAP, you will need to add a few more beans to your <code>resources.groovy</code> file.  Someone <a href="http://grails.1312388.n4.nabble.com/Spring-Security-CAS-authentication-LDAP-Roles-combo-td2955194.html">posted a thread</a> on the grails-dev mailing list about a year ago with the core information for this configuration.  However, the example they give hard-codes the LDAP connection settings in the bean definitions themselves.  Since our app is deployed with the LDAP plugin (it is turned off if CAS is turned on), I wanted to use the same property settings so that we could easily toggle back and forth between plain LDAP and CAS.  Here is the revised bean configuration within <code>resources.groovy</code>:</p>
<pre class="brush: groovy; title: ; notranslate">
    // If CAS is active and if ldap is configured, do UserDetails lookup from ldap to get the roles.
    // All of these setting names and how they are used come from reading the SpringSecurityLdapGrailsPlugin.groovy
    if (application.config.grails.plugins.springsecurity.cas.active) {
        def config = SpringSecurityUtils.securityConfig
        if (config.ldap.context.server) {
            SpringSecurityUtils.loadSecondaryConfig 'DefaultLdapSecurityConfig'
            config = SpringSecurityUtils.securityConfig

            initialDirContextFactory(org.springframework.security.ldap.DefaultSpringSecurityContextSource,
               config.ldap.context.server){
                userDn = config.ldap.context.managerDn
                password = config.ldap.context.managerPassword
            }

            ldapUserSearch(org.springframework.security.ldap.search.FilterBasedLdapUserSearch,
               config.ldap.search.base,
               config.ldap.search.filter,
                initialDirContextFactory){
            }

            ldapAuthoritiesPopulator(org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator,
                initialDirContextFactory,
               config.ldap.authorities.groupSearchBase){
                  groupRoleAttribute = config.ldap.authorities.groupRoleAttribute
                  groupSearchFilter = config.ldap.authorities.groupSearchFilter
                  searchSubtree = config.ldap.authorities.searchSubtree
                  rolePrefix = &quot;ROLE_&quot;
                  convertToUpperCase = config.ldap.mapper.convertToUpperCase
                  ignorePartialResultException = config.ldap.authorities.ignorePartialResultException
            }

            userDetailsService(org.springframework.security.ldap.userdetails.LdapUserDetailsService,
                ldapUserSearch,
                ldapAuthoritiesPopulator){
            }
        }
        else {
            //Dummy service if LDAP isn't set up
            userDetailsService(EmptyUserDetailsService)
        }
    }
</pre>
<p>Ideally, I would like to be able to keep the LDAP plugin turned on in an &#8220;authorization only&#8221; mode so that I could use the <code>userDetailsService</code> configuration directly from it.  That is not yet possible with the plugin, so this is the next best thing.  You still avoid having to write any new code in your application and at least get the benefit of being able to fall back on the default property settings for the LDAP plugin.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/12/21/spring-security-cas-ldap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Auto-create User Domain Object with Spring Security</title>
		<link>http://swordsystems.com/2011/12/12/auto-create-user-domain-object-with-spring-security/</link>
		<comments>http://swordsystems.com/2011/12/12/auto-create-user-domain-object-with-spring-security/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 16:13:21 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[Single Sign On]]></category>
		<category><![CDATA[SSO]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[ldap]]></category>
		<category><![CDATA[spring-security]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=194</guid>
		<description><![CDATA[For those who skip straight to the last page of a book to see how it ends &#8211; See Chap 7. Events of the spring-security-core plugin documentation. For those who like a little more detail&#8230; I just moved our grails app from using the shiro plugin to using the spring-security plugin(s). I like shiro&#8217;s filter-based [...]]]></description>
			<content:encoded><![CDATA[<p>For those who skip straight to the last page of a book to see how it ends &#8211; See <a href="http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/7%20Events.html" target="_blank">Chap 7. Events</a> of the spring-security-core plugin documentation.</p>
<p>For those who like a little more detail&#8230;</p>
<p>I just moved our grails app from using the <a href="http://www.grails.org/plugin/shiro" target="_blank">shiro</a> plugin to using the <a href="http://www.grails.org/plugin/spring-security-core" target="_blank">spring-security</a> plugin(s).  I like shiro&#8217;s filter-based config, but all the pre-built extension modules that <a href="http://burtbeckwith.com/blog/" target="_blank">Burt Beckwith</a> has put together for spring-security (<a href="http://www.grails.org/plugin/spring-security-ldap" title="spring-security-ldap" target="_blank">LDAP</a>, <a href="http://www.grails.org/plugin/spring-security-cas" title="Grails CAS plugin" target="_blank">CAS</a>, etc.) makes it much easier for us to support the range of environments in which we have to deploy.</p>
<p>The one feature which took me a little while to figure out was how to have our app auto-create a user domain object when it is using an external authentication source.  For example, say an instance of our app is configured to authentication against an LDAP server.  The app has a <code>MyUser</code> class that holds local settings for users like preferences, documents, etc.  When a user signs in for the first time and makes it past the authentication step, we need to automatically create a <code>MyUser</code> instance and associate it with the LDAP username.  With the shiro-based authentication, we did this in the controller method which handled the authentication itself.  Spring security works a little differently and there isn&#8217;t a central, post-authentication landing point.  </p>
<p>If your app is always deployed with the same type of authentication (e.g. always with LDAP), you could put the persistence code into a custom <code>UserDetailsService</code>.  There are several posts on the web that discuss creating a custom <code>UserDetails</code> object and a corresponding service for it, so this was the first approach I looked at.  <a href="http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/11%20Custom%20UserDetailsService.html" target="_blank">Chapter 11</a> of the spring-security-core plugin&#8217;s user guide has info on it as well.  The primary shortcoming is that you can&#8217;t chain together <code>UserDetailsService</code>s.  You have to implement one for each form of authentication with which you want to work. </p>
<p>If your app must work with a variety of authentication methods, it is easier to register a listener with Spring Security.  <a href="http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/7%20Events.html" target="_blank">Chapter 7</a> of the plugin guide discusses the two ways to do this.  I found that handling the <code>AuthenticationSuccessEvent</code> was all I needed.  Since we already had a Grail&#8217;s service that handles various user-related tasks, the listener object was dirt simple:</p>
<pre class="brush: groovy; title: ; notranslate">
import org.springframework.beans.factory.InitializingBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.AuthenticationSuccessEvent

class MyAuthenticationEventListener implements ApplicationListener&lt;AuthenticationSuccessEvent&gt;, InitializingBean, ApplicationContextAware {
    ApplicationContext applicationContext
    def userService

    void afterPropertiesSet() {
        userService = applicationContext.getBean('userService')
    }

    void onApplicationEvent(AuthenticationSuccessEvent e) {
        //the principal field of the source object is a UserDetails object of some form.
        //The spring-security API contract guarantees that at least the username field will be populated.
        userService.createUser(e.source.principal)
    }
}
</pre>
<p>Since the whole class really just has one line of &#8220;functional&#8221; code, I could have used the closure-based approach described in section 7.3 of the user guide.  I just prefer to keep true code out of the <code>Config.groovy</code> file.</p>
<p>Then, within the <code>UserService.createUser</code> method, the key lines look something like this:</p>
<pre class="brush: groovy; title: ; notranslate">
    def user = MyUser.findByUsername(userDetails.username)
    if (!user)
    {
        MyUser.withTransaction {status -&gt;
            user = new MyUser(username:userDetails.username /*, set any other props you want to store locally*/)
            user.save(flush: true, failOnError:true)
        }
    }
    return user
</pre>
<p>One note of interest &#8211; without the <code>withTransaction</code> statement, you may get an exception stating that no hibernate session exists and one cannot be opened.  The <code>withTransaction</code> closure wraps this up nicely for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/12/12/auto-create-user-domain-object-with-spring-security/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Running latest Groovy from Maven</title>
		<link>http://swordsystems.com/2011/04/05/running-latest-groovy-from-maven/</link>
		<comments>http://swordsystems.com/2011/04/05/running-latest-groovy-from-maven/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 15:10:15 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[groovy plugin]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=126</guid>
		<description><![CDATA[Say you have a groovy-project that you build with maven.  You use the org.codehaus.gmaven:gmaven-plugin to compile your groovy code and run groovy tests without a problem.  Then you add some features or tests that need groovy 1.7.  You add the proper dependency and version to the &#60;dependencies&#62; section of your pom, run your test&#8230; and [...]]]></description>
			<content:encoded><![CDATA[<p>Say you have a groovy-project that you build with maven.  You use the org.codehaus.gmaven:gmaven-plugin to compile your groovy code and run groovy tests without a problem.  Then you add some features or tests that need groovy 1.7.  You add the proper dependency and version to the &lt;dependencies&gt; section of your pom, run your test&#8230; and watch it blow up because the gmaven-plugin defaults to using groovy 1.6.  So you dig around on the web and find references for how to use the &lt;providerSelection&gt; tag of the gmaven-plugin to get your code compiled with 1.7 and to use 1.7 when running tests.  Things seem good.  Until&#8230;</p>
<p>You add a feature that requires some version of groovy greater than 1.7.4 (the version included with the latest gmaven-plugin, 1.3).  In my case, I used the @Delegate annotation with some inheritance in a test configuration and hit a bug that was fixed in groovy 1.7.6.  No matter what version I used in my dependencies section, my tests were executed under groovy 1.7.4.  I finally came up with the configuration below which let me run with a different groovy.  Note that it made no difference what I included in the dependencies section.  The gmaven-plugin configuration appears to be completely independent of that.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;plugin&gt;
    &lt;groupId&gt;org.codehaus.gmaven&lt;/groupId&gt;
    &lt;artifactId&gt;gmaven-plugin&lt;/artifactId&gt;
    &lt;version&gt;1.3&lt;/version&gt;
    &lt;configuration&gt;
        &lt;providerSelection&gt;1.7&lt;/providerSelection&gt;
        &lt;!-- This is only used if you want to run a groovy script from the command line using maven --&gt;
        &lt;source&gt;${groovy.script}&lt;/source&gt;
    &lt;/configuration&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;goals&gt;
                &lt;goal&gt;compile&lt;/goal&gt;
                &lt;goal&gt;testCompile&lt;/goal&gt;
            &lt;/goals&gt;
        &lt;/execution&gt;
    &lt;/executions&gt;
    &lt;!-- This block is required in order to make the gmaven plugins use a groovy other than 1.7.4.
     This is independent of the groovy entry in the dependencies section.  This does not affect the class path.

     What is interesting is that there must be both the gmaven.runtime entry with the explicit excludes
     and the additional dependency on whatever version we do want to use.  If you exclude the former,
     it will throw an exception. --&gt;
    &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.3&lt;/version&gt;
            &lt;exclusions&gt;
                 &lt;exclusion&gt;
                     &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
                     &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
                 &lt;/exclusion&gt;
            &lt;/exclusions&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.6&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/plugin&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/04/05/running-latest-groovy-from-maven/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Validation differences between Grails 1.1 and 1.2</title>
		<link>http://swordsystems.com/2010/06/09/validation-differences-between-grails-1-1-and-1-2/</link>
		<comments>http://swordsystems.com/2010/06/09/validation-differences-between-grails-1-1-and-1-2/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 18:34:44 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[frustration]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=65</guid>
		<description><![CDATA[&#8230;or My Penance For Ignoring Validation Errors&#8230; We recently updated our app from Grails 1.1.1 to 1.2.2. (We wanted to move all the way to 1.3.1 but since we build with maven, we finally decided to wait until a new grails-maven plugin is released. See GRAILS-6327.) During the upgrade, we hit two particularly annoying issues [...]]]></description>
			<content:encoded><![CDATA[<h2>&#8230;or My Penance For Ignoring Validation Errors&#8230;</h2>
<p>We recently updated our app from Grails 1.1.1 to 1.2.2.  (We wanted to move all the way to 1.3.1 but since we build with maven, we finally decided to wait until a new grails-maven plugin is released.  See <a href="http://jira.codehaus.org/browse/GRAILS-6327">GRAILS-6327</a>.)  During the upgrade, we hit two particularly annoying issues related to persistence and setting up associations.  </p>
<p>The first involved a <code>belongsTo</code> relation like this:</p>
<pre class="brush: groovy; title: ; notranslate">class AppUser {
    UserPrefs prefs = new UserPrefs()
}

class UserPrefs {
    static belongsTo = [user: AppUser]
}
</pre>
<p>This worked under Grails 1.1, but under Grails 1.2 the prefs object was not getting persisted when the user was saved.  Other <code>belongsTo</code> relations, both one-to-many and one-to-one worked as expected.  We finally discovered that using the short form of the relation notation did work:</p>
<pre class="brush: groovy; title: ; notranslate">static belongsTo = AppUser
</pre>
<p>This <a href="http://groovyguts.wordpress.com/2009/10/15/why-belongsto-is-important-for-validation/">post</a> provided a clue as to where the problem may be.  The <code>user</code> property of the Prefs object is not automatically set because the relationship is one-to-one.  (At least, it is not automatically set all the time.  If we load an AppUser object with Hibernate, it appears that the user property is set in the UserPrefs object.  Go figure.)  Under Grails 1.1, having a null user was apparently fine.  My guess (based on the second error we hit, below) is that any validation errors caused by the child object were not stopping the save of the parent object.  Grails 1.2, on the other hand, does care about the child object validation, though I could never get it to report anything in the <code>errors</code> property of either the parent or child object.  </p>
<p>In order to work around the issue, I loosened the constraints on <code>UserPrefs</code> a little:</p>
<pre class="brush: groovy; title: ; notranslate">class UserPrefs {
    static constraints = {
        user(nullable: true)
    }
    static belongsTo = [user: AppUser]
}
</pre>
<p>With this change, cascading persistence works.  Given, it&#8217;s not an ideal solution, but it does let us have access to the <code>user</code> property if needed.</p>
<p>What made this extra confusing is that we have a similar relationship in another set of classes that worked without a problem.  The only difference there is that the child class is not automatically created with a static initializer as is done in for the <code>prefs</code> property in <code>AppUser</code>.  It is always explicitly set into the owning object.  I&#8217;ve run out of time to pursue this one further, so I don&#8217;t have a final answer.  Anyone else out there have more insight into this?</p>
<p>The second persistence issue related to this section of code in the update method of one of our controllers:</p>
<pre class="brush: groovy; title: ; notranslate">def update = {
    def hubMap = HubMap.get(params.id);
    hubMap.properties = params;
    if (hubMap.save()) {
        ...add success message to response...
    } else {
        ...add failure message to response...
    }
    ...
}
</pre>
<p>Again, the code worked fine under Grails 1.1.1, but the save call failed under 1.2.2.  Unfortunately, there was a hole in both our unit and integration tests for this method, so we didn&#8217;t catch it until much later in the release cycle.</p>
<p>Was the JSON conversion in the controller&#8217;s <code>get</code> method that generated the original data for the browser different?   Nope.<br />
Had the behaviour of the <code>properties</code> meta-method changed?  Nope.</p>
<p>The difference is in how Grails handles any existing validation errors on a domain object when you call <code>save()</code>.  In our case, the JSON that was being sent to the controller (via a Prototype AJAX call) contained two properties that were references to other objects.  The javascript object conversion in the browser was not setting these properties in a meaningful way for the AJAX call; they were both coming across with the string value <code>[object Object]</code>.  Since these fields are never updated in this particular workflow, we had never checked what was happening to them.  Grails obviously could not convert from the string values to the proper objects, it ignored the values and set two errors on the domain object to record them.  However, we didn&#8217;t check for errors after the <code>properties</code> call.  We went straight to the <code>save</code> call. Under Grails 1.1, deep within the saving sequence in a random class called <code>AbstractDynamicPersistentMethod</code>, you come across this bit of code:</p>
<pre class="brush: groovy; title: ; notranslate">doInvokeInternal(...) {
    ...
    Errors errors = new BeanPropertyBindingResult(target, target.getClass().getName());
    mc.setProperty(target, ERRORS_PROPERTY, errors);
    ...
}
</pre>
<p>Any existing errors are replaced with a fresh, clean <code>BeanPropertyBindingResult</code> object, wiping out the error information.  We never spotted it because we never expected the properties with errors to change anyway.  That hole has been closed in Grails 1.2:</p>
<pre class="brush: groovy; title: ; notranslate">doInvokeInternal(...) {
    ...
    Errors errors = setupErrorsProperty(target);
    ...
}
</pre>
<p>The new <code>setupErrorsProperty</code> call will copy out existing errors.  We put in a few adjustments to not attempt to update those properties and all is well.</p>
<p>So there you have it.  A couple of gotchas in the upgrade path for grails.  Hope this saves some folks from banging their head against the wall.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2010/06/09/validation-differences-between-grails-1-1-and-1-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails, Maven, packaging, and skipTests fun</title>
		<link>http://swordsystems.com/2010/04/22/grails-maven-packaging-and-skiptests-fun/</link>
		<comments>http://swordsystems.com/2010/04/22/grails-maven-packaging-and-skiptests-fun/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 16:25:55 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[frustration]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=62</guid>
		<description><![CDATA[The grails maven plugin honors the maven.test.skip option (which turns off compiling and executing tests), but not the skipTests option (which only turns off executing tests). This means that you cannot easily create a package with test classes in it without running all of the tests. I finally come up with a close work around: [...]]]></description>
			<content:encoded><![CDATA[<p>The grails maven plugin honors the <code>maven.test.skip</code> option (which turns off compiling and executing tests), but not the <code>skipTests</code> option (which only turns off executing tests).  This means that you cannot easily create a package with test classes in it without running all of the tests.  I finally come up with a close work around:<br />
<code><br />
mvn clean grails:exec install -Dcommand=test-app -Dargs="-unit DoesNotExist" -Dmaven.test.skip=true<br />
</code><br />
By explicitly listing the <code>test-app</code> command but specifying a test that does not exist, I was able to get the unit tests to be compiled.  Since I only needed some common testing files in my package, this works for me.  If someone wanted to package both the unit and integration tests, I don&#8217;t think this would work.  I filed a new issue in the <a href="http://jira.codehaus.org/browse/GRAILS-6188">Grails Jira</a> to try to get a real resolution.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2010/04/22/grails-maven-packaging-and-skiptests-fun/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails+Maven+GeoTools+PdfBox = PITA</title>
		<link>http://swordsystems.com/2010/03/20/grailsmavengeotoolspdfbox-pita/</link>
		<comments>http://swordsystems.com/2010/03/20/grailsmavengeotoolspdfbox-pita/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 20:35:27 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[frustration]]></category>
		<category><![CDATA[GIS]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[geotools]]></category>
		<category><![CDATA[pdfbox]]></category>
		<category><![CDATA[xml-api]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=54</guid>
		<description><![CDATA[Overcoming link errors related to XML libraries when using GeoTools and PdfBox]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a bit of maven-voodoo for you.  If you have a Grails (1.1.1) app that is built with Maven (2.1) and you try to link in GeoTools (specifically the gt-xsd-core module) and you try to bring in PdfBox as well, you will get really fascinating class loading and linking problems revolving around various XML pieces.  I finally found two different ways to get rid of the errors.  For those who like to cut to the chase, I&#8217;ll list the solutions first and then explain a bit more what errors I was seeing.</p>
<h3>Solution #1: Exclude, exclude, exclude</h3>
<p>If you don&#8217;t need commons-jxpath, you can add these three exclusions to the gt-xsd-core dependency declaration.</p>
<pre>    &lt;dependency&gt;
        &lt;groupId&gt;org.geotools.xsd&lt;/groupId&gt;
        &lt;artifactId&gt;gt-xsd-core&lt;/artifactId&gt;
        &lt;version&gt;${gt.version}&lt;/version&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;commons-jxpath&lt;/groupId&gt;
                &lt;artifactId&gt;commons-jxpath&lt;/artifactId&gt;
            &lt;/exclusion&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;xml-apis&lt;/groupId&gt;
                &lt;artifactId&gt;xml-apis&lt;/artifactId&gt;
            &lt;/exclusion&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;xml-apis&lt;/groupId&gt;
                &lt;artifactId&gt;xml-apis-xerces&lt;/artifactId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;</pre>
<p>This at least works for me given the subset of geotools functionality I am using (primarily encoding and parsing OGC Filter objects to and from XML so I can persist them with Hibernate).  It is still pulling in xercesImpl and that appears to be enough, at least to get my unit and integration tests working.</p>
<h3>Solution #2: Using Dependency Management</h3>
<p>If you need the commons-jxpath functionality in gt-xsd-core, add this to your dependencyManagement section of your POM:</p>
<pre>    &lt;dependencyManagement&gt;
        &lt;dependencies&gt;
            &lt;!-- The gt-xsd-core tries to bring commons-jxpath 1.2 in.  That messes up the maven junitreport plugin for
            some reason (like links to a version of xalan or xml-apis or something.  The 1.3 version doesn't have that
            issue. --&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;commons-jxpath&lt;/groupId&gt;
                &lt;artifactId&gt;commons-jxpath&lt;/artifactId&gt;
                &lt;version&gt;1.3&lt;/version&gt;
            &lt;/dependency&gt;
        &lt;/dependencies&gt;
    &lt;/dependencyManagement&gt;</pre>
<p>and then keep the exclusions for the xml-api artifacts as above:</p>
<pre>    &lt;dependency&gt;
        &lt;groupId&gt;org.geotools.xsd&lt;/groupId&gt;
        &lt;artifactId&gt;gt-xsd-core&lt;/artifactId&gt;
        &lt;version&gt;${gt.version}&lt;/version&gt;
        &lt;exclusions&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;xml-apis&lt;/groupId&gt;
                &lt;artifactId&gt;xml-apis&lt;/artifactId&gt;
            &lt;/exclusion&gt;
            &lt;exclusion&gt;
                &lt;groupId&gt;xml-apis&lt;/groupId&gt;
                &lt;artifactId&gt;xml-apis-xerces&lt;/artifactId&gt;
            &lt;/exclusion&gt;
        &lt;/exclusions&gt;
    &lt;/dependency&gt;</pre>
<p>This is what I have setup in my POM right now because I think I might need jxpath soon.  I also tried adding a node in dependency management to use the 1.3.03 version of xml-apis rather than 1.0b2 (which is what was pulled in by default), but that doesn&#8217;t appear to make any difference.  I still had to have the 2 exclusions under gt-xsd-core for things to work.</p>
<h2>So what was the problem?</h2>
<p>Now, a little more about the problems I had.  I had two types of errors:</p>
<p><strong>Maven junitreport conflict</strong> &#8211; When I added the dependency for gt-xsd-core and then ran my unit tests using the maven grails plugin (<code>mvn grails:exec -Dcommand=test-app -Dargs="-unit"</code>), my tests would run fine (except for one which I&#8217;ll detail below), but then I would get this error when the junitreport plugin tried to run its XSL transform:</p>
<p><code>Embedded error: java.lang.reflect.InvocationTargetException<br />
Provider org.apache.xalan.processor.TransformerFactoryImpl not found</code></p>
<p>Normally I would suspect that the geotools dependencies brought in some new version of the xalan library and it didn&#8217;t have an old class that the junitreport plugin required.  To check this, I compared the output from both maven dependency:classpath and dependency:tree between my trunk branch and the branch where I had added the geotools dependencies.  The comparision showed that only one one dependency had changed between the branches; a newer version of commons-pool was used.  All other classpath mods were new libraries that were not previously included at all.  In fact, xerces and xalan was not included by the trunk branch at all.  I am sure that someone with more recent experiences with xml-apis, xerces, and xalan knows exactly what was happening.  My guess is that by including the xml-apis-xerces dependency, some piece of the junitreport plugin thought that it could use xalan as opposed to some other XSL lib that it would use when xerces was not present.  This is supported by the fact that if I added xalan as a dependency, the error went away.  If I have time, I&#8217;ll look at the docs for junitreport one of these days and see if that sheds some light on the issue.</p>
<p><strong>PDFImageWriter/NodeList conflict</strong> &#8211; One of the unit tests exercised our use of PDFBox.  If I did not have the above exclusions and I include xalan, this error appeared during the PDFImageWriter constructor:</p>
<p><code>java.lang.LinkageError: loader constraint violation: loader (instance<br />
of &lt;bootloader&gt;) previously initiated loading for a different type with<br />
name "org/w3c/dom/NodeList"</code></p>
<p>I haven&#8217;t tracked down exactly why this linkage conflict occurred.  The bizare thing is that I inserted some link-loading debugging that I used in the past to try to see where NodeList was coming from in both my trunk and geotools-enabled branches:<br />
<code><br />
def clazz =  org.w3c.dom.NodeList.class<br />
def codeSource = clazz.getProtectionDomain().getCodeSource();<br />
println ("Source Location: " + codeSource);<br />
</code></p>
<p>In trunk (i.e. no geotools and working fine), it came back as null; NodeList wasn&#8217;t loaded at all.  In the geotools-enabled branch, it would load (from xerces, I think), but then had that conflict.</p>
<p>At this point, I have a solution (two, actually) and have spend pretty much a whole day researching various paths, so I need to wrap it up and move on.  If anyone has a better solution or thoughts as to why exactly there were problems, feel free to comment.</p>
<p>One last note in case there is any confusion from me mentioning xalan so much &#8211; I did not end up adding a dependency for xalan to my POM.  Just using the exclusion statements listed above solved the issue.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2010/03/20/grailsmavengeotoolspdfbox-pita/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSON conversion and request thread reuse</title>
		<link>http://swordsystems.com/2009/12/18/json-conversion-and-request-thread-reuse/</link>
		<comments>http://swordsystems.com/2009/12/18/json-conversion-and-request-thread-reuse/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 15:33:52 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Controller]]></category>
		<category><![CDATA[frustration]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=50</guid>
		<description><![CDATA[When reusable thread pools and thread local variables can bite you in the butt.]]></description>
			<content:encoded><![CDATA[<p>Wrapping up (I hope) my experience with custom JSON conversions in Grails&#8230; The day before we were supposed to hit a major release milestone last week, I finally caught sight of a random bug that had been driving us nuts.  For some AJAX requests, seemingly at random, the object that has the transient properties was not being rendered with them.  Instead, it had only the regular, persistent properties and full representations of its associated objects rather than just the normal stubs of related objects with just the type and id.  In other words, it was using deep JSON rendering, and this was overriding the custom JSON <code>ObjectMarshaller</code> that we had set for the class.  But why was it doing it seemingly at random?  This is where luck and experience combined to make the solution clear rather quickly and avoided some painful slogging through request handling on the server.</p>
<p>The luck part was that I remembered seeing a checkin from a teammate a couple of weeks ago where he got rid of direct use of a <code>grails.converters.deep.JSON</code> object (which is deprecated) and instead switched to a normal <code>grails.converters.JSON</code> object with a <code>use('deep')</code> statement:</p>
<p><code>def get = {<br />
	def o = OurClass.get(params.id);<br />
	JSON.use("deep")<br />
	render(contentType: "application/json", text: o as JSON)<br />
}<br />
</code><br />
This change was in a different controller for a different domain object though.  Why was it affecting our other domain class?  That&#8217;s where the experience part came in.  A few years ago I had to track down why hibernate transactions would fail seemingly at random in another web app when running under JBoss.  I could see why an initial transaction would fail (we&#8217;d get a timeout and not rollback properly), but there was no reason why later requests would cause failures.  That&#8217;s when I discovered the downside of request thread pooling.  Under most web contains, HTTP requests are handled by a pool of reusable threads.  That means changes to thread local variables stick around between requests unless explicitly reset.  In the case of the Hibernate bug, since the session was not getting closed properly, it wasn&#8217;t getting fully reset and cleared out, so subsequent requests that used that thread were getting the old session and failing because there was no way to get it back to a good state.</p>
<p>For the current JSON conversion bug, the <code>JSON.use</code> method was calling <code>ConvertersConfigurationHolder.setTheadLocalConverterConfiguration(...)</code>, thus making the deep converter stick around for that thread.  So when future requests came in to any controller on that thread, all JSON conversion calls were made with the deep configuration.</p>
<p>The solution is straightforward.  Use the <code>JSON.use(String, Closure)</code> call instead when you want to make a deep call:</p>
<p><code>def get = {<br />
    def o = OurClass.get(params.id);<br />
    JSON.use("deep") {<br />
        render(contentType: "application/json", text: o as JSON)<br />
    }<br />
}</p>
<p></code>This sets the configuration only for the closure, saving you from thread-based side effects later on.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/12/18/json-conversion-and-request-thread-reuse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails JSON converter and transient properties</title>
		<link>http://swordsystems.com/2009/11/23/grails-json-converter-and-transient-properties/</link>
		<comments>http://swordsystems.com/2009/11/23/grails-json-converter-and-transient-properties/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 16:04:55 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=42</guid>
		<description><![CDATA[I figured out why my domain object was rendering as JSON differently in unit tests vs. when running the application and integration tests. Drum roll, please&#8230;No grailsApplication object is setup in unit tests. I hear a great big, &#8220;Huh?&#8221; First, a little background on converters. (You may want to get the Grails source code and [...]]]></description>
			<content:encoded><![CDATA[<p>I figured out why my domain object was rendering as JSON differently in unit tests vs. when running the application and integration tests.   Drum roll, please&#8230;No grailsApplication object is setup in unit tests.</p>
<p>I hear a great big, &#8220;Huh?&#8221;  </p>
<p>First, a little background on converters.  (You may want to get the Grails source code and have directories open to the <code>org.codehaus.groovy.grails.web.converters</code> and <code>grails.converter</code> packages before diving into this.)  When a <code>JSON</code> converter is created, it obtains a <code>ConverterConfiguration</code> from the global <code>ConvertersConfigurationHolder</code>.  <code>ConverterConfiguration</code> has several properties which influence the conversion process, but the most interesting for this discussion is its prioritized set of <code>ObjectMarshallers</code>.  <code>ObjectMarshaller</code>s are what do the actual work of turning an object into a JSON representation.  Each <code>ObjectMarshaller</code> handles a certain set of classes, like arrays, maps, beans, grails domain objects, etc.  When the <code>JSON</code> object is ready to convert a data object, it calls <code>config.getMarshaller(data)</code>.  The config iterates through its list of marshallers, calling <code>marshaller.supports(data)</code> on each.  Since multiple marshallers may be able to handle a specific class (like <code>GroovyBeanMarshaller</code> and <code>DomainClassMarshaller</code> can both handle domain classes), whichever marshaller has highest priority (i.e. is called first) will be invoked.</p>
<p>When the standard <code>ConverterConfiguration</code> is initialized, the <code>DomainClassMarshaller</code> is given higher priority than the <code>GroovyBeanMarshaller</code>.  Thus, it handles the conversion of domain objects during normal Grails application execution even though domain objects are also groovy beans.  However, the <code>DomainClassMarshaller.supports()</code> method has a slight twist to it.  It depends on there being a <code>GrailsApplication</code> object registered in the <code>ConverterUtil</code> class in order to tell it that a particular object is a domain object.  Without the <code>GrailsApplication</code> object, <code>ConverterUtil.isDomainClass()</code> always returns false, causing <code>DomainClassMarshaller.supports()</code> to also return false.  The <code>ConverterConfiguration</code> next checks the <code>GroovyBeanMarshaller</code>.  Its <code>supports()</code> method returns true, so it handles the conversion in this case.  </p>
<p>So why is this a big deal?  For most domain object, it probably isn&#8217;t.  Both marshallers render the primary properties of the domain object.  However, the <code>DomainClassMarshaller</code> only renders properties return by <code>domainClass.getPersistentProperties()</code> while <code>GroovyBeanMarshaller</code> renders all properties, including transient ones.  Because I needed some transient properties in the JSON representation, my unit tests worked great (since there is no grailsApplication setup, so the <code>GroovyBeanMarshaller</code> did the full rendering), but then my code failed when I ran the integration tests and the real app (since the <code>DomainClassMarshaller</code> handled the rendering).</p>
<p>How do you fix this?  It&#8217;s pretty easy once you know where to look.  First, I wanted to make my unit tests behave like the real app, so I had to get them to fail.  Unfortunately, the conversion classes are written in java, not groovy, so you can&#8217;t just do a quick override of the <code>ConverterUtil</code> metaclass to get it to return what you want.  You actually need to setup a <code>GrailsApplication</code> object.  Rather than trying to create and initialize a whole one though, I determined that I could create a small stub class that overrode the two methods I needed:</p>
<p><code><br />
import org.codehaus.groovy.grails.commons.*<br />
class GrailsApplicationStub extends DefaultGrailsApplication {<br />
    def artefacts = [(DomainClassArtefactHandler.TYPE):[:]]</p>
<p>    boolean isArtefactOfType(String artefactType, String className) {<br />
        return getArtefact(artefactType, className) != null<br />
    }</p>
<p>    GrailsClass getArtefact(String artefactType, String name) {<br />
        def retVal = artefacts[artefactType] ? artefacts[artefactType][name] : null<br />
        return retVal<br />
    }<br />
}<br />
</code><br />
When initializing the unit test, I created the stub and set in the particular domain class that I wanted to be recognized.  Then register the application stub with the <code>ConverterUtil</code> class:</p>
<p><code><br />
def grailsApp = new GrailsApplicationStub();<br />
grailsApp.artefacts[DomainClassArtefactHandler.TYPE][YourClass.name] = new DefaultGrailsDomainClass(YourClass);<br />
ConverterUtil.setGrailsApplication(grailsApp);<br />
</code><br />
Instances of <code>YourClass</code> will now be handled by the <code>DomainClassMarshaller</code> in the unit test.  When the unit test checks for the existence of a transient property in a JSON representation, it should fail.</p>
<p>Next, I needed to change the marshaller prioritization so that the desired domain class was handled by a regular <code>GroovyBeanMarshaller</code>.  Since I always wanted the <code>GroovyBeanMarshaller</code> to handle the class, I inserted this code into my unit test setup (and later into <code>BootStrap</code> so the behavior would apply to the full app):</p>
<p><code><br />
JSON.registerObjectMarshaller(YourClass, {o, c -><br />
    new GroovyBeanMarshaller().marshalObject(o, c)<br />
    })<br />
</code></p>
<p>This creates a <code>ClosureObjectMarshaller</code> that handles <code>YourClass</code> objects and gives the new marshaller the default priority of 1 (which puts it at the top of the priority list).  When processing an object, this closure marshaller simply passes it through to a <code>GroovyBeanMarshaller</code>.  Since the new marshaller only handles <code>YourClass</code> objects, the rendering behavior for all other domain objects is not affected.</p>
<p>This resolved my original issue.  The JSON rendering of my object is now correct when I run my app. I did go down a side path while coming to this final solution.  If you only want to override how a <code>YourClass</code> object is rendered some of the time, you could instead register a named configuration for it like this:</p>
<p><code><br />
JSON.createNamedConfig("FullYourClassRender") {cfg -><br />
    cfg.registerObjectMarshaller(new ClosureOjectMarshaller<JSON>(YourClass, {o, c -><br />
        new GroovyBeanMarshaller().marshalObject(o, c)<br />
        }))<br />
    }<br />
</code><br />
Then when you want to use that particular configuration, you wrap the <code>JSON</code> object calls in a use statement:</p>
<p><code><br />
JSON.use("FullYourClassRender") {<br />
    render(contentType: "application/json", text: myObject as JSON)<br />
    }<br />
</code></p>
<p>Other configuration options are also available.  Take a look at the <code>JSON</code> class to see them.</p>
<p>I hope this helps document the conversion process a bit.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/11/23/grails-json-converter-and-transient-properties/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fun with Grails JSON conversion</title>
		<link>http://swordsystems.com/2009/11/20/fun-with-grails-json-conversion/</link>
		<comments>http://swordsystems.com/2009/11/20/fun-with-grails-json-conversion/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 06:15:15 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[Intellij]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=39</guid>
		<description><![CDATA[I discovered a problem this afternoon with how one of the domain objects in my Grails app was being converted to JSON in its controller.  The conversion functioned as expected in a unit test, but failed in integration tests and when running the real app.  &#8220;Time to see how good the debugger in Intellij 9 [...]]]></description>
			<content:encoded><![CDATA[<p>I discovered a problem this afternoon with how one of the domain objects in my Grails app was being converted to JSON in its controller.  The conversion functioned as expected in a unit test, but failed in integration tests and when running the real app.  &#8220;Time to see how good the debugger in Intellij 9 is,&#8221; I say to myself.  So I dive into the grails.converters.JSON class to try to find where the difference comes from.  Unfortunately, every time I step into the render() method, the rendering quickly fails with this exception:</p>
<p>org.codehaus.groovy.grails.web.json.JSONException: &#8220;Misplaced object&#8221;</p>
<p>It turns out that the JSON converter has a writer property that is a JSONWriter object.  The act of showing the writer in the variables window of the Intellij debugger causes its toString() method to be called by the IDE (though any breakpoints set in the class do not get triggered by the call).  This, in turn, causes the writer to actually do the writing of the object which, when complete, changes the writer&#8217;s state property to DONE.  When the real code execution tries to process the data, the JSONWriter throws the exception because it thinks it has already finished rendering.</p>
<p>The trick to step through the JSON converter is to define a custom Type Renderer for the JSONWriter class that does not invoke the &#8220;toString&#8221; method.  <a href="http://blogs.jetbrains.com/idea/2008/04/type-renderers/" target="_blank">A blog post</a> on the Intellij site defines how to setup a Type Renderer for a class.  I set mine up so that the node renders simply as &#8220;JSONWriter&#8221; since I don&#8217;t need to see the details for it.  One caveat though &#8211; I found that the new Type Renderer didn&#8217;t affect entries already in my variables window until I right-clicked one and selected &#8220;View As -&gt; JSONWriter&#8221;.  Then the view changed to use the new display settings.</p>
<p>Now back to debugging&#8230;maybe I&#8217;ll actually figure out the real problem sometime before the sun comes up.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/11/20/fun-with-grails-json-conversion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>When dynamic programming backfires</title>
		<link>http://swordsystems.com/2009/11/20/when-dynamic-properties-backfire/</link>
		<comments>http://swordsystems.com/2009/11/20/when-dynamic-properties-backfire/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 05:53:22 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[frustration]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=35</guid>
		<description><![CDATA[I love Groovy&#8217;s meta-programming capabilities.  Duck typing, DSLs, ExpandoMetaClass&#8230; it&#8217;s all great until you blow your arm off with them and spend two hours picking the pieces back up.  Such was my experience today as I was trying to set up my first unit test for a Grails controller.  I needed to pass in some [...]]]></description>
			<content:encoded><![CDATA[<p>I love Groovy&#8217;s meta-programming capabilities.  Duck typing, DSLs, ExpandoMetaClass&#8230; it&#8217;s all great until you blow your arm off with them and spend two hours picking the pieces back up.  Such was my experience today as I was trying to set up my first unit test for a Grails controller.  I needed to pass in some parameters.  As I just wrote in my last post, the grails user guide has information on integration testing controllers, but nothing more than a brief mention of the <code>ControllerUnitTestCase</code>.  Unfortunately, searching for phrases like &#8220;grails unit test controller&#8221; on Google turn up posts from last Fall, before the <code>ControllerUnitTestCase </code>was released with Grails 1.1.  Don&#8217;t ask me why I didn&#8217;t just search for <code>ControllerUnitTestCase </code>from the start.  20/20 hindsight.</p>
<p>Working with what I could find, I came across a <a href="http://kousenit.wordpress.com/2008/03/24/integration-tests-of-controllers-in-grails/" target="_blank">blog post from March 2008</a> that covered integration testing with controllers, much like the grails User Guide.  It at least had some explicit examples of how to pass in parameters, so I hoped the approach would work with my <code>ControllerUnitTestCase </code>implementation.  Using the code snippets in the post as a guide, I setup my test something like this:</p>
<p><code>controller.request.params = [layoutType:'filmstrip',compKey:'testKey']<br />
controller.create()<br />
</code><br />
This looks good, right?  The test scaffolding connects the injected <code>params </code>property of the controller with the <code>params </code>property of the request.  Should work like a charm.</p>
<p>And so started my descent into WTF Land.</p>
<p>The tests compiled and ran fine, except that no params were getting passed through to the controller.  I assumed that the old documentation for integration testing no longer exactly applied for the new unit test setups.  Eventually I dug through enough of <code>ControllerUnitTestCase</code>, <code>MvcUnitTestCase</code>, and <code>MockUtils </code>that I figured out there was a way to get direct access to the <code>params </code>property of the controller.  &#8220;Makes sense,&#8221; I thought, &#8220;sort of a mini-mock.  Who needs the request for a unit test?&#8221;  Great, so let&#8217;s try this:</p>
<p><code>controller.params = [layoutType:'filmstrip',compKey:'testKey']<br />
controller.create()<br />
</code><br />
Run again and&#8230;</p>
<p><code>groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: params for class: YourController<br />
</code><br />
Erk.  Closer inspection of <code>grails.test.MockUtils.addCommonWebProperties()</code> reveals how the <code>params </code>property is added to the controller class with only a <code>get </code>method.  Okay, so we can still manipulate the map once we get it.  One more try:</p>
<p><code>controller.params.putAll([layoutType:"filmstrip",compKey:'testKey'])<br />
controller.create()<br />
</code><br />
Success!  Finally, information is going where it needs to be.  I later realized that section 9.2 of the user guide does actually show an example similar to this, except that it sets each item on params individually:</p>
<p><code>def controller = new AuthenticationController()<br />
controller.params.login = "marcpalmer"<br />
controller.params.password = "secret"<br />
controller.params.passwordConfirm = "secret"<br />
controller.signup()</p>
<p></code>&#8220;Oh well,&#8221; I say to myself, &#8220;at least I got it working.  I&#8217;d better post a comment on that old blog post so that others know the new way to set parameters.&#8221;  I returned to the blog page, moved down to the comments section&#8230; and saw that someone else had posted a comment just last month thanking the author for the good information.  Wait a second&#8230; you normally don&#8217;t thank someone if their examples don&#8217;t work.  So I scrolled up and took a closer look at the examples again:</p>
<p><code>controller.request.parameters = [sender:'me',msg:'test']<br />
controller.create()<br />
</code><br />
Anyone with a better eye for detail than me see the difference that sent me down the rat hole? It&#8217;s <code>request.parameters</code>, not <code>request.params</code> as I had entered.  For the 100th time today, Doh!</p>
<p>But wait a second (or an hour, as the case may be)&#8230; If I was calling <code>request.params</code> and there is no params property, how did my test run at all?  Dig, dig, dig&#8230; It turns out that the request is a <code>GrailsMockHttpServletRequest </code>object.  Scanning through that class, I see the ever so powerful and ever so dangerous <code>setProperty(String name, value)</code> override.  If you try to set a property that doesn&#8217;t exist, it adds the value as an entry in the request&#8217;s <code>attributes </code>map.  So the test scaffolding was perfectly happy with my <code>request.params</code> call.  It nicely tucked my params map away in the attributes and continued on its way.</p>
<p>Sigh&#8230;it almost makes me miss compile-time method checking&#8230; but not quite.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2009/11/20/when-dynamic-properties-backfire/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

