<?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</title>
	<atom:link href="http://swordsystems.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://swordsystems.com</link>
	<description>Cutting Commentary</description>
	<lastBuildDate>Tue, 15 May 2012 14:50:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Grails 2 Unit Tests &#8211; Undocumented Properties</title>
		<link>http://swordsystems.com/2012/05/15/grails-2-unit-tests-undocumented-properties/</link>
		<comments>http://swordsystems.com/2012/05/15/grails-2-unit-tests-undocumented-properties/#comments</comments>
		<pubDate>Tue, 15 May 2012 14:50:27 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[unit test]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=242</guid>
		<description><![CDATA[GrailsUnitTestMixin (and its descendents DomainClassUnitTestMixin, ServiceUnitTestMixin, etc) give your test classes some static and instance variables that aren&#8217;t mentioned in the docs yet. You get applicationContext, grailsApplication, config, and messageSource. Previously, if you had code that needed a grailsApplication (such as the JSON configurations), you had to set it up yourself. Now you get it [...]]]></description>
			<content:encoded><![CDATA[<p><code>GrailsUnitTestMixin</code> (and its descendents <code>DomainClassUnitTestMixin</code>, <code>ServiceUnitTestMixin</code>, etc) give your test classes some static and instance variables that aren&#8217;t mentioned in the docs yet.  You get <code>applicationContext, grailsApplication, config</code>, and <code>messageSource</code>.  Previously, if you had code that needed a grailsApplication (such as the JSON configurations), you had to set it up yourself.  Now you get it for free.  The mixin also implements the <code>shouldFail</code> method from <code>GroovyTestCase</code> so you can keep that functionality even though your tests are now JUnit 4 based.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2012/05/15/grails-2-unit-tests-undocumented-properties/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails 2 Unit Tests &#8211; Using Base Classes</title>
		<link>http://swordsystems.com/2012/05/15/grails-2-unit-tests-using-base-classes/</link>
		<comments>http://swordsystems.com/2012/05/15/grails-2-unit-tests-using-base-classes/#comments</comments>
		<pubDate>Tue, 15 May 2012 14:43:15 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[unit test]]></category>
		<category><![CDATA[grails testing]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=228</guid>
		<description><![CDATA[I&#8217;ve been meaning to write up my experiences with upgrading a 1.x app to grails 2 for two months now. Since I can&#8217;t seem to find the time to do a large post, I&#8217;ll follow MrHaki&#8217;s example and sprinkle some nuggets of wisdom around. Here&#8217;s a couple of bits on the new unit testing components. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been meaning to write up my experiences with upgrading a 1.x app to grails 2 for two months now.  Since I can&#8217;t seem to find the time to do a large post, I&#8217;ll follow <a href="http://mrhaki.blogspot.com/search/label/Grails" target="_blank">MrHaki&#8217;s</a> example and sprinkle some nuggets of wisdom around.  Here&#8217;s a couple of bits on the new unit testing components.</p>
<p>First, read <a href="http://naleid.com/blog/2012/05/01/upgrading-to-grails-2-unit-testing/" title="Grails 2 unit testing" target="_blank">Ted Naleid</a>&#8216;s great writeup.  He encountered many of the same issues I found and documented them in great detail.  Plus he has a list of other reference pages.</p>
<p>Second, as Ted mentions, there are problems using a base class for tests.  This is especially true if you have JUnit annotations in the base class like <code>@Before</code>.  Instead, turn your base class into a generic POGO and then use the @TestMixin annotation to include it in your tests.  </p>
<pre class="brush: groovy; title: ; notranslate">
class MyAppTestSupport {
    //...useful common properties and methods here....
}
</pre>
<p>Then in your test class:</p>
<pre class="brush: groovy; title: ; notranslate">
@TestFor(MyDomainClass)
@TestMixin(MyAppTestSupport)
class MyDomainClassTests {
    //you can access the properties and methods from MyAppTestSupport here just as
    //if they were part of your class
}
</pre>
<p>This makes it a little harder to jump to routines in the mixed-in class in an IDE (at least Intellij gets a bit confused), but the tests will run consistently.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2012/05/15/grails-2-unit-tests-using-base-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>No Fluff Just Stuff and CANI</title>
		<link>http://swordsystems.com/2012/05/02/no-fluff-just-stuff-and-cani/</link>
		<comments>http://swordsystems.com/2012/05/02/no-fluff-just-stuff-and-cani/#comments</comments>
		<pubDate>Wed, 02 May 2012 13:49:28 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=222</guid>
		<description><![CDATA[I attended another great NFJS conference this weekend. This was the first year where I would say that mobile development was one of the leading topic areas. Surprisingly, there wasn&#8217;t a single Grails presentation, though Grails was mentioned by several presenters. It seems to have slipped into the area of &#8220;we&#8217;ll assume you are using [...]]]></description>
			<content:encoded><![CDATA[<p>I attended another great NFJS conference this weekend.  This was the first year where I would say that mobile development was one of the leading topic areas.  Surprisingly, there wasn&#8217;t a single Grails presentation, though Grails was mentioned by several presenters.  It seems to have slipped into the area of &#8220;we&#8217;ll assume you are using Grails if you can since it makes your life much easier&#8221; category for now.  </p>
<p>In any case, mobile dev was the focus of or was mentioned in 8 of the 11 sessions I attended.  The design pattern of implementing REST APIs for your server apps and using a lightweight, MVC javascript library like <a href="http://documentcloud.github.com/backbone" title="backbone" target="_blank">Backbone</a> or <a href="http://spinejs.com/" title="spine" target="_blank">Spine</a> for your front end tied into this.  You can use the REST APIs as a service for native mobile apps along with the web apps, and the small size of the JS libraries works well for the limited memory and bandwidth of mobile browsers.  Nathaniel Schutta&#8217;s <a href="http://www.nofluffjuststuff.com/conference/reston/2012/04/session?id=24969" target="_blank">JavaScript Libraries You Aren&#8217;t Using&#8230;Yet</a> presentation is a great overview of some of the most popular libraries.</p>
<p>I must say that the body parts theme is getting a bit out of hand.  Besides backbone and spine, there are the templating libraries <a href="http://mustache.github.com/" title="moustache" target="_blank">mustache</a> and <a href="http://handlebarsjs.com/" title="handlebars" target="_blank">handlebars</a>.  <a href="https://github.com/walmartlabs" target="_blank">Walmart</a> has developed backbone extensions called thorax and lumbar.  Since <a href="http://coffeescript.org/" target="_blank">CoffeScript</a> is also a part of this mix, I thought I should take this whole clever name scheme to the next level -</p>
<p>I hereby announce the CANIjs library &#8211; Caffeinated Nerve Impulses &#8482;.  I don&#8217;t know what it&#8217;s going to do yet, but as soon as the jitters where off, I&#8217;ll think about it.  Probably something to do with eventing (nerves, signals, events, etc).  I do know that if you use it in the wrong way, everyone will say &#8220;That&#8217;s un-cani.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2012/05/02/no-fluff-just-stuff-and-cani/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails Plugins Presentation</title>
		<link>http://swordsystems.com/2012/02/17/grails-plugins-presentation/</link>
		<comments>http://swordsystems.com/2012/02/17/grails-plugins-presentation/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 16:32:22 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=203</guid>
		<description><![CDATA[I presented at the DC GUG meeting a couple of days ago, this time on Grails plugins. I wanted to go beyond the normal &#8220;these are the basics of Grails&#8221; intro to cover the main points of what you need to do to get a real project up and running and how to maintain it. [...]]]></description>
			<content:encoded><![CDATA[<p>I presented at the <a href="http://www.dcgroovy.org/events/43477442/" title="DC Groovy User's Group" target="_blank">DC GUG</a> meeting a couple of days ago, this time on Grails plugins.  I wanted to go beyond the normal &#8220;these are the basics of Grails&#8221; intro to cover the main points of what you need to do to get a real project up and running and how to maintain it.  I covered things like authentication, fixtures, tests and test data sets, audit logging, remote debugging, and monitoring. A bit too aggressive for an hour-long presentation (okay, so way too aggressive), but folks seemed to enjoy it.  Hopefully I&#8217;ll have another opportunity to present it so I can tune it up a bit.  For now, the slides are on <a href="http://www.slideshare.net/ericsword/grails-goto-plugins" title="slideshare" target="_blank">slideshare</a> and the basis for the sample project is on <a href="https://github.com/esword/grails-plugin-sandbox" title="github" target="_blank">github</a>.  I&#8217;ll try to breakout the key points into individual posts soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2012/02/17/grails-plugins-presentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>I am Alanis Morissette</title>
		<link>http://swordsystems.com/2011/12/15/i-am-alanis-morissette/</link>
		<comments>http://swordsystems.com/2011/12/15/i-am-alanis-morissette/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 14:30:44 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=204</guid>
		<description><![CDATA[Isn&#8217;t it ironic that one of your posts attracts the attention of a grails guru&#8230;and it&#8217;s because you misspelled his name. (Sorry about that, Burt. I updated the post.) Even better, my blog software then blocked Sir Beckwith from posting because it thinks he is part of a spammer network. Shortly after it blocked him, [...]]]></description>
			<content:encoded><![CDATA[<p>Isn&#8217;t it ironic that one of your posts attracts the attention of a grails guru&#8230;and it&#8217;s because you misspelled his name. (Sorry about that, Burt.  I updated the post.)  Even better, my blog software then blocked Sir Beckwith from posting because it thinks he is part of a spammer network.  Shortly after it blocked him, it let through a comment from a spam bot.  Sigh.  Looks like I have some research to do since I can&#8217;t get WP-Spamfree to properly generate a log telling me why it blogged him.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/12/15/i-am-alanis-morissette/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>More Parallel Processing in Jenkins Notes</title>
		<link>http://swordsystems.com/2011/10/31/more-parallel-processing-in-jenkins-notes/</link>
		<comments>http://swordsystems.com/2011/10/31/more-parallel-processing-in-jenkins-notes/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 16:05:25 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Hudson]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=186</guid>
		<description><![CDATA[October must be my month to think about CI testing. Unfortunately, I haven&#8217;t had time to do much with it since my last post a year ago, but I did stumble across these rough notes I took while getting a &#8220;job pyramid&#8221; setup in our Hudson/Jenkins server last year. I never got around to turning [...]]]></description>
			<content:encoded><![CDATA[<p>October must be my month to think about CI testing.  Unfortunately, I haven&#8217;t had time to do much with it since my <a href="http://swordsystems.com/2010/10/11/using-hudson-to-run-tests-in-parallel/" title="Using Hudson to run tests in parallel" target="_blank">last post</a> a year ago, but I did stumble across these rough notes I took while getting a &#8220;job pyramid&#8221; setup in our Hudson/Jenkins server last year.  I never got around to turning them into a full post, but I wanted to record them in a better place for future reference.  Maybe they will help someone else as well.  Remember, these are now a year old, so some bugs may be fixed or new features added.  I haven&#8217;t had time to stay current on happenings with Jenkins since then.  Please forgive the lack of formatting, proof reading, grammar, or anything resembling organization.</p>
<h2>Random Tips</h2>
<ul>
<li>I installed the HTML Publisher plugin to view the codenarc reports until I could figure out why the Violations plugin doesn&#8217;t like the codenarc XML output.  Make sure to put your reports in unique directories.  I initially tried to just output the report in the target directory and it ended up archiving my whole target directory.
<li>The codenarc plugin requires that the full parent path for the file it will output be present, so if you want to write it to, say, the <code>target/test-reports</code> directory, must make sure that directory is there.  I added another line to do this in the groovy script I already had for creating the fingerprint file.
<li>I added the job config history plugin.  Very handy when experimenting with different setups so you can easily get back to a config that worked.
<li>Turned on the log parsing plugin.  Would be handy if it shipped with a default rules parsing file, but nice none-the-less.
<li>Downstream builds report plugin &#8211; Doesn&#8217;t really provide any new info when only have a single layer of downstream jobs
<li>Groovy plugin &#8211; I put some shared scripts in a common directory and created a Hudson global property for the path.  If I tried to use that variable to list the path to a script (e.g. <code>$SHARED_SCRIPTS/some_script.groovy</code>), the plugin would assume the path was relative to the workspace.  I had to insert an extra &#8220;/&#8221; in the &#8220;Groovy script file&#8221; space (e.g. <code>/$SHARED_SCRIPTS/some_script.groovy</code>) for the plugin to realize it was an absolute path.
<li>Like the codenarc tool, the JSUnit ant tool will fail unless the parent directory of the output directory has not already been created.
<li>Increase your quiet time if you often check in groups of files using multiple commits
<li>If run functional (e.g. selenium) tests in separate build step, need to output reports to different directory or else they wipe the unit/integration reports
<li>There is a time sync problem between servers documented in the <a href="http://www.sonatype.com/people/2009/02/the-hudson-build-farm-experience-volume-iii/" title="sonatype blog" target="_blank">sonatype blog</a>.  The article says to use VMWare Tools to sync time on VM with the ESX server.  Unfortunately, it our own ESX server&#8217;s time is about 25 minutes slow, so that causes problems of it&#8217;s own.
<li>If you want to have a single build step which runs unit and integration tests and generates coverage stats, you should specify the arguments in this order: <code>-coverage -xml -unit -integration</code>.  If you try to do something like this: <code>-unit -integration -coverage -xml</code>, mvn/grails will think that you want to only execute an integration test named &#8220;-coverageTests&#8221; and it will also give you an error because it doesn&#8217;t understand the -xml parameter on it&#8217;s own.  (Yes, I know this is the old syntax form for running grails tests.  I haven&#8217;t tried with the newer form.)
<li>If you clone a downstream project, the build trigger to run when the upstream project completes is not cloned with it
<li>You can&#8217;t set a build to a better result than it already has.  i.e. if it&#8217;s FAILED, you can&#8217;t set it to UNSTABLE.  This is a pain if mvn tries to fail your build and you want to run a post-build script that checks if it was really a failure.
<li>A small problem with having to combine the cobertura output (and thus not using the HTML output directly from the cobertura-grails plugin) is that you don&#8217;t get the nice closure-renaming in the file-level stats from the grails plugin.  So you see things like <code>MyController$_closure2...</code> You can still see what lines are covered or not right below the stats, so this isn&#8217;t a huge issue.
<li>Using the clone workspace method makes the config a little cleaner, but there may be a risk that not all the downstream jobs get the archive copied before the next build job completes and removes the current copy (since it only keeps 1, I think).  Not sure if this could happen unless possibly the downstream job is spun out to a clone and then a next build of the upstream job is started on the master.  If the clone doesn&#8217;t start copying the workspace archive until after the master completes the next build, you could get the wrong archive.  You also can&#8217;t fingerprint it.  At least, I don&#8217;t think you can.
</ul>
<h2>Syncing Builds</h2>
<p>I setup the full &#8220;job diamond&#8221; as a mentioned in my <a href="http://swordsystems.com/2010/10/11/using-hudson-to-run-tests-in-parallel/" title="Using Hudson to run tests in parallel" target="_blank">last post</a> on this.  One issue I ran into was how to make sure the join job pulls artifacts from the proper build of the origin job?  You can&#8217;t do &#8220;last successful build&#8221; because there could have been additional builds of the originator job while the first-tier sub-jobs were run but prior to the join-job running.</p>
<p>The solution I came up with was to have the join trigger call two sub-triggers</p>
<ol>
<li>Aggregate archived artifacts &#8211; grab the artifacts you need from the primary downstream jobs.  In my case, I wanted to get the test reports.
<li>Parametrized build trigger &#8211; Define a sub-parametrized build trigger that invokes the join-job, passing the BUILD_NUMBER of the origin job as the parameter. (Use the Predefined parameters dialog for this.)
</ol>
<p>Then, in the join-job</p>
<ol>
<li>Define a string parameter to accept the passed in build number.
<li>In the build steps, create a &#8220;Copy artifacts&#8221; step, set it to get a specific build, and then set the build parameter name as the value
</ol>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/10/31/more-parallel-processing-in-jenkins-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GPars Quick Hits</title>
		<link>http://swordsystems.com/2011/09/28/gpars-quick-hits/</link>
		<comments>http://swordsystems.com/2011/09/28/gpars-quick-hits/#comments</comments>
		<pubDate>Thu, 29 Sep 2011 02:30:07 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[gpars]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=165</guid>
		<description><![CDATA[Just finished my presentation to the DC Groovy Users Group on GPars collection and closure enhancements. Slides are on slide share for anyone who wants to take a peek. I&#8217;ll post up some of the coding examples when I get a chance.]]></description>
			<content:encoded><![CDATA[<p>Just finished my presentation to the DC Groovy Users Group on GPars collection and closure enhancements.  Slides are on <a href="http://www.slideshare.net/ericsword/gpars-quick-hits" title="slide share">slide share</a> for anyone who wants to take a peek.  I&#8217;ll post up some of the coding examples when I get a chance.</p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/09/28/gpars-quick-hits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GPars performance test</title>
		<link>http://swordsystems.com/2011/08/29/gpars-performance-test/</link>
		<comments>http://swordsystems.com/2011/08/29/gpars-performance-test/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 11:46:28 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[gpars]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://swordsystems.com/?p=164</guid>
		<description><![CDATA[We just added a REST interface for replicating data between servers. Parts of the service require us to GET a collection of URLs all at once and to POST an object to a collection of remote servers all at once. I thought this would be a great time to try out GPars. After all, you [...]]]></description>
			<content:encoded><![CDATA[<p>We just added a REST interface for replicating data between servers.  Parts of the service require us to GET a collection of URLs all at once and to POST an object to a collection of remote servers all at once.  I thought this would be a great time to try out GPars.  After all, you can&#8217;t get much easier pooling/multi-threaded support than:</p>
<pre class="brush: java; title: ; notranslate">
    GParsPool.withPool {
        urlList.eachParallel {
            ...get/post with Jersey client...
        }
    }
</pre>
<p>Some of my co-workers expressed concern that this would involve creating and destroying the pool data structures (specifically, Java threads) for every url or server collection we submitted.  They thought this would take too much overhead.  So I decided to put together a few tests to see what GPars could get us using its simplest form of concurrency.  First, an interesting tidbit from the reference guide:</p>
<blockquote><p>
While the GParsPool class relies on the jsr-166y Fork/Join framework and so offers greater functionality and better performance, the GParsExecutorsPool uses good old Java executors and so is easier to set up in a managed or restricted environment.  It needs to be stated, however, that GParsPool performs typically much better than GParsExecutorsPool does.  (<a href="http://www.gpars.org/guide/guide/3.%20Data%20Parallelism.html">Section 3 intro</a>).
</p></blockquote>
<p>and, from Groovy in Action v2:</p>
<blockquote><p>
GParsPool does not create threads. Instead, it takes them from a fork/join thread pool of the jsr166y library, which is a candidate for inclusion in future Java versions. GPars uses this library extensively, especially its support for parallel arrays that are the basis for all parallel collection processing in GPars.&#8221; (Section 17.2)
</p></blockquote>
<p>If these statements were correct, then hopefully we didn&#8217;t have to worry about maintaining an existing pool and setting up a countdown latch of some form.</p>
<h2>Tests</h2>
<p>I threw together some quick-and-dirty tests:</p>
<ul>
<li>A series of mathematical operations (i.e. pure cpu)</li>
<li>Open and read in the text of 120 files, each about 1-4Kb</li>
<li>Get the contents of a small web page (9kb) hosted on a machine on the local network</li>
</ul>
<p>Obviously, these were not meant to be a definitive test of all of GPars capabilities.  I just wanted to see if we could use the simplest form of GPars notation or if we had to do something more complicated.</p>
<p>I ran each test in a loop various numbers of times (100 up to 10000), just to see if there was significant difference over time.  The results I list below are for the test that ran the loop 5000 times.  The core bit of code I timed was something like this:</p>
<pre class="brush: java; title: ; notranslate">
    int ms = 0
    5000.times {
        StopWatch timer = new StopWatch().go()
        GParsExecutorsPool.withPool {
            List result = data.collectParallel {
                //(1..100).sum {i -&gt; i^it}
                //or
                //it.text.size()
            }
        }
        ms += timer.stop
    }
    def message = DebugUtils.logTimePerItem(&quot;GParsPool&quot;, numLoops, ms)
    println message
</pre>
<p>where &#8220;it&#8221; was a File or URL (or a number for test #1).</p>
<p>I ran the test using regular sequential code (i.e. commenting out the <code>withPool</code> block and changing <code>collectParallel</code> to the normal <code>collect</code>), and then using GParsPool.withPool and GParsExecutorsPool.withPool.  I also tried using the GPars <code>ParallelEnhancer</code> class and the <code>makeConcurrent</code>, both of which let me just use the normal <code>collect</code> call rather than having to write <code>collectParallel</code>.  For some reason, these conventions slowed down the collection processing by a noticeable amount.  I did not dive into why that happens, but I suspect it has to do with the additional overhead of the custom <code>MetaClass</code> handling.</p>
<h1>Results</h1>
<p>These are the results on my Dell Precision M6400 running 32-bit Fedora 14.  The JVM had 1.5G of RAM.</p>
<h3>Test: Mathematical Operation</h3>
<p>Normal: 5000 in 14594 (343/s)<br />
GParsPool: 5000 in 12480 (401/s)<br />
GParsExecutorsPool: 5000 in 15685 (319/s)</p>
<p>I reran this test with the timer inside the withPool call to see what the overhead of creating the pool was, i.e.:</p>
<pre class="brush: java; title: ; notranslate">
        GParsExecutorsPool.withPool {
            MemStopWatch timer = new MemStopWatch().go()
            List result = data.collectParallel {
                (1..100).sum {i -&gt; i^it}
            }
            ms += timer.stop
        }
</pre>
<p>with these results:<br />
GParsPool: 5000 in 11253 (444/s)<br />
GParsExecutorsPool: 5000 in 13308 (376/s)</p>
<p>So setting up the pool each time definitely has some overhead cost, but even doing that, the GParsPool is still faster than normal, single-threaded sequential execution, even on my little ol&#8217; dual core machine.</p>
<h3>Test: Open and Read Files</h3>
<p>Normal: 5000 in 31726 (157/s)<br />
GParsPool: 5000 in 24050 (207/s)<br />
GParsExecutorsPool: 5000 in 25351 (197/s)</p>
<p>Very similar scale of results as with the straight mathematical operation.</p>
<h3>Test: Get small web page over local network</h3>
<p>All tests resulted in the same numbers &#8211; network latency was the deciding factor.  Sorry for not having the exact metrics on this one.</p>
<h1>Conclusion</h1>
<p>So what does all this mean?  I think it means that just using the simple <code>GParsPool.withPool</code> structure to iterate over a collection is perfectly fine for our needs.  We could optimize a bit with different structures and a pre-existing pool, but it honestly won&#8217;t make a bit of difference in real performance given that network latency is the deciding factor for us.  Your mileage may vary, especially if you are running an open server that has higher load requirements. </p>
]]></content:encoded>
			<wfw:commentRss>http://swordsystems.com/2011/08/29/gpars-performance-test/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

