<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Man Builds Website</title>
	<atom:link href="http://manbuildswebsite.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://manbuildswebsite.com</link>
	<description>Real Life Software Development</description>
	<lastBuildDate>Wed, 09 May 2012 10:00:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='manbuildswebsite.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Man Builds Website</title>
		<link>http://manbuildswebsite.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://manbuildswebsite.com/osd.xml" title="Man Builds Website" />
	<atom:link rel='hub' href='http://manbuildswebsite.com/?pushpress=hub'/>
		<item>
		<title>Unit Test Patterns: The Domain Test Values Class</title>
		<link>http://manbuildswebsite.com/2010/12/20/domain-test-values/</link>
		<comments>http://manbuildswebsite.com/2010/12/20/domain-test-values/#comments</comments>
		<pubDate>Mon, 20 Dec 2010 21:31:04 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://manbuildswebsite.com/?p=228</guid>
		<description><![CDATA[The purpose of the domain test values class pattern is to provide values used in the testing of a domain in a way which adds to the understanding of tests by improving readability and adding meaning to values in a general way.
We've found that by using the domain test values class pattern we've improved the readability and therefore the understanding and maintainability of our test code for very little effort.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=228&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>On my latest Java project, my colleagues and I are keen to improve the readability of test classes. We&#8217;ve chosen to use <a href="http://mockito.org/">Mockito</a> and <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> because of their natural language approach to mocking and assertions, but on their own they can&#8217;t always convey the meaning of <em>values</em> used in a test.</p>
<p>To overcome this, we use a pattern which I&#8217;ll call the &#8220;Domain Test Values Class&#8221;,  the purpose of which is to provide values used in the testing of a domain in a way which improves understanding of test code by increasing readability and adding meaning to values.</p>
<h2><span id="more-228"></span>Natural language in tests</h2>
<p>Mockito and Hamcrest greatly improve test readability by allowing you write tests like this:</p>
<pre>AccountService accountService = mock(AccountService.class);
given(accountService.getBalance(1234567)).willReturn(100.0);

double remainingBalance = accountController.withdraw(1234567, 100.0);

assertThat(remainingBalance, is(0.0));
verify(accountService, never()).markOverdrawn();</pre>
<p>So in these few lines we can see what&#8217;s mocked, that the remaining balance should be 0.0 and that markOverdrawn() should never be called.</p>
<h2>Removing the magic numbers</h2>
<p>We&#8217;re still lacking some clarity because of those <a href="http://en.wikipedia.org/wiki/Magic_number_%28programming%29">magic numbers</a> and it&#8217;s always good practice to replace them with constants:</p>
<pre>final long accountNumber = 1234567L;
final double startingBalance = 100.0;
final double withdrawalAmount = startingBalance;

AccountService accountService = mock(AccountService.class);
given(accountService.getBalance(accountNumber)).willReturn(startingBalance);

double remainingBalance = accountController.withdraw(accountNumber, withdrawalAmount);

assertThat(remainingBalance, is(0.0));
verify(accountService, never()).markOverdrawn();</pre>
<p>Now it&#8217;s more obvious from the code what the numbers mean, but it&#8217;s still not ideal, we don&#8217;t know if it matters that the account number is 1234567. Or if the starting balance has to be 100. Are we right to assume that 0.0 means that the account is empty?</p>
<h2>Adding meaning</h2>
<p>With a little renaming the test not only becomes more readable, but it starts showing more intent:</p>
<pre>final long anAccountNumber = 1234567L;
final double aCreditBalance = 100.0;
final double aZeroBalace = 0.0;

AccountService accountService = mock(AccountService.class);
given(accountService.getBalance(anAccountNumber)).willReturn(aCreditBalance);

double remainingBalance = accountController.withdraw(anAccountNumber, aCreditBalance);

assertThat(remainingBalance, is(aZeroBalance));
verify(accountService, never()).markOverdrawn();</pre>
<p>Now simply by choosing some good names the test is very easily understood, so let&#8217;s apply this more generally:</p>
<h2>The domain test values class</h2>
<p>It&#8217;s not hard to see that some of the values in the example above will be required in other tests in the account domain, so instead of putting them at the top of the method or as constants in just one test, let&#8217;s statically import them and create an AccountDomainTestValues class:</p>
<pre>public class AccountDomainTestValues {
    /**A constant test value*/
    public static final long AN_ACCOUNT_NUMBER = anyAccountNumber();
    /**A constant test value*/
    public static final double A_CREDIT = anyCredit();
    /**A simple constant*/
    public static final double ZERO_BALANCE = 0.0;
    /**A generated value*/
    public static final long anyAccountNumber() {
        //randomly generate an account number
    }

    /**A generated value*/
    public static final long anyCredit() {
        //randomly generate a credit value
    }
}</pre>
<p>As well as constants, the class also provides methods for generating values. Notice the naming convention &#8211; constants are prefixed with &#8220;a&#8221; or &#8220;an&#8221; while methods generating values use &#8220;any&#8221; &#8211; this adds intent to the value:</p>
<ul>
<li>&#8220;any&#8221;: the actual value is not important to the test</li>
<li> &#8220;a&#8221;: the value is fixed and so should be considered important and can be used more than once to mean the same thing during a test</li>
</ul>
<p>For example:</p>
<pre>import static com.manbuildswebsite.AccountDomainTestValues.*;
...

accountService.deposit(AN_ACCOUNT_NUMBER, anyCredit());

assertThat(accountService.isOverdrawn(AN_ACCOUNT_NUMBER), is(false));</pre>
<p>Using the &#8220;any&#8221; methods to populate the constant fields exercises a larger range of values than would otherwise be the case; programmers tend to stick to numbers like 1 or 123, and while randomly generating numbers is not a substitute for testing edge cases, it does ensure a range of real-life values are tested.</p>
<p>We&#8217;ve found that by using the <em>domain test values class </em>pattern we&#8217;ve improved the readability, and so the understanding and maintainability, of our test code for very little effort.</p>
<h2>Disclaimer&#8230;</h2>
<p>This pattern, or something like it, may well have been catalogued  somewhere already, though if it has I&#8217;m yet to  find it, so I present it  here in the hope that it either helps others  or that someone will point  me to a published version of it!</p>
<h6>© 2010 Dave Bower/Man Builds Website</h6>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/228/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/228/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/228/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=228&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/12/20/domain-test-values/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Redirecting to .com (without confusing CloudFoundry&#8230;)</title>
		<link>http://manbuildswebsite.com/2010/09/26/redirecting-to-com-without-confusing-cloudfoundry/</link>
		<comments>http://manbuildswebsite.com/2010/09/26/redirecting-to-com-without-confusing-cloudfoundry/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 15:57:36 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Gotchas]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[.com]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[redirect]]></category>
		<category><![CDATA[www]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=200</guid>
		<description><![CDATA[Redirect requests to multiple domains to your primary address using Grails.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=200&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s a two-for-one today &#8211; a &#8220;gotcha&#8221; and a &#8220;how to&#8221; all rolled into one, this time about redirecting in a Grails filter.</p>
<p>Much like my <a href="/2010/09/06/spring-secutiry-acegi-plugin-and-favicon-permissions/">favicon woes</a> my initial attempt to redirect to a primary domain (a .com without the &#8220;www&#8221; prefix) had some unexpected consequences when deployed to a live server on CloudFoundry &#8211; I started getting warnings that my site had gone down!</p>
<p>In this post I&#8217;ll hopefully save you the panic of CloudFoundry telling you that your site&#8217;s not responding when you try to rationalise your domain names!</p>
<h2><span id="more-200"></span>www? It&#8217;s so last century</h2>
<p>Here&#8217;s the problem: you&#8217;ve got your domain, let&#8217;s say it&#8217;s <a href="http://lourish.com">lourish.com</a> and you want to set up your site so that if people go to <a href="http://www.lourish.com">http://www.lourish.com</a>, they&#8217;re immediately redirected to <a href="http://lourish.com">http://lourish.com</a>, dropping the www.</p>
<p>If you&#8217;ve also been on a spending spree and bought the .org, .co.uk and a host of other domains all of which just point back to your .com site then, without a redirect you&#8217;ll find search engines can list each domain separately, ruining your search ranking.</p>
<h2>(Not) Fixing it with a Filter</h2>
<p>We&#8217;re talking Grails here (though the principles are the same in Java too) so creating a filter to make the redirect work is simple stuff. Here&#8217;s a snippet of code from my filter class:</p>
<pre>    def filters = {
        redirectToDotCom(uri: '/**') {
            before = {
                if(request.serverName != "lourish.com") {
                    def reqUrl = request.requestURL
                    def redirectTo = reqUrl.toString()
                        .replace(request.serverName, "lourish.com")
                    redirect(url: redirectTo)
                    return false
                }
            }
        }
...</pre>
<p>So what we do is</p>
<ol>
<li>Intercept all requests (<code>uri: '/**'/</code>)</li>
<li>Check the server name</li>
<li>If it&#8217;s not the primary .com address (lourish.com), replace the server name in the incoming request with the .com server name</li>
<li>Perform the redirect</li>
</ol>
<p>Simple enough and it works in most cases &#8211; it doesn&#8217;t cope with upper case or request parameters, but then if the redirect works, parameters should never be generated!</p>
<h2>Confusing CloudFoundry</h2>
<p>If you&#8217;re deploying to <a href="http://www.cloudfoundry.com">CloudFoundry</a> you&#8217;ll find that this simple filter causes big problems.</p>
<p>CloudFoundry has a great little monitoring feature which will check that your site&#8217;s up by not only checking your Apache server on localhost port 80 but also your tcserver&#8217;s servlet manager on localhost port 8080 &#8211; testing for a 200 status.</p>
<p>But take a look at what that filter&#8217;s doing, it&#8217;s redirecting absolutely everything to our .com address. This is ok for the Apache test &#8211; the 302 leads to a 200 eventually, but it also affects the call to tcserver on localhost:8080 which should check the management console, but we&#8217;re redirecting to .com:8080 and that port&#8217;s blocked!</p>
<p>So the filter causes a false reading on the monitoring tool and potentially unexpected problems, like the app being restarted to &#8220;fix&#8221; the problem!</p>
<h2>Fixing the Filter</h2>
<p>To fix this we could test the port but the solution I chose was simply to add a few &#8220;pass-through&#8221; urls to the filter:</p>
<pre>    static final List ALLOWED_SERVER_NAMES = ["lourish.com", "localhost", "127.0.0.1"]
    static isLive = Environment.current == Environment.PRODUCTION

    def filters = {
        redirectToDotCom(uri: '/**') {
            before = {
                if (isLive
                        &amp;&amp; !ALLOWED_SERVER_NAMES.contains(request.serverName)){
                    def reqUrl = request.requestURL
                    def redirectTo = reqUrl.toString()
                        .replace(request.serverName, "lourish.com")
                    redirect(url: redirectTo)
                    return false
                }
            }
        }</pre>
<p>I&#8217;ve added <code>ALLOWED_SERVER_NAMES</code> which contains the host names which won&#8217;t be not redirected and I&#8217;ve also added an <code>isLive</code> check to let me test on my beta and local servers without constantly being redirected to the live site!</p>
<p>So that&#8217;s how to redirect to one address in a Grails app and still keep CloudFoundry happy!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/200/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=200&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/09/26/redirecting-to-com-without-confusing-cloudfoundry/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>When localhost is not the same as 127.0.0.1 a MySQL Connection Gotcha</title>
		<link>http://manbuildswebsite.com/2010/09/13/when-localhost-is-not-the-same-as-127-0-0-1-a-mysql-connection-gotcha/</link>
		<comments>http://manbuildswebsite.com/2010/09/13/when-localhost-is-not-the-same-as-127-0-0-1-a-mysql-connection-gotcha/#comments</comments>
		<pubDate>Mon, 13 Sep 2010 10:20:23 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Gotchas]]></category>
		<category><![CDATA[cloudfoundry]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=188</guid>
		<description><![CDATA[Setting up MySQL connection pooling has been standard stuff in server-side apps for as long as I&#8217;ve been writing them, so I was at a loss when, every 5 days or so, my newly deployed app died with this exception: Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=188&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Setting up MySQL connection pooling has been standard stuff in server-side apps for as long as I&#8217;ve been writing them, so I was at a loss when, every 5 days or so, my newly deployed app died with this exception:</p>
<pre>Exception in thread "main" 
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 
Communications link failure

Last packet sent to the server was 0 ms ago.</pre>
<p><span id="more-188"></span>I&#8217;d already set up the driver with what I understood to be the correct reconnection properties &#8211; autoReconnectForPools=true and a validation query &#8211; in my Grails app:</p>
<pre>dataSource {
    dbCreate = "update"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "lourishbeta"
    password = "lourishbeta"
    url = "jdbc:mysql://${System.getProperty("dbHostName",
            "localhost")}/beta?autoReconnectForPools=true"
    properties {
        validationQuery = "select 1"
        maxActive = 150
    }
}</pre>
<p>I initially thought it must be something to do with the (generally very reliable) CloudFoundry dropping the connection, but eventually I came upon <a href="http://forums.mysql.com/read.php?39,199085,199085#msg-199085" target="_blank">this enormous thread</a> on the MySQL forums which, in a very, very roundabout way gave the solution:</p>
<p><strong>Use 127.0.0.1 instead of localhost.</strong></p>
<p>So now my datasource looks like this:</p>
<pre>dataSource {
    dbCreate = "update"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "lourishbeta"
    password = "lourishbeta"
    url = "jdbc:mysql://${System.getProperty("dbHostName",
            "127.0.0.1")}/beta?autoReconnectForPools=true"
    properties {
        validationQuery = "select 1"
        maxActive = 150
    }
}</pre>
<p>And the MySQL connection has been up for over 2 weeks. Phew!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/188/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/188/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=188&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/09/13/when-localhost-is-not-the-same-as-127-0-0-1-a-mysql-connection-gotcha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Spring Secutiry (ACEGI) Plugin and Favicon Permissions</title>
		<link>http://manbuildswebsite.com/2010/09/06/spring-secutiry-acegi-plugin-and-favicon-permissions/</link>
		<comments>http://manbuildswebsite.com/2010/09/06/spring-secutiry-acegi-plugin-and-favicon-permissions/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 09:58:22 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Gotchas]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[acegi]]></category>
		<category><![CDATA[favicon]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[spring security]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=184</guid>
		<description><![CDATA[Here&#8217;s a quick gotcha for you. You set up a favicon in the root of your web app, as is the convention, and when you log in you are redirected to a picture of your favicon or you are asked to download it&#8230; Weird. Odds on you&#8217;ve installed the Spring Security plugin and forgotten to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=184&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a quick gotcha for you. You set up a favicon in the root of your web app, as is the convention, and when you log in you are redirected to a picture of your favicon or you are asked to download it&#8230; Weird.</p>
<p>Odds on you&#8217;ve installed the Spring Security plugin and forgotten to give permission to the favicon file in the root and the result is that on login Spring Security redirects you to the first restricted item that was requested by the browser &#8211; the favicon.</p>
<p>The solution? Easy, set the favicon path to IS_AUTHENTICATED_ANONYMOUSLY in your SecurityConfig.groovy (or database):</p>
<pre>controllerAnnotationStaticRules = [
    ...
    '/favicon.ico' : ['IS_AUTHENTICATED_ANONYMOUSLY'],
    ...
]</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/184/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/184/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/184/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=184&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/09/06/spring-secutiry-acegi-plugin-and-favicon-permissions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Handling Embedded Fonts in the Grails UI-Performance Plugin</title>
		<link>http://manbuildswebsite.com/2010/08/31/handling-embedded-fonts-in-the-grails-ui-performance-plugin/</link>
		<comments>http://manbuildswebsite.com/2010/08/31/handling-embedded-fonts-in-the-grails-ui-performance-plugin/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 09:47:24 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[ui-performance]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=178</guid>
		<description><![CDATA[I&#8217;ve been waiting for the time to give Burt Beckwith&#8217;s fantastic UI-Performance plugin a proper post, but it looks like it&#8217;s not going to happen any time soon so I thought some of you might find this tip for getting the plugin to cache font files, along with images and css, useful. Brief Background For [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=178&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been waiting for the time to give Burt Beckwith&#8217;s fantastic <a href="http://grails.org/plugin/ui-performance" target="_blank">UI-Performance plugin</a> a proper post, but it looks like it&#8217;s not going to happen any time soon so I thought some of you might find this tip for getting the plugin to cache font files, along with images and css, useful.</p>
<h3><span id="more-178"></span>Brief Background</h3>
<p>For those who are unaware of the <a href="http://grails.org/plugin/ui-performance" target="_blank">UI-Performance plugin,</a> it provides a set of easy-to-implement performance improvements for Web applications, based on the &#8220;<a href="http://stevesouders.com/hpws/rules.php" target="_blank">14 rules</a>&#8221; from Steve Souders of Yahoo!. These involve such things as compressing content by zipping, setting expires headers, moving Javascript to the bottom of pages and more.</p>
<h3>Easy to Implement</h3>
<p>The plugin is extraordinarily easy to use in an existing Web app and I was up and running within a couple of hours of downloading &#8211; with dramatic performance improvements to my page load times.</p>
<h3>Extending to Embedded CSS Font Files</h3>
<p>As with many current websites I&#8217;ve been using embedded fonts and it wasn&#8217;t immediately obvious how to get the UI-Performance plugin to configure font files for caching, however a bit of experimentation showed that it was, in fact, dead easy!</p>
<p>There is a configuration property for the file extensions the plugin will set up for caching and all you need do is add the font suffixes &#8220;woff&#8221;, &#8220;ttf&#8221;, &#8220;svg&#8221; and &#8220;eot&#8221;, so that your Config.groovy has the line:</p>
<p><code><br />
uiperformance.imageExtensions=['gif', 'jpg', 'png', 'woff', 'ttf', 'svg', 'eot']<br />
</code></p>
<p>And that&#8217;s it! The same principle applies to any other file types you may be referencing in your CSS (whatever they may be!).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/178/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/178/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/178/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=178&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/08/31/handling-embedded-fonts-in-the-grails-ui-performance-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Upgrading Grails from 1.2.2 to 1.3.1</title>
		<link>http://manbuildswebsite.com/2010/06/16/upgrading-grails-from-1-2-2-to-1-3-1/</link>
		<comments>http://manbuildswebsite.com/2010/06/16/upgrading-grails-from-1-2-2-to-1-3-1/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 21:52:33 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Gotchas]]></category>
		<category><![CDATA[controllers]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[upgrade]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=163</guid>
		<description><![CDATA[The usually simple upgrade process in Grails has caused me a few headaches in moving from 1.2.2 to 1.3.1. I skipped the 1.3 upgrade because there were a few people having issues on the mailing list but yesterday I bit the bullet and encountered a couple of problems. I think the release notes for Grails [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=163&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The usually simple upgrade process in Grails has caused me a few headaches in moving from 1.2.2 to 1.3.1. I skipped the 1.3 upgrade because there were a few people having issues on the mailing list but yesterday I bit the bullet and encountered a couple of problems.</p>
<p>I think the release notes for Grails 1.3.x have been unusually poor so this post has the issues I&#8217;ve encountered in the hope that you won&#8217;t go quite as mad as I have. I&#8217;ll keep it updated if I find more problems. <span id="more-163"></span></p>
<h2>Controller defaultAction must now be static</h2>
<p>Not much more to say, but if like me you&#8217;ve been doing this in your controllers:</p>
<p><pre class="brush: groovy;">
    def defaultAction = &quot;open&quot;
</pre></p>
<p>you&#8217;ll need to do this instead:</p>
<p><pre class="brush: groovy;">
    static defaultAction = &quot;open&quot;
</pre></p>
<p>Otherwise you&#8217;ll get a tomcat 404 error saying that &#8220;resource() is not available&#8221;</pre>
<h2>Missing dependencies</h2>
<p>Now I can't say if this was me doing something wrong or a problem with the upgrade process, but when I tried to run my app for the first time I got all sorts of dependency problems. I don't use Maven, or any Maven repos (in fact I don't like Maven, but that's another post for another day) but I was getting lots of Maven output suggesting lookups for every dependency were being made to a remote repo.</p>
<p>I eventually solved the problem by adding grailsCentral() to my repositories in the build.config, quite why it wasn't there in the first place I don't know:</p>
<p><pre class="brush: groovy;">
grails.project.class.dir = &quot;target/classes&quot;
grails.project.test.class.dir = &quot;target/test-classes&quot;
grails.project.test.reports.dir = &quot;target/test-reports&quot;
grails.project.dependency.resolution = {

    inherits(&quot;global&quot;) {
    }
    log &quot;warn&quot; // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    repositories {
        grailsPlugins()
        grailsHome()
        grailsCentral()
    }
    dependencies {
        runtime 'mysql:mysql-connector-java:5.1.5'
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=163&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/06/16/upgrading-grails-from-1-2-2-to-1-3-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Forcing No Selection on a Grails datePicker</title>
		<link>http://manbuildswebsite.com/2010/04/14/forcing-no-selection-on-a-grails-datepicker/</link>
		<comments>http://manbuildswebsite.com/2010/04/14/forcing-no-selection-on-a-grails-datepicker/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 16:21:41 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Gotchas]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[datePicker]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[gsp]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=157</guid>
		<description><![CDATA[I just came across this problem using the datePicker tag in a gsp &#8211; it appeared that there was no way to stop the tag showing today&#8217;s date when no value was set on the bean. My tag looked like this: &#60;g:datePicker name="myDate" value="${myBean.aDate}" precision="day" years="${[2009, 2010, 2011]}" noSelection="${['':'--']}"/&#62; Whenever myBean.aDate was null the tag [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=157&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I just came across this problem using the datePicker tag in a gsp &#8211; it appeared that there was no way to stop the tag showing today&#8217;s date when no value was set on the bean. <span id="more-157"></span></p>
<p>My tag looked like this:</p>
<pre>&lt;g:datePicker name="myDate"
    value="${myBean.aDate}"
    precision="day"
    years="${[2009, 2010, 2011]}"
    noSelection="${['':'--']}"/&gt;
</pre>
<p>Whenever myBean.aDate was null the tag still displayed today&#8217;s date and no matter how I read the <a href="http://grails.org/doc/latest/ref/Tags/datePicker.html">datePicker docs</a> there seemed to be no solution, that is until I happened upon a <a href="http://osdir.com/ml/lang.groovy.grails.user/2007-03/msg00231.html">mailing list post </a>which showed a &#8220;default&#8221; attribute:</p>
<pre>&lt;g:datePicker name="myDate"
    value="${myBean.aDate}"
    precision="day"
    years="${[2009, 2010, 2011]}"
    noSelection="${['':'--']}"
    default="none"/&gt;
</pre>
<p>The addition of &#8220;default=none&#8221; stops the tag showing today&#8217;s date and instead reverts to the noSelection value as I had originally expected. I have no idea what other values this &#8220;default&#8221; attribute can take, or where the code that reads it is in the Grails source (a search for datePicker in the source yielded nothing useful) so I can&#8217;t say anything more about it!</p>
<p>As soon as the Grails JIRA is back up (under maintenance at the moment, apparently) I&#8217;ll raise a bug on the docs.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/157/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/157/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/157/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=157&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/04/14/forcing-no-selection-on-a-grails-datepicker/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Sending Asynchronous HTML Email in Grails with ActiveMQ, JMS and Gmail</title>
		<link>http://manbuildswebsite.com/2010/04/02/sending-asynchronous-html-email-in-grails-with-activemq-jms-and-gmail/</link>
		<comments>http://manbuildswebsite.com/2010/04/02/sending-asynchronous-html-email-in-grails-with-activemq-jms-and-gmail/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 15:00:40 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[activemq]]></category>
		<category><![CDATA[gmail]]></category>
		<category><![CDATA[jms]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=147</guid>
		<description><![CDATA[Sending email asynchronously is an essential part of most Web applications and there are many ways in which to implement it. In this post I&#8217;ve chosen to demonstrate how to set up JMS, ActiveMQ and Gmail with the Grails Mail plugin to provide asynchronous email capabilities while only having to write a few lines of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=147&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Sending email asynchronously is an essential part of most Web applications and there are many ways in which to implement it. In this post I&#8217;ve chosen to demonstrate how to set up JMS, ActiveMQ and Gmail with the Grails Mail plugin to provide asynchronous email capabilities while only having to write a few lines of code, all thanks to some great plugins. I&#8217;ll also show the fantastic Grails Mail templating feature which uses GSP views to generate HTML emails along with a solution for one of the big bugs with it too!</p>
<p><span id="more-147"></span></p>
<h2>Design</h2>
<p>Below is an overview of the system I&#8217;ll be building.</p>
<div id="attachment_150" class="wp-caption aligncenter" style="width: 490px"><a href="http://lourish.files.wordpress.com/2010/04/async-mail-overview.png"><img class="size-full wp-image-150" title="Grails Asynchronous Mail Design Overview" src="http://lourish.files.wordpress.com/2010/04/async-mail-overview.png?w=480&h=221" alt="Design Overview" width="480" height="221" /></a><p class="wp-caption-text">Design Overview</p></div>
<p>The EmailService handles the synchronous part of sending (queueing, adapting, formatting), the SendMailQueue is ActiveMQ via JMS and the SendMailService handles the background sending of the email using the Grails Mail plugin connecting to Gmail over SMTPS/SSL.</p>
<h2>Setup</h2>
<p>You will need <a href="http://grails.org/">Grails</a> 1.2.x or newer and these plugins:</p>
<ul>
<li><a href="http://www.grails.org/JMS+Plugin">JMS</a></li>
<li><a href="http://www.grails.org/ActiveMQ+Plugin">ActiveMQ </a></li>
<li><a href="http://www.grails.org/Mail+plugin">Mail</a></li>
</ul>
<p>You will also need a Gmail account if you want to reproduce this entire tutorial. I set up a premium account but the configuration should be the same for a free account.</p>
<h2>Configuration</h2>
<p>Most of the effort is in getting the configuration right, and it&#8217;s not really any work at all as I&#8217;ve worked it out for you! We just need to set up an ActiveMQ Spring bean as our JMS provider and configure the mail plugin to use a Gmail account.</p>
<h3>Spring Configuration</h3>
<p>If you don&#8217;t have an external ActiveMQ server you&#8217;ll need to set up a local one by adding a connection factory bean. In the following example I also set up a connection pool to improve performance (otherwise there&#8217;s a performance hit on every message sent). Just add this to Resources.groovy:</p>
<pre>beans = {
    jmsConnectionFactory(org.apache.activemq.pool.PooledConnectionFactory){bean -&gt;
        bean.destroyMethod ="stop"
        connectionFactory(org.apache.activemq.ActiveMQConnectionFactory) {
            brokerURL = "tcp://localhost:61616"
        }
    }
}</pre>
<h3>JavaMail settings for Gmail</h3>
<p>There is a huge amount of conflicting information about how JavaMail should be configured for Gmail, it&#8217;s an interesting case as it requires an SSL connection, rather than a plain SMTP one. However, I can guarantee that the following settings work for the Grails Mail plugin (and therefore also for Spring&#8217;s SimpleMailMessage) with a Gmail account.</p>
<p>In Config.groovy add the following (and replace the username and password with your own!):</p>
<pre>grails.mail.host = "smtp.gmail.com"
grails.mail.from = "address@mydomain.com"
grails.mail.port = "465"
grails.mail.username = "user@mydomain.com"
grails.mail.password = "mypassword"
grails.mail.props = ["mail.smtp.auth": "true",
        "mail.smtp.socketFactory.port": "465",
        "mail.smtp.socketFactory.class": "javax.net.ssl.SSLSocketFactory",
        "mail.smtp.socketFactory.fallback": "false",
        "mail.smtp.starttls.enable": "true",
        "mail.debug": "true"]</pre>
<p>The last item in the props setting &#8211; mail.debug &#8211; provides some useful logging, more on that below, but you can remove it when you have it working.</p>
<p>Of course, it&#8217;s unlikely that you&#8217;ll have the same mail server for dev, test and prod so you can set up different environment configurations:</p>
<pre>environments {
    production {
        grails.mail.host = "smtp.gmail.com"
        grails.mail.port = "465"
        grails.mail.username = "user@mydomain.com"
        grails.mail.password = "mypassword"
        grails.mail.props = ["mail.smtp.auth": "true",
                "mail.smtp.socketFactory.port": "465",
                "mail.smtp.socketFactory.class": "javax.net.ssl.SSLSocketFactory",
                "mail.smtp.socketFactory.fallback": "false",
                "mail.smtp.starttls.enable": "true",
                "mail.debug": "true"]

    }
    development {
        grails.mail.host = "smtp.gmail.com"
        grails.mail.port = "465"
        grails.mail.username = "devuser@mydevdomain.com"
        grails.mail.password = "mydevpassword"
        grails.mail.props = ["mail.smtp.auth": "true",
                "mail.smtp.socketFactory.port": "465",
                "mail.smtp.socketFactory.class": "javax.net.ssl.SSLSocketFactory",
                "mail.smtp.socketFactory.fallback": "false",
                "mail.smtp.starttls.enable": "true",
                "mail.debug": "true"]
    }
}</pre>
<p>You may be tempted to add the config like this:</p>
<pre>development {
        grails {
            mail {
                host = "smtp.gmail.com"
                port = ...</pre>
<p>Don&#8217;t! By defining a &#8220;grails&#8221; closure you will clear all previously defined settings for the &#8220;grails&#8221; key!</p>
<h2>Implementing the Services</h2>
<p>We&#8217;re almost finished and we haven&#8217;t yet written a line of real code! Let&#8217;s start with the EmailService which will help us queue the messages:</p>
<h3>EmailService</h3>
<p>Let&#8217;s create a new non-transactional service named EmailService, in this service we could add any request processing, security checks and adapt the request for queuing.</p>
<pre>package lourish

class EmailService {

    boolean transactional = false

    def sendEmail(attrs) {
        sendJMSMessage("sendMail",
                [to: attrs.to,
                 from: attrs.from,
                 subject: attrs.subject,
                 view: attrs.view,
                 model: attrs.model])
    }
}</pre>
<p>This service method is just one call to sendJMSMessage (a meta-method added to all services and controllers by the JMS plugin). The first argument is the queue name we&#8217;re sending to and the second is the JMS message itself, in this case a map defining the email to send.</p>
<p>Make sure that everything you send over an ActiveMQ queue is a  primitive type, map or list &#8211; it ought to be possible to send  serializable objects but in my experience it simply doesn&#8217;t work!</p>
<h3>SendMailService</h3>
<p>The JMS plugin is set up to deliver messages to any service &#8220;exposed&#8221; to JMS which has the same name as the queue the message is on. So in the EmailService we send the message on the sendMail queue so the JMS plugin will try to find a service named SendMailService and call its onMessage method:</p>
<pre>package lourish

class SendMailService {
    boolean transactional = false

    //Tell the JMS plugin that this is a message endpoint
    static expose = ['jms']

    //The Mail plugin service
    def mailService

    def onMessage(emailMessage) {
        try {
            mailService.sendMail {
                to emailMessage.to
                from emailMessage.from
                subject emailMessage.subject
                body(view: emailMessage.view, model: emailMessage.model)

            }
        } catch (Exception e) {
            log.error("Failed to send email ${emailMessage}", e)
        }
        //Return null to avoid poison messages
        return null
    }
}</pre>
<p>Notice that the onMessage method is returning null &#8211; this is important as it tells the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jms.html#jms-receiving-async-message-listener-adapter">MessageListenerAdapter</a> that the method has run successfully. If you return anything else it will be assumed it&#8217;s a retry message and you could end up with a poison messaged in your queue.</p>
<p>Also note that the &#8220;mailService&#8221; bean is set up by the Mail plugin and there are more details in the plugin documentation about how it works.</p>
<h3>HTML Templates</h3>
<p>As we&#8217;re sending HTML emails we need to create a template GSP for the message body as defined in the &#8220;view&#8221; parameter of the JMS message. Create the following helloWorld.gsp template in grails-app/views/emails:</p>
<pre>&lt;%@ page contentType="text/html" %&gt;
&lt;html&gt;
&lt;body&gt;&lt;h1&gt;${greeting}&lt;/h1&gt;&lt;/body&gt;
&lt;/html&gt;</pre>
<p>I&#8217;d recommend a good read of the <a href="http://www.grails.org/Mail+plugin">Mail plugin</a> and <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jms.html">Spring JMS</a> docs for full details. Bear in mind that the email templates don&#8217;t support sitemesh layouts.</p>
<h2>Sending a Mail</h2>
<p>That&#8217;s the services created and the system configured so we can try it out.</p>
<h3>An Example Controller</h3>
<p>Here&#8217;s an example of a controller to send a test email to demonstrate how the whole thing works:</p>
<pre>package lourish

class SendMailController {
    //Our email queuing service
    def emailService

    def index = {
        try {
            emailService.send(to: "myemail@emailaddress.com",
                from: "me@gmail.com",
                subject: "Test HTML mail using JMS, ActiveMQ, and the Grails Mail plugin",
                model: [greeting: "Hello World!"],
                view: "/emails/helloWorld")

        } catch (Exception e) {
            log.error("${e}", e)
            flash.message = "Mail not sent: ${e}"
            return
        }
        flash.message = "Mail sent"
    }
}</pre>
<p>and a corresponding GSP in views/sendMail/index.gsp:</p>
<pre>&lt;%@ page contentType="text/html;charset=UTF-8" %&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Mail Test&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;${flash.message}&lt;/body&gt;
&lt;/html&gt;</pre>
<p>You can now run the app and browse to /sendMail to send an email.</p>
<h3>Debug</h3>
<p>When you run the app, you should not only receive an email but you should also see some logging from Java mail if you have the debug in. It will look a bit like this:</p>
<pre>DEBUG: JavaMail version 1.4.1
DEBUG: not loading file: C:\java\jdk1.6.0_16\jre\lib\javamail.providers
DEBUG: java.io.FileNotFoundException: C:\java\jdk1.6.0_16\jre\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: not loading file: C:\java\jdk1.6.0_16\jre\lib\javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\java\jdk1.6.0_16\jre\lib\javamail.address.map (The system cannot find the file specified)</pre>
<p>If it gets to this point and stops, it means that the mailService bean has initialised but sending the mail has failed because of some application issue before connecting to the remote mail server. Note that the exceptions in the logging above are benign if they&#8217;re at DEBUG level so don&#8217;t be confused by them, you&#8217;ll need to check your application logging for the real problem.</p>
<h3>Running in a WAR</h3>
<p><a href="http://jira.codehaus.org/browse/GRAILSPLUGINS-1885 ﻿">There is a bug in the Mail plugin</a> which means that sending mail using templates fails when an application is packaged as a WAR and deployed in a container. The exception you&#8217;ll see is:</p>
<pre>org.springframework.jms.listener.adapter.ListenerExecutionFailedException:
 Listener method 'onMessage' threw exception; nested exception is
  java.lang.NoClassDefFoundError: org/springframework/mock/web/MockHttpServletRequest</pre>
<p>The problem is that the Mail plugin relies on the MockHttpServletRequest class in the spring test jar which is unavailable when running in a WAR, but present when using run-app. To resolve this issue it&#8217;s necessary to add the Spring Framework test jar, in my case $GRAILS_HOME/lib/org.springframework.test-3.0.0.RELEASE.jar, to your lib directory. It&#8217;s an ugly fix, but hopefully it will only be temporary.</p>
<h2>Further Reading</h2>
<p>I hope that I&#8217;ve provided a useful overview of queued email which is suitable for production Web applications. In most large companies the mail server is likely to be local so you probably won&#8217;t have to deal with Gmail, however the concepts remain the same.</p>
<p>For more information on the topics in this post also see:</p>
<ul>
<li><em>Grails Mail Plugin: <a href="http://www.grails.org/Mail+plugin">http://www.grails.org/Mail+plugin</a></em></li>
<li><em>Grails JMS Plugin: <a href="http://www.grails.org/JMS+Plugin">http://www.grails.org/JMS+Plugin</a></em></li>
<li><em>Grails ActiveMQ Plugin: <a href="http://www.grails.org/ActiveMQ+Plugin">http://www.grails.org/ActiveMQ+Plugin</a></em></li>
<li><em>Integrating ActiveMQ with Spring: <a href="http://activemq.apache.org/spring-support.html">http://activemq.apache.org/spring-support.html</a></em></li>
<li><em>Spring JMS support: <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jms.html">http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jms.html</a></em></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/147/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/147/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/147/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/147/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/147/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/147/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/147/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/147/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=147&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/04/02/sending-asynchronous-html-email-in-grails-with-activemq-jms-and-gmail/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>

		<media:content url="http://lourish.files.wordpress.com/2010/04/async-mail-overview.png" medium="image">
			<media:title type="html">Grails Asynchronous Mail Design Overview</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple Aspects using Annotations in Grails</title>
		<link>http://manbuildswebsite.com/2010/03/15/simple-aspects-using-annotations-in-grails/</link>
		<comments>http://manbuildswebsite.com/2010/03/15/simple-aspects-using-annotations-in-grails/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 14:31:09 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[acegi]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring security]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=137</guid>
		<description><![CDATA[Aspect Oriented Programming is a concept which will be familiar to users of the Spring Framework as one of its core features. However, the details of how to get AOP working in Grails appear thin on the ground, so in this post I will show how to set up a simple aspect then configure and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=137&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Aspect Oriented Programming is a concept which will be familiar to users of the Spring Framework as one of its core features. However, the details of how to get AOP working in Grails appear thin on the ground, so in this post I will show how to set up a simple aspect then configure and apply it using attributes. I will assume some familiarity with Spring AOP so I won&#8217;t explain the  terminology or general concepts since they are exactly the same  in  Java as they are in Grails.<span id="more-137"></span></p>
<h2>Building an Aspect Around Spring Security</h2>
<p>In my last post I showed <a href="/2010/03/10/updating-the-logged-in-user-with-acegispring-security-in-grails/">how to update the logged-in user domain object when using the Spring Security plugin</a> &#8211; whenever the user domain object is updated the security context also needs to be  updated as the plugin caches the logged in user. A nice way to implement this cache refresh would be to annotate those methods which update the user domain object; given a UserService with an updateUser method, I want to be able to annotate that method so that the cached domain object is refreshed:</p>
<pre>public class UserService {
    @UpdatesUser
    User updateUser(user) {
        println "updateUser"
    }
}</pre>
<p>To implement this aspect I will follow these 5 steps:</p>
<ol>
<li>Create the UpdatesUser annotation</li>
<li>Create a Spring bean for the &#8216;refreshAuthenticatedUser&#8217; method which will perform the cache refresh</li>
<li>Write a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-pointcuts">pointcut</a> to match the &#8216;join points&#8217; where the user is updated (ie the annotated methods on which the aspect should be applied)</li>
<li>Mark up &#8216;refreshAuthenticatedUser&#8217; with <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-advice">advice </a>so it is called for annotated methods</li>
<li>Configure the Spring container to use the aspect</li>
</ol>
<p>Aspects can be written in Groovy or Java but since this is a Grails post I&#8217;ll show a pure Groovy/Grails example using @AspectJ annotations</p>
<h2>Creating the Annotation</h2>
<p>The noteworthy thing about the annotation is that it needs to be  retained at runtime. Otherwise it&#8217;s very simple and can live in the src/groovy directory:</p>
<pre>package example

import java.lang.annotation.ElementType
import java.lang.annotation.Target
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Retention

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface UpdatesUser {
}</pre>
<h2>Creating a Spring Bean for the Aspect</h2>
<p>Taking the code from my <a href="/2010/03/10/updating-the-logged-in-user-with-acegispring-security-in-grails/">last post</a> to refresh the user cache I can create an aspect using markup:</p>
<pre>package example

import org.springframework.security.context.SecurityContextHolder
import org.springframework.security.providers.UsernamePasswordAuthenticationToken
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserImpl
import org.springframework.security.GrantedAuthorityImpl
import org.springframework.security.GrantedAuthority

@Aspect
@Component("refreshUserAspect")
public class RefreshUserAspect {

    public void refreshAuthenticatedUser(User user){
        GrantedAuthority[] auths = user.authorities.collect {
            new GrantedAuthorityImpl(it.authority)
        }
        def grailsUser = new GrailsUserImpl(
                user.username,
                "",
                user.enabled,
                true,
                true,
                true,
                auths,
                user)
        def authToken = new UsernamePasswordAuthenticationToken(grailsUser, "", auths)
        SecurityContextHolder.context.authentication = authToken
    }
}</pre>
<p>So the only additions to the code are the annotations:</p>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-at-aspectj">@Aspect</a> to allow the framework to auto-create this class as an aspect</li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-stereotype-annotations">@Component</a> tells the framework that this is a Spring bean with the name &#8220;refreshUserAspect&#8221;</li>
</ul>
<h2>Defining a Pointcut</h2>
<p>The <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-pointcuts">pointcut</a> definition tells the framework when the refreshAuthenticatedUser method should be called, in this case it&#8217;s whenever the UpdatesUser annotation is present. The definition will live in the same class as the Aspect:</p>
<pre>@Aspect
@Component("refreshUserAspect")
public class RefreshUserAspect {

    @Pointcut("@annotation(example.UpdatesUser)")
    public void userUpdatingOperation() {
    }

    public void refreshAuthenticatedUser(User user){
...
    }
}</pre>
<p>The pointcut is just an annotated empty method and the UpdatesUser annotation is referenced by its fully qualified class name in the pointcut annotation.</p>
<h2>Declaring the Advice</h2>
<p>An advice declaration relates a pointcut to a method and in this case must also inject the user object into the method.</p>
<p>It looks like this:</p>
<pre>    @AfterReturning(pointcut="example.RefreshUserAspect.userUpdatingOperation()",
            returning="user")
    public void refreshAuthenticatedUser(User user){
...
    }</pre>
<p>It&#8217;s saying:</p>
<ul>
<li>@AfterReturning &#8211; call this method on successful execution of methods</li>
<li>pointcut=&#8221;example.RefreshUserAspect.userUpdatingOperation&#8221; &#8211; attach this advice to methods matched by the pointcut defined on the userUpdatingOperation method of this class</li>
<li>returning=&#8221;user&#8221; &#8211; use the return value of the matched method for the &#8216;user&#8217; argument of this advice</li>
</ul>
<h2>Configuring the Spring Container</h2>
<p>In order for Spring to find the @AspectJ annotated aspect it&#8217;s necessary to define an AnnotationAwareAspectJAutoProxyCreator. It shouldn&#8217;t be needed since Grails 1.2.x but Grails 1.2.1 has a few problems with its aspect support which I will discuss later.</p>
<p>Define the AnnotationAwareAspectJAutoProxyCreator in Resources.groovy:</p>
<pre>import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
import example.aop.SimpleAspect

beans = {
    autoProxyCreator(AnnotationAwareAspectJAutoProxyCreator) {
        proxyTargetClass = true
    }
}</pre>
<p>So the final Aspect looks like this:</p>
<pre>package example

import org.springframework.security.context.SecurityContextHolder
import org.springframework.security.providers.UsernamePasswordAuthenticationToken
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserImpl
import org.springframework.security.GrantedAuthorityImpl
import org.springframework.security.GrantedAuthority

@Aspect
@Component("refreshUserAspect")
public class RefreshUserAspect {

    @Pointcut("@annotation(example.UpdatesUser)")
    public void userUpdatingOperation() {
    }

    @AfterReturning(pointcut="example.RefreshUserAspect.userUpdatingOperation()",
            returning="user")
    public void refreshAuthenticatedUser(User user){
        GrantedAuthority[] auths = user.authorities.collect {
            new GrantedAuthorityImpl(it.authority)
        }
        def grailsUser = new GrailsUserImpl(
                user.username,
                "",
                user.enabled,
                true,
                true,
                true,
                auths,
                user)
        def authToken = new UsernamePasswordAuthenticationToken(grailsUser, "", auths)
        SecurityContextHolder.context.authentication = authToken
    }
}</pre>
<p>Now if the updateUser method in the UserService is annotated:</p>
<pre>public class UserService {
    @UpdatesUser
    User updateUser(user) {
        println "updateUser"
    }
}</pre>
<p>the spring security user object will be refreshed thanks to a call to the aspect&#8217;s @AfterReturning advice. Although this example is quite simple there&#8217;s not much more that is Grails-specific left to know when creating aspects.</p>
<h2>Problems in Grails 1.2.1</h2>
<p>There are a <a href="http://jira.codehaus.org/browse/GRAILS-5932">number of issues </a>with aspect support in Grails 1.2.1 which make working with aspects difficult. Most should be resolved in the 1.2.2 release but I&#8217;ll mention some of them here since they make certain operations impossible.</p>
<h3>Repeat calls to the same advice</h3>
<p>Although the annotation-based pointcuts I&#8217;ve described here work perfectly, other types of pointcuts can cause problems. For example, defining a pointcut as:</p>
<pre>@Pointcut("execution(* example.UserService.updateUser(..))")</pre>
<p>should match the service method and call the advice just the same as the annotation, but what actually happens is that the advice is called more than once for every call to updateUser.</p>
<p>I haven&#8217;t tried all types of <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-pointcuts">pointcut definition</a>, but be aware that other types may suffer from this problem.</p>
<h3>Service methods subject to advice cannot be edited on-the-fly</h3>
<p>Another unfortunate problem is that if a service has a method which is subject to an aspect, changing that service in any way will cause it to be recompiled and future calls to that service method will fail with a CGLIB error when running the application in development (grails run-app):</p>
<pre>java.lang.ClassCastException: example.SimpleService$$EnhancerByCGLIB$$735effdb cannot be cast to example.UserService</pre>
<p>I&#8217;m not sure if this is likely to be fixed in the next version of grails or not.</p>
<h3>@AspectJ annotated aspects are not auto-discovered</h3>
<p>It should be possible to use beans with @AspectJ annotations without creating an AnnotationAwareAspectJAutoProxyCreator, however Grails doesn&#8217;t find the annotated classes so the auto-proxy creator must be manually defined in the Spring resources as described earlier in this post. This should be fixed in Grails 1.2.2.</p>
<h2>The Future</h2>
<p>I&#8217;ll update this post with more information after the next release of Grails, when hopefully some of the problems are resolved, until then I hope this serves as a useful example.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/137/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=137&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/03/15/simple-aspects-using-annotations-in-grails/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
		<item>
		<title>Updating the Logged in User with Acegi/Spring Security in Grails</title>
		<link>http://manbuildswebsite.com/2010/03/10/updating-the-logged-in-user-with-acegispring-security-in-grails/</link>
		<comments>http://manbuildswebsite.com/2010/03/10/updating-the-logged-in-user-with-acegispring-security-in-grails/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 14:36:19 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[HowTo]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring security]]></category>

		<guid isPermaLink="false">http://blog.lourish.com/?p=132</guid>
		<description><![CDATA[Following on from my post on how to log in a user using the Grails Acegi/Spring Security plugin I stumbled into a new use for the same code when I tried to update a user&#8217;s own details while logged in. The security plugin caches the user&#8217;s domain object so any changes are not seen until [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=132&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Following on from my post on <a href="/2010/02/23/how-to-login-a-user-with-the-grails-spring-security-plugin/">how to log in a user using the Grails Acegi/Spring Security plugin</a> I stumbled into a new use for the same code when I tried to update a user&#8217;s own details while logged in. The security plugin caches the user&#8217;s domain object so any changes are not seen until the next login (wholly unhelpful when you&#8217;re trying to implement account management on a Website!).</p>
<p><span id="more-132"></span></p>
<h2>Stop Caching the User Domain Object</h2>
<p>There are a couple of ways to solve this problem, the brute-force approach is to turn off caching of the domain object  so it&#8217;s reloaded on each call. Turning off user caching is simple in the latest version of the <a href="http://www.grails.org/AcegiSecurity+Plugin+-+Customizing+with+SecurityConfig">Spring  Security plugin</a>, just add this line to your SecurityConfig.groovy file:</p>
<pre>cacheUsers = false
</pre>
<h2>Refresh the Authentication Token</h2>
<p>Of course there is a performance hit associated with turning off caching, so instead it&#8217;s much more useful to be able to refresh the domain object only when needed. This can be achieved using the same method as logging in a user when the password is not available, as described in my <a href="/2010/02/23/how-to-login-a-user-with-the-grails-spring-security-plugin/">previous post</a>:</p>
<pre>import org.springframework.security.context.SecurityContextHolder
import org.springframework.security.providers.UsernamePasswordAuthenticationToken
import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserImpl
import org.springframework.security.GrantedAuthority
import org.springframework.security.GrantedAuthorityImpl
...
    private def refreshUserPrincipal(username) {
        def user = User.findByUsername(username)
        GrantedAuthority[] auths = user.authorities.collect {
            new GrantedAuthorityImpl(it.authority)
        }
        def grailsUser = new GrailsUserImpl(
                user.username,
                "",
                true,
                true,
                true,
                true,
                auths,
                user)

        def authToken =  new UsernamePasswordAuthenticationToken(
                grailsUser, '', auths)
        SecurityContextHolder.context.authentication = authToken
    }
</pre>
<p>So by calling the refreshUserPrincipal method after making updates to the user&#8217;s domain object you can maintain the benefits of caching while continuing to use the authenticateService.userDomain object to read up-to-date properties of the user.</p>
<h2>Update</h2>
<p>Also see my post on AOP where I show <a href="/2010/03/15/simple-aspects-using-annotations-in-grails/">how this update method can be extended using aspect oriented programming</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lourish.wordpress.com/132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lourish.wordpress.com/132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lourish.wordpress.com/132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lourish.wordpress.com/132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lourish.wordpress.com/132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lourish.wordpress.com/132/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lourish.wordpress.com/132/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lourish.wordpress.com/132/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=manbuildswebsite.com&#038;blog=10122343&#038;post=132&#038;subd=lourish&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://manbuildswebsite.com/2010/03/10/updating-the-logged-in-user-with-acegispring-security-in-grails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5cc4657ed82518de6796fca6d8e481a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">lourish</media:title>
		</media:content>
	</item>
	</channel>
</rss>
