Author Archive

New Grails Book by Burt Beckwith

September 27th, 2012 No comments

My new position doesn’t offer me as much opportunity to use Grails as I would like, but jumped at this chance to learn more about it from one of the masters. Programming Grails is early release, but reviews are positive for the details about how grails uses spring and hibernate (and other persistence mechanisms). I just picked up a copy from O’Reilly. Used this discount code to get 50% off – AUTHD. I love

Now we’ll see if I ever get around to readying it.

Categories: grails Tags:

Grails 2 Unit Tests – Undocumented Properties

May 15th, 2012 No comments

GrailsUnitTestMixin (and its descendents DomainClassUnitTestMixin, ServiceUnitTestMixin, etc) give your test classes some static and instance variables that aren’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 for free. The mixin also implements the shouldFail method from GroovyTestCase so you can keep that functionality even though your tests are now JUnit 4 based.

Categories: grails, Testing, unit test Tags: ,

Grails 2 Unit Tests – Using Base Classes

May 15th, 2012 No comments

I’ve been meaning to write up my experiences with upgrading a 1.x app to grails 2 for two months now. Since I can’t seem to find the time to do a large post, I’ll follow MrHaki’s example and sprinkle some nuggets of wisdom around. Here’s a couple of bits on the new unit testing components.

First, read Ted Naleid‘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.

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 @Before. Instead, turn your base class into a generic POGO and then use the @TestMixin annotation to include it in your tests.

class MyAppTestSupport {
    //...useful common properties and methods here....

Then in your test class:

class MyDomainClassTests {
    //you can access the properties and methods from MyAppTestSupport here just as 
    //if they were part of your class

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.

Categories: grails, Testing, unit test Tags:

No Fluff Just Stuff and CANI

May 2nd, 2012 No comments

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’t a single Grails presentation, though Grails was mentioned by several presenters. It seems to have slipped into the area of “we’ll assume you are using Grails if you can since it makes your life much easier” category for now.

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 Backbone or Spine 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’s JavaScript Libraries You Aren’t Using…Yet presentation is a great overview of some of the most popular libraries.

I must say that the body parts theme is getting a bit out of hand. Besides backbone and spine, there are the templating libraries mustache and handlebars. Walmart has developed backbone extensions called thorax and lumbar. Since CoffeScript is also a part of this mix, I thought I should take this whole clever name scheme to the next level -

I hereby announce the CANIjs library – Caffeinated Nerve Impulses ™. I don’t know what it’s going to do yet, but as soon as the jitters where off, I’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 “That’s un-cani.”

Categories: grails, javascript, REST Tags: , ,

Grails Plugins Presentation

February 17th, 2012 No comments

I presented at the DC GUG meeting a couple of days ago, this time on Grails plugins. I wanted to go beyond the normal “these are the basics of Grails” 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’ll have another opportunity to present it so I can tune it up a bit. For now, the slides are on slideshare and the basis for the sample project is on github. I’ll try to breakout the key points into individual posts soon.

Categories: grails, groovy Tags: , ,

Spring security: CAS + LDAP

December 21st, 2011 No comments

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. However, there are two mildly annoying issues with the plugin as a whole:

First, once it is installed, you can’t turn it off (at least, not in development mode). The value of the setting is ignored unless you deploy as a war. There is already a bug 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’s copy of the plugin.

The second issue relates to auto-creating user accounts. I posted 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 userDetailsService so you get the default GormUserDetailsService. That class will throw a “user not found” exception if there is no local user domain object for the given user name. If you have no need for role information (authorities in spring-security speak), then you can simply plug in a simplistic userDetailsService like this one:

import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils

 * 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)

You could extend InMemoryUserDetailsManager if you didn’t want to re-create the UserDetails all the time, or wrap a GormUserDetailsService 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.

LDAP Integration

If you do need role information from LDAP, you will need to add a few more beans to your resources.groovy file. Someone posted a thread 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 resources.groovy:

    // 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 ( {
        def config = SpringSecurityUtils.securityConfig
        if (config.ldap.context.server) {
            SpringSecurityUtils.loadSecondaryConfig 'DefaultLdapSecurityConfig'
            config = SpringSecurityUtils.securityConfig

                userDn = config.ldap.context.managerDn
                password = config.ldap.context.managerPassword


                  groupRoleAttribute = config.ldap.authorities.groupRoleAttribute
                  groupSearchFilter = config.ldap.authorities.groupSearchFilter
                  searchSubtree = config.ldap.authorities.searchSubtree
                  rolePrefix = "ROLE_"
                  convertToUpperCase = config.ldap.mapper.convertToUpperCase
                  ignorePartialResultException = config.ldap.authorities.ignorePartialResultException

        else {
            //Dummy service if LDAP isn't set up

Ideally, I would like to be able to keep the LDAP plugin turned on in an “authorization only” mode so that I could use the userDetailsService 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.

I am Alanis Morissette

December 15th, 2011 No comments

Isn’t it ironic that one of your posts attracts the attention of a grails guru…and it’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’t get WP-Spamfree to properly generate a log telling me why it blogged him.

Categories: Uncategorized Tags:

Auto-create User Domain Object with Spring Security

December 12th, 2011 No comments

For those who skip straight to the last page of a book to see how it ends – See Chap 7. Events of the spring-security-core plugin documentation.

For those who like a little more detail…

I just moved our grails app from using the shiro plugin to using the spring-security plugin(s). I like shiro’s filter-based config, but all the pre-built extension modules that Burt Beckwith has put together for spring-security (LDAP, CAS, etc.) makes it much easier for us to support the range of environments in which we have to deploy.

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 MyUser 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 MyUser 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’t a central, post-authentication landing point.

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 UserDetailsService. There are several posts on the web that discuss creating a custom UserDetails object and a corresponding service for it, so this was the first approach I looked at. Chapter 11 of the spring-security-core plugin’s user guide has info on it as well. The primary shortcoming is that you can’t chain together UserDetailsServices. You have to implement one for each form of authentication with which you want to work.

If your app must work with a variety of authentication methods, it is easier to register a listener with Spring Security. Chapter 7 of the plugin guide discusses the two ways to do this. I found that handling the AuthenticationSuccessEvent was all I needed. Since we already had a Grail’s service that handles various user-related tasks, the listener object was dirt simple:

import org.springframework.beans.factory.InitializingBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.ApplicationListener

class MyAuthenticationEventListener implements ApplicationListener<AuthenticationSuccessEvent>, 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. 

Since the whole class really just has one line of “functional” 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 Config.groovy file.

Then, within the UserService.createUser method, the key lines look something like this:

    def user = MyUser.findByUsername(userDetails.username)
    if (!user)
        MyUser.withTransaction {status ->
            user = new MyUser(username:userDetails.username /*, set any other props you want to store locally*/)
   true, failOnError:true)
    return user

One note of interest – without the withTransaction statement, you may get an exception stating that no hibernate session exists and one cannot be opened. The withTransaction closure wraps this up nicely for you.

More Parallel Processing in Jenkins Notes

October 31st, 2011 No comments

October must be my month to think about CI testing. Unfortunately, I haven’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 “job pyramid” 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’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.

Random Tips

  • I installed the HTML Publisher plugin to view the codenarc reports until I could figure out why the Violations plugin doesn’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.
  • 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 target/test-reports 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.
  • 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.
  • Turned on the log parsing plugin. Would be handy if it shipped with a default rules parsing file, but nice none-the-less.
  • Downstream builds report plugin – Doesn’t really provide any new info when only have a single layer of downstream jobs
  • Groovy plugin – 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. $SHARED_SCRIPTS/some_script.groovy), the plugin would assume the path was relative to the workspace. I had to insert an extra “/” in the “Groovy script file” space (e.g. /$SHARED_SCRIPTS/some_script.groovy) for the plugin to realize it was an absolute path.
  • Like the codenarc tool, the JSUnit ant tool will fail unless the parent directory of the output directory has not already been created.
  • Increase your quiet time if you often check in groups of files using multiple commits
  • 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
  • There is a time sync problem between servers documented in the sonatype blog. The article says to use VMWare Tools to sync time on VM with the ESX server. Unfortunately, it our own ESX server’s time is about 25 minutes slow, so that causes problems of it’s own.
  • 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: -coverage -xml -unit -integration. If you try to do something like this: -unit -integration -coverage -xml, mvn/grails will think that you want to only execute an integration test named “-coverageTests” and it will also give you an error because it doesn’t understand the -xml parameter on it’s own. (Yes, I know this is the old syntax form for running grails tests. I haven’t tried with the newer form.)
  • If you clone a downstream project, the build trigger to run when the upstream project completes is not cloned with it
  • You can’t set a build to a better result than it already has. i.e. if it’s FAILED, you can’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.
  • 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’t get the nice closure-renaming in the file-level stats from the grails plugin. So you see things like MyController$_closure2... You can still see what lines are covered or not right below the stats, so this isn’t a huge issue.
  • 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’t start copying the workspace archive until after the master completes the next build, you could get the wrong archive. You also can’t fingerprint it. At least, I don’t think you can.

Syncing Builds

I setup the full “job diamond” as a mentioned in my last post 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’t do “last successful build” 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.

The solution I came up with was to have the join trigger call two sub-triggers

  1. Aggregate archived artifacts – grab the artifacts you need from the primary downstream jobs. In my case, I wanted to get the test reports.
  2. Parametrized build trigger – 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.)

Then, in the join-job

  1. Define a string parameter to accept the passed in build number.
  2. In the build steps, create a “Copy artifacts” step, set it to get a specific build, and then set the build parameter name as the value
Categories: Testing Tags: ,

GPars Quick Hits

September 28th, 2011 No comments

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’ll post up some of the coding examples when I get a chance.

Categories: groovy Tags: ,