<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Development Blog</title>
	<atom:link href="http://nedlowe.co.uk/wordpress/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://nedlowe.co.uk/wordpress</link>
	<description>Sharing The Knowledge</description>
	<lastBuildDate>Thu, 18 Feb 2010 15:47:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Dummy Files in Unit Tests</title>
		<link>http://nedlowe.co.uk/wordpress/?p=74</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=74#comments</comments>
		<pubDate>Mon, 15 Feb 2010 13:04:36 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=74</guid>
		<description><![CDATA[Let&#8217;s say that you have an application which accepts a filepath as part of its interface.  When unit testing, you may have some dummy files which you use to test the interface.  
However, getting the full path of these test files can be a pain.
Assuming that the files are (as per Maven conventions) [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s say that you have an application which accepts a filepath as part of its interface.  When unit testing, you may have some dummy files which you use to test the interface.  </p>
<p>However, getting the full path of these test files can be a pain.</p>
<p>Assuming that the files are (as per Maven conventions) in <code>/src/test/resources/</code> then they will be put on the classpath (by default <code>/test-classes/</code> as part of the build process.</p>
<p>If you&#8217;re using Spring, then you can take advantage of that to do the following:</p>
<pre class="brush: java;">
Resource classPathResource = new ClassPathResource(&quot;/simple_dataset.csv&quot;);
String inputFilename = classPathResource.getURI().getPath();
</pre>
<p><code>inputFilename</code> now contains the full path to the file, and can be passed into your application as per normal.</p>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=74</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load a CSV file into an ArrayList</title>
		<link>http://nedlowe.co.uk/wordpress/?p=72</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=72#comments</comments>
		<pubDate>Mon, 15 Feb 2010 12:58:13 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=72</guid>
		<description><![CDATA[It isn&#8217;t hard to write code which iterates through files, cuts them up and loads them into an ArrayList.  And if the delimiting character isn&#8217;t a comma?  No problem, it isn&#8217;t hard to add that functionality.  And if you want to skip the first set of lines because you&#8217;re paginating the file? [...]]]></description>
			<content:encoded><![CDATA[<p>It isn&#8217;t hard to write code which iterates through files, cuts them up and loads them into an <code>ArrayList</code>.  And if the delimiting character isn&#8217;t a comma?  No problem, it isn&#8217;t hard to add that functionality.  And if you want to skip the first set of lines because you&#8217;re paginating the file?  Easy!  And if you want to write some changes back out again &#8211; no problem, I can add that feature in no time.</p>
<p>Except it&#8217;s already been done.  So why waste the time? <img src='http://nedlowe.co.uk/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a href="http://opencsv.sourceforge.net/">OpenCSV</a> is an easy to use library which you can embed into your applications (Apache License).  Then you can simply do something like:</p>
<pre class="brush: java;">
// Loop through file
List&lt;String[]&gt; inputSet = new ArrayList&lt;String[]&gt;();
try {
   CSVReader reader = new CSVReader(new FileReader(inputFilename));
   String[] nextLine;
   try {
	while ((nextLine = reader.readNext()) != null) {
   	  inputSet.add(nextLine);
	}
   } catch (IOException e) {
      // WHATEVER
   }
} catch (FileNotFoundException e) {
   // WHATEVER
}
</pre>
<p>And you&#8217;re done.  See the <a href="http://opencsv.sourceforge.net/">OpenCSV</a> homepage for some of the other features.</p>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=72</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom XStream Converter</title>
		<link>http://nedlowe.co.uk/wordpress/?p=66</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=66#comments</comments>
		<pubDate>Fri, 12 Feb 2010 17:30:23 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=66</guid>
		<description><![CDATA[XStream is a great utility for serializing objects to XML &#8211; and then back again.
The default XML output is neat enough &#8211; albeit a little verbose (using fully qualified class names for example).  There are plenty of tutorials available showing how to use XStream aliases to clean up the output (e.g. Manual Tweaking Output).
However, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://xstream.codehaus.org/">XStream</a> is a great utility for serializing objects to XML &#8211; and then back again.</p>
<p>The default XML output is neat enough &#8211; albeit a little verbose (using fully qualified class names for example).  There are plenty of tutorials available showing how to use XStream aliases to clean up the output (e.g. <a href="http://xstream.codehaus.org/manual-tweaking-output.html">Manual Tweaking Output</a>).</p>
<p>However, sometimes it is not enough to just tweak and alias &#8211; more serious manipulation of the output stream is required.  For example, complicated Collection-based objects come out very cumbersome (but generic &#8211; which is the point).  Luckily, XStream provides a powerful interface for custom generation (A <code>Converter</code> in XStream-speak).</p>
<p>To fully control how an object is serialised, create a new class which implements the <code>Converter</code> interface:</p>
<pre class="brush: java;">
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class MyCustomMapConverter implements Converter {

	@Override
	public void marshal(Object source, HierarchicalStreamWriter writer,
			MarshallingContext context) {
          // TODO
	}

	@Override
	public boolean canConvert(Class clazz) {
		return clazz.equals(ClassToBeConverted.class);
	}

        @Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
          // TODO
	}

}
</pre>
<p>As can be seen above, the <code>canConvert</code> method tells XStream which objects should use this converter.  The other two methods are called when converting objects to XML (<code>marshal</code>) or converting XML to objects (<code>unmarshal</code>).</p>
<p>Marshalling the object is achieved by starting and ending Nodes, while populating their attributes and values.  So for example:</p>
<pre class="brush: java;">
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
  for (RouterConfigRuleMap routerConfigRuleMap : routerConfigRuleMapSet.getRouterConfigRuleMapSet())
  {
	writer.startNode(&quot;routetype&quot;);
	writer.addAttribute(&quot;type&quot;, routerConfigRuleMap.getRouteType().toString());
	writer.endNode();
}
</pre>
<p>will iterate through a collection generating the following output:</p>
<pre class="brush: xml;">
&lt;routetype type=&quot;example&quot; /&gt;
&lt;routetype type=&quot;foo&quot; /&gt;
</pre>
<p>These patterns can become arbitrarily complex.</p>
<p>Unmarshalling is a little more complicated.  XStream will work out which (registered &#8211; see later) Converter to use by matching the node to the class (in my head these seems like an extremely difficult task&#8230; I&#8217;m not sure how XStream has implemented this &#8211; maybe I should look into this!)  The node (and all children) will be passed to the <code>unmarshal</code> method.</p>
<p>It is up to us to define how the target object is populated from these nodes.  Methods are provided to:</p>
<ul>
<li>Check if the node has children (<code>reader.hasMoreChildren()</code>)</li>
<li>Move down to the child level (<code>reader.moveDown()</code>)</li>
<li>Move back up to the parent level (<code>reader.moveUp()</code>)</li>
</ul>
<p>The <code>moveUp/Down</code> methods can be called as many times as necessary to walk the tree.</p>
<p>I provide a full example as I couldn&#8217;t find many good ones on the net:</p>
<pre class="brush: java;">
@Override
public Object unmarshal(HierarchicalStreamReader reader,	UnmarshallingContext context) {

  RouterConfigRuleMapSet routerConfigRuleMapSet = new RouterConfigRuleMapSet();

  while (reader.hasMoreChildren()) {
	reader.moveDown();

	RouterConfigRuleMap routerConfigRuleMap = new RouterConfigRuleMap();
	routerConfigRuleMap.setRouteType(RouteType.valueOf(reader.getAttribute(&quot;type&quot;)));

	while (reader.hasMoreChildren()) {
		reader.moveDown();
		RouterConfigRule routerConfigRule = new RouterConfigRule();

		if (reader.getAttribute(&quot;extractor&quot;) != null) {
			routerConfigRule.setExtractor(reader.getAttribute(&quot;extractor&quot;));
		}

		if (reader.getAttribute(&quot;formatter&quot;) != null) {
			routerConfigRule.setFormatter(reader.getAttribute(&quot;formatter&quot;));
		}

		if (reader.getAttribute(&quot;distributor&quot;) != null) {
			routerConfigRule.setDistributor(reader.getAttribute(&quot;distributor&quot;));
		}

		routerConfigRuleMap.putRouterConfigRule(reader.getAttribute(&quot;name&quot;), routerConfigRule);

		reader.moveUp();
		}
	reader.moveUp();
	routerConfigRuleMapSet.addRouterConfigRuleMapSet(routerConfigRuleMap);
	}
  return routerConfigRuleMapSet;
}
</pre>
<p>Out of completeness, here is the equivalent <code>marshal</code> implementation:</p>
<pre class="brush: java;">
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {

  RouterConfigRuleMapSet routerConfigRuleMapSet = (RouterConfigRuleMapSet)source;
  for (RouterConfigRuleMap routerConfigRuleMap : routerConfigRuleMapSet.getRouterConfigRuleMapSet())
  {
	writer.startNode(&quot;routetype&quot;);
	writer.addAttribute(&quot;type&quot;, routerConfigRuleMap.getRouteType().toString());

	for (Object routerConfig : routerConfigRuleMap.routerConfigRuleMap.entrySet()) {
		Entry&lt;String, RouterConfigRule&gt; entry = (Entry&lt;String, RouterConfigRule&gt;) routerConfig;
		RouterConfigRule routerConfigRule = entry.getValue(); 

		writer.startNode(&quot;routename&quot;);
		writer.addAttribute(&quot;name&quot;, entry.getKey().toString());
		if (routerConfigRule.getExtractor() != null) {
			writer.addAttribute(&quot;extractor&quot;, routerConfigRule.getExtractor());
		}

		if (routerConfigRule.getFormatter() != null) {
			writer.addAttribute(&quot;formatter&quot;, routerConfigRule.getFormatter());
		}

		if (routerConfigRule.getDistributor() != null) {
			writer.addAttribute(&quot;distributor&quot;, routerConfigRule.getDistributor());
		}

		writer.endNode();
	}
	writer.endNode();
  }
}
</pre>
<p>To register the <code>Converter</code> simply add the following line when you instantiate the XStream object:</p>
<pre class="brush: java;">
XStream stream = new XStream();
  stream.registerConverter(new RouterConfigMapConverter()); // NEW LINE
</pre>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=66</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ubuntu Tomcat JasperServer deployment issue</title>
		<link>http://nedlowe.co.uk/wordpress/?p=62</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=62#comments</comments>
		<pubDate>Sat, 30 Jan 2010 09:45:23 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=62</guid>
		<description><![CDATA[I could not get web applications &#8211; in this case JasperServer, but I&#8217;m sure it applies to anything &#8211; placed in /usr/share/tomcat6/webapps/ to autodeploy, and was therefore getting 404 errors.  I am not sure if this is because of the Tomcat install which comes with Ubuntu (which is notoriously bad, although I thought these [...]]]></description>
			<content:encoded><![CDATA[<p>I could not get web applications &#8211; in this case JasperServer, but I&#8217;m sure it applies to anything &#8211; placed in <code>/usr/share/tomcat6/webapps/</code> to autodeploy, and was therefore getting 404 errors.  I am not sure if this is because of the Tomcat install which comes with Ubuntu (which is notoriously bad, although I thought these issues had been resolved?).</p>
<p>The <a href="http://jasperserver.sourceforge.net/docs/3-7-0/JasperServer-CE-Install-Guide.pdf">JasperServer install guide</a> is excellent, but at the end it (correctly) assumes the autodeploy will work, and that browsing to <a href="http://localhost:8080/jasperserver/">http://localhost:8080/jasperserver/</a> will bring up the login page.</p>
<p>To get around this issue, copy <code>/usr/share/tomcat6/webapps/jasperserver/META-INF/context.xml</code> to <code>/etc/tomcat6/Catalina/localhost/jasperserver.xml</code> and restart Tomcat.</p>
<p>Tomcat Version: 6.0.20<br />
Ubuntu Version: 9.0.4</p>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=62</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Log4j and Tomcat issue</title>
		<link>http://nedlowe.co.uk/wordpress/?p=59</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=59#comments</comments>
		<pubDate>Sun, 24 Jan 2010 17:10:13 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=59</guid>
		<description><![CDATA[Quick one &#8211; I had this issue today so wanted to record it for posterity.
Tomcat can get confused if WEB-INF/lib contains the log4j jar, with initialisation errors such as:

java.lang.ClassNotFoundException: org.apache.log4j.Category

You might not even have directly included it &#8211; it might be included via a Maven dependency.
The solution is simple; remove log4j!  It&#8217;s (often) already [...]]]></description>
			<content:encoded><![CDATA[<p>Quick one &#8211; I had this issue today so wanted to record it for posterity.</p>
<p>Tomcat can get confused if WEB-INF/lib contains the log4j jar, with initialisation errors such as:<br />
<code><br />
java.lang.ClassNotFoundException: org.apache.log4j.Category<br />
</code></p>
<p>You might not even have directly included it &#8211; it might be included via a Maven dependency.</p>
<p>The solution is simple; remove log4j!  It&#8217;s (often) already included in Tomcat, which is the root cause of the issues.  If it&#8217;s a Maven dependency, add an exclusion.</p>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=59</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Security 3 Setup</title>
		<link>http://nedlowe.co.uk/wordpress/?p=55</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=55#comments</comments>
		<pubDate>Sun, 24 Jan 2010 07:35:51 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=55</guid>
		<description><![CDATA[Getting Spring Security setup only involves a few steps, but it can be confusing to work out exactly what they are &#8211; especially since almost all documentation refers to Spring Security 2, and there are a couple of differences.
The first thing to do is to add the Spring Security dependencies to your Maven pom.xml.  [...]]]></description>
			<content:encoded><![CDATA[<p>Getting <a href="http://static.springsource.org/spring-security/site/">Spring Security</a> setup only involves a few steps, but it can be confusing to work out exactly what they are &#8211; especially since almost all documentation refers to Spring Security 2, and there are a couple of differences.</p>
<p>The first thing to do is to add the Spring Security dependencies to your Maven pom.xml.  A good explanation of which ones are needed is located <a href="http://blog.springsource.com/2009/06/03/spring-security-300m1-released/">here</a>.  In summary though, you probably want the following Artifact ids (Group id is <code>org.springframework.security</code>):</p>
<ul>
<li>spring-security-core</li>
<li>spring-security-config</li>
<li>spring-security-web</li>
<li>spring-security-taglibs</li>
</ul>
<p>(Note &#8211; be careful, for some reason the main Maven repository has a few spring-security-* artifacts under the Group id <code>org.springframework</code> &#8211; but they aren&#8217;t physically located there and you will get &#8216;Artifact Not Found&#8217; errors).</p>
<p>After they are downloaded, you need to add the following to <code>web.xml</code>:</p>
<pre class="brush: xml;">
&lt;listener&gt;
   &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;

&lt;context-param&gt;
     &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
     &lt;param-value&gt;
	/WEB-INF/applicationContext-security.xml
     &lt;/param-value&gt;
&lt;/context-param&gt;

&lt;filter&gt;
    &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    &lt;filter-class&gt;
        org.springframework.web.filter.DelegatingFilterProxy
    &lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<p>The extra context configuration puts all the security related information into a separate Spring xml for clarity (plus a different default namespace &#8211; we&#8217;ll see this in a minute).</p>
<p>The new filter does exactly as expected &#8211; intercepts calls to /* (sub-directories included) and applies the Spring Security rules (which we have yet to define).</p>
<p>As specified above, create the file <code>/WEB-INF/applicationContext-security.xml</code>.  This file looks like a normal Spring config file, except instead of the default namespace being <code>beans</code> it is <code>security</code> &#8211; this means that all references to tags which are normally valid need to be prefixed with <code>beans:</code> (see below for an example).</p>
<p><strong>Pay attention to this config &#8211; it is this file which is slightly different from Spring 2</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans:beans
       xmlns=&quot;http://www.springframework.org/schema/security&quot;
       xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security-3.0.xsd&quot;&gt;

    &lt;http auto-config=&quot;true&quot;&gt;
    	&lt;intercept-url pattern=&quot;/client/**&quot; access=&quot;ROLE_USER&quot; /&gt;
    	&lt;intercept-url pattern=&quot;/**&quot; access=&quot;IS_AUTHENTICATED_ANONYMOUSLY&quot; /&gt;
    &lt;/http&gt;

&lt;authentication-manager alias=&quot;authenticationManager&quot;&gt;
	&lt;authentication-provider&gt;
	  &lt;user-service&gt;
		&lt;user name=&quot;ned&quot; password=&quot;ned&quot; authorities=&quot;ROLE_USER&quot; /&gt;
	  &lt;/user-service&gt;
	&lt;/authentication-provider&gt;
&lt;/authentication-manager&gt;	

&lt;/beans:beans&gt;
</pre>
<p>Breaking this file down, the &#8216;key&#8217; tag is <code>http</code>.  The <code>auto-config</code> attribute tells Spring Security to add in all the &#8216;normal&#8217; configuration properties.  As you get more comfortable with Spring Security, you may want to override some of these defaults (e.g. the form to show that captures login information).</p>
<p>The <code>user-service</code> tag adds a single valid user, <em>ned</em>.  In a more likely scenario, the <code>user-service</code> will be hooked up to a database to get a list of valid users &#8211; that&#8217;s an exercise for another day.</p>
<p>The <code>intercept-url</code> patterns are fairly self-explanatory, with one caveat: Spring Security resolves them top-to-bottom, and chooses the first one that matches.  Therefore, make sure your more granular, specific patterns are at the top and a catch-all like &#8220;/**&#8221; goes at the bottom.</p>
<p>Set the above into your Spring application, then try and access <em>your_site/client/whatever.html</em>.  All being well, you should be prompted with the default Spring Security login page.  Put in the credentials you entered into the <code>user-service</code> and you&#8217;re all set.  Congratulations, you just secured your website using Spring Security!</p>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=55</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SiteMesh with Spring MVC</title>
		<link>http://nedlowe.co.uk/wordpress/?p=52</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=52#comments</comments>
		<pubDate>Sun, 17 Jan 2010 16:21:23 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=52</guid>
		<description><![CDATA[SiteMesh is an open source framework that implements the Decorator pattern.  It essentially takes the output stream from a web application, and adds elements to (&#8217;decorates&#8217;) it. Why would we want that?  Put simply, it is an incredibly clean way of adding headers/footers/anything, with the underlying jsp (or whatever) having no knowledge of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.opensymphony.com/sitemesh/">SiteMesh</a> is an open source framework that implements the <em>Decorator</em> pattern.  It essentially takes the output stream from a web application, and adds elements to (&#8217;decorates&#8217;) it. Why would we want that?  Put simply, it is an incredibly clean way of adding headers/footers/anything, with the underlying jsp (or whatever) having no knowledge of that fact it will decorated.  In combination with Spring MVC, this creates a powerful weapon for your developer arsenal.</p>
<p><em>This tutorial assumes you have an existing Spring MVC project</em></p>
<p>To enable SiteMesh, first either include the jar in your lib folder or add it as a Maven dependency (<em>opensymphony | sitemesh</em>).  Next, add the following to your web.xml:</p>
<pre class="brush: xml;">
&lt;filter&gt;
    &lt;filter-name&gt;sitemesh&lt;/filter-name&gt;
    &lt;filter-class&gt;
        com.opensymphony.module.sitemesh.filter.PageFilter
    &lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;sitemesh&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<p>Now we create a new file <code>decorators.xml</code> in WEB-INF.  This file tells SiteMesh which files to map, and which &#8216;decorator&#8217; (which we haven&#8217;t got to yet) to use.  <strong>IMPORTANT</strong> &#8211; in most guides you see, it will tell you to map <code>WEB-INF/jsp</code> or similar.  Remember, Spring MVC is handling the jsp references, so you actually want to point at your html folders/files (Spring MVC totally abstracts the jsp file layer).</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;

&lt;decorators defaultdir=&quot;/WEB-INF/decorators&quot;&gt;
    &lt;decorator name=&quot;master&quot; page=&quot;master.jsp&quot;&gt;
        &lt;pattern&gt;/*&lt;/pattern&gt;
    &lt;/decorator&gt;
&lt;/decorators&gt;
</pre>
<p>The file <em>master.jsp</em> above is the decorator.  Create a file called <em>/WEB-INF/decorators/master.jsp</em> containing the following:</p>
<pre class="brush: xml;">
&lt;%@ taglib prefix=&quot;decorator&quot; uri=&quot;http://www.opensymphony.com/sitemesh/decorator&quot; %&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;
    :: nedlowe.co.uk :: &lt;decorator:title /&gt; ::
    &lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;header&quot;&gt;
       &lt;a href=&quot;http://www.nedlowe.co.uk/&quot;&gt;http://www.nedlowe.co.uk/&lt;/a&gt;
    &lt;/div&gt;
    &lt;div id=&quot;main&quot;&gt;
      &lt;decorator:body /&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>And you&#8217;re done!  Load any page in your Spring MVC application &#8211; and you should see the output has been decorated.</p>
<p>The two <code>decorator</code> tags above look at the pre-decorated page, pull out the respective <code>head</code> and <code>body</code>, and insert them into the output stream.  For more complicated usage, see the <a href="http://www.opensymphony.com/sitemesh/">SiteMesh homepage</a>.</p>
<p>Now let&#8217;s look forward to <a href="http://joewalnes.com/2009/09/07/sitemesh-3-preview/">SiteMesh 3</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=52</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting Spring MVC XML bean definitions into annotations</title>
		<link>http://nedlowe.co.uk/wordpress/?p=42</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=42#comments</comments>
		<pubDate>Sun, 17 Jan 2010 11:32:21 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=42</guid>
		<description><![CDATA[As of Spring 2.5, annotations can be used on Spring MVC classes instead of defining each and every page in the *-servlet.xml definition file.  However, most online guides still reference the old practice.  Below is a simple guide to migrating to (in my opinion), the much cleaner annotation approach.
&#8216;Normal&#8217; Pages
Previously, &#8216;normal&#8217; pages would:

 [...]]]></description>
			<content:encoded><![CDATA[<p>As of Spring 2.5, annotations can be used on Spring MVC classes instead of defining each and every page in the *-servlet.xml definition file.  However, most online guides still reference the old practice.  Below is a simple guide to migrating to (in my opinion), the much cleaner annotation approach.</p>
<p><strong>&#8216;Normal&#8217; Pages</strong><br />
Previously, &#8216;normal&#8217; pages would:</p>
<ul>
<li> Implement the <code>Controller</code> interface</li>
<li> Implement the <code>handleRequest</code> method</li>
<li>Have a simple *-servlet entry along the lines of:</li>
</ul>
<pre class="brush: xml;">
&lt;bean name=&quot;/contact_success.html&quot; class=&quot;com.package.contact.ContactSuccessController&quot; /&gt;
</pre>
<p>Switching this to annotations is simple:</p>
<p>Firstly, add the <code>context:component-scan</code> element to your *-servlet.xml file, along with the Spring MVC annotation handlers:</p>
<pre class="brush: xml;">
&lt;context:component-scan base-package=&quot;com.yourpackage.name&quot; /&gt;
&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping&quot; /&gt;
&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot; /&gt;
</pre>
<p>For the above to work you will also need to add the <code>context</code> namespace URI to your main <code>beans</code> definition (third line down) and the schema to use (6th and 7th lines down):</p>
<pre class="brush: xml;">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd&quot;&gt;
</pre>
<p>Annotate your class with the <code>@Controller</code> annotation, and a <code>@RequestMapping</code> annotation which specifies which URL is mapped by this controller:</p>
<pre class="brush: java;">
@Controller
@RequestMapping(&quot;/contact_success.html&quot;)
public class ContactSuccessController {
  // Rest of class
}
</pre>
<p>The method which handles the request (which &#8211; unlike the previous case where we implemented an interface &#8211; can have any name) should be annotated with <code>@RequestMapping(method = RequestMethod.GET)</code>.</p>
<p>So the bean definition in *-servlet.xml is removed, and the class becomes:</p>
<pre class="brush: java;">
@Controller
@RequestMapping(&quot;/contact_success.html&quot;)
public class ContactSuccessController {
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView handleRequest()  {
     return new ModelAndView(&quot;contact/contactSuccess&quot;);
  }
}
</pre>
<p>Note that unlike the traditional xml based approach, the <code>@RequestMapping</code> annotation specifying which URL to map can be set at the method level (allowing multiple URLs to be mapped by a single Controller).</p>
<p><strong>&#8216;Form&#8217; Pages</strong></p>
<p>Form pages are a little more complicated.  Previously, they would have:</p>
<ul>
<li>Extending the superclass <code>SimpleFormController</code></li>
<li>Overridden methods <code>onSubmit</code> and <code>formBackingObject</code></li>
<li>Had a complicated bean definition containing all form options (e.g. which validator to use, which success page, etc)</li>
</ul>
<p>To migrate these, first enable <code>context:component-scan</code>, along with the new Spring MVC annotation bean definitions as per the previous case.</p>
<p>Next, annotate the form class as per the &#8216;normal&#8217; case. The method annotated with <code>@RequestMapping(method = RequestMethod.GET)</code> handles the initial &#8217;setup&#8217; of the form &#8211; basically what was previously handled in <code>formBackingObject</code>.  This method also returns the view to use for the form.  The command object will be initialised here, then stored in the model).  </p>
<pre class="brush: java;">
@Controller
@RequestMapping(&quot;/contact.html&quot;)
public class ContactFormController  {

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView setupForm(ModelMap model) {

		ContactForm contactForm = new ContactForm();
		model.addAttribute(&quot;contactForm&quot;, contactForm);

        return new ModelAndView(&quot;contact/contactForm&quot;);
	}

 // CLASS NOT COMPLETE YET!!!
}
</pre>
<p>The method which is called when the &#8216;Submit&#8217; button is pressed is annotated in a similar manner, except the RequestMethod is POST instead of GET.  However, the differences then get larger:</p>
<ul>
<li>There is no automated validation (assuming a validator is specified of course).  See below how this is handled.</li>
<li>The validator will return a status.  If there is an error we simply return the same view.  If not, we set the <code>SessionStatus</code> to complete and return the name of the Success view to use.</li>
<li>To get at our command object we need to pull it out of the model &#8211; using the <code>@ModelAttribute("contactForm")</code> annotation.
</ul>
<p>As mentioned above, we need to call the <code>validator</code> directly.  To do this, we need to <code>@Autowire</code> the <code>validator</code> into the class (as per normal Spring injection).  Since we are no longer relying on Spring MVC calling the <code>validator</code>, we can improve the <code>validate</code> method on the <code>validator</code> to become typesafe, instead of passing in a generic <code>object</code> as before.</p>
<p>Complete class:</p>
<pre class="brush: java;">
@Controller
@RequestMapping(&quot;/contact.html&quot;)
public class ContactFormController  {

	@Autowired
	ContactFormValidator contactFormValidator;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView setupForm(ModelMap model) {

		ContactForm contactForm = new ContactForm();
		model.addAttribute(&quot;contactForm&quot;, contactForm);

        return new ModelAndView(&quot;contact/contactForm&quot;);
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(@ModelAttribute(&quot;contactForm&quot;) ContactForm contactForm,
			                      BindingResult errors,
			                      SessionStatus sessionStatus) {
		contactFormValidator.validate(contactForm, errors);
		if (errors.hasErrors()) {
			return new ModelAndView(&quot;contact/contactForm&quot;);
		}
		else {
			// Business Logic
			sessionStatus.setComplete();
			return new ModelAndView(new RedirectView(&quot;contact_success.html&quot;));
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=42</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Breaking Up A Large Hibernate Class</title>
		<link>http://nedlowe.co.uk/wordpress/?p=40</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=40#comments</comments>
		<pubDate>Sun, 10 Jan 2010 17:14:45 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=40</guid>
		<description><![CDATA[Over time, Hibernate classes can get very large &#8211; especially when modelling a complicated object (for example a financial transaction).
At this point, the @Embedded annotation comes to the rescue.  The class annotated with @Embedded will be linked into the parent class as if it were one large class.
This even works with collections &#8211; the [...]]]></description>
			<content:encoded><![CDATA[<p>Over time, Hibernate classes can get very large &#8211; especially when modelling a complicated object (for example a financial transaction).</p>
<p>At this point, the @Embedded annotation comes to the rescue.  The class annotated with @Embedded will be linked into the parent class as if it were one large class.</p>
<p>This even works with collections &#8211; the collection can be defined in the child (@Embeddable) class.</p>
<pre class="brush: java;">
@Entity
public class PretendClass {
  @Id
  private Long transactionId;

  @Embedded
  private PretendChildClass pretendChildClass = new PretendChildClass();

}

@Embeddable
public class PretendChildClass {

  @OneToMany(mappedBy = &quot;transaction&quot;, targetEntity = TransactionAttributeImpl.class, cascade = CascadeType.ALL)
  @MapKey(name = &quot;transactionAttributeType&quot;)
  @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
  private Map&lt;TransactionAttributeType, TransactionAttribute&gt; transactionAttributeMap = new HashMap&lt;TransactionAttributeType, TransactionAttribute&gt;();	

}
</pre>
<p>One caveat &#8211; we ought to be programming to interfaces rather than implementations.  Assuming we marked an interface as @Embedded, Hibernate will scan the <b>interface</b> and not import any of the fields defined in the class.  In this case, one simply adds the @Target annotation:</p>
<pre class="brush: java;">
  @Embedded
  @Target(value = PretendChildClassImpl.class)
  private PretendChildClass pretendChildClass = new PretendChildClassImpl();
</pre>
<p>If using Criteria, this extra &#8216;level&#8217; in the class hierarchy is simply referenced via a full-stop:</p>
<pre class="brush: java;">
  List&lt;Transaction&gt; transactionList;
  Criteria crit = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(TransactionImpl.class);
  crit.createAlias(&quot;embeddable_child_class.variable_we_want&quot;, &quot;transactionExtRef&quot;); // THE IMPORTANT LINE
  crit.add(Restrictions.eq(&quot;transactionExtRef.transactionExtRefType&quot;, transactionExtRefType))
       .add(Restrictions.eq(&quot;transactionExtRef.transactionExtRefValue&quot;, transactionExtRefValue));
  transactionList = crit.list();
  return transactionList;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=40</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Database Population Tool</title>
		<link>http://nedlowe.co.uk/wordpress/?p=32</link>
		<comments>http://nedlowe.co.uk/wordpress/?p=32#comments</comments>
		<pubDate>Sun, 20 Dec 2009 07:12:02 +0000</pubDate>
		<dc:creator>Ned Lowe</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nedlowe.co.uk/wordpress/?p=32</guid>
		<description><![CDATA[My source control contains many tables, many of which have dependencies on one another via foreign keys.  When the table structures are being changed fairly regularly, it can be a pain to have to keep updating the database manually.
Ant has a built in SQL task which will pick up a file, then execute the [...]]]></description>
			<content:encoded><![CDATA[<p>My source control contains many tables, many of which have dependencies on one another via foreign keys.  When the table structures are being changed fairly regularly, it can be a pain to have to keep updating the database manually.</p>
<p><a href="http://ant.apache.org/">Ant</a> has a built in SQL task which will pick up a file, then execute the contained statements on the database of your choice.</p>
<ol>
<li>Firstly, create the required scripts to be executed.  For table creation scripts, I always add &#8216;DROP TABLE IF EXISTS&#8217; (or a variant depending on SQL dialect) to make it easier to run a script on its own if it has no external dependencies.</li>
<li>Create extra scripts for dropping the tables (with the commands in the correct order to respect foreign keys).</li>
<li>Create an Ant build file (<i>build.xml</i>).  Each script to be executed is placed in the file in order of execution (to again respect foreign keys).</li>
<li>Execute Ant from the directory containing <i>build.xml</i></li>
</ol>
<p><b>Example for step one</b></p>
<pre class="brush: sql;">
DROP TABLE IF EXISTS reference_generator;

CREATE TABLE reference_generator (
  ref_gen_type VARCHAR(20) NOT NULL,
  reference    BIGINT      NOT NULL,
  timestamp    DATETIME    NOT NULL,
  PRIMARY KEY (ref_gen_type)
)
ENGINE=INNODB;
</pre>
<p><b>Example for step two (filename &#8211; drop_party.sql)</b></p>
<pre class="brush: sql;">
DROP TABLE IF EXISTS party_attribute;
DROP TABLE IF EXISTS party_ext_ref;
DROP TABLE IF EXISTS party_flag;
DROP TABLE IF EXISTS party;
</pre>
<p><b>Example for step three (build.xml)</b></p>
<pre class="brush: xml;">
&lt;project name=&quot;DatabaseSetup&quot; basedir=&quot;.&quot; default=&quot;createAndPopulate&quot;&gt;

  &lt;property name=&quot;sql.driver&quot; value=&quot;com.mysql.jdbc.Driver&quot; /&gt;
  &lt;property name=&quot;sql.url&quot; value=&quot;jdbc:mysql://server/dbname&quot; /&gt;
  &lt;property name=&quot;sql.username&quot; value=&quot;myusername&quot; /&gt;
  &lt;property name=&quot;sql.password&quot; value=&quot;mypassword&quot; /&gt;

  &lt;target name=&quot;createAndPopulate&quot;&gt;
    &lt;sql driver=&quot;${sql.driver}&quot; url=&quot;${sql.url}&quot; userid=&quot;${sql.username}&quot; password=&quot;${sql.password}&quot; &gt;
      &lt;transaction src=&quot;./table/drop_party.sql&quot; /&gt;
      &lt;transaction src=&quot;./table/party.sql&quot; /&gt;
      &lt;transaction src=&quot;./table/party_attribute.sql&quot; /&gt;
      &lt;transaction src=&quot;./table/party_ext_ref.sql&quot; /&gt;
      &lt;transaction src=&quot;./table/party_flag.sql&quot; /&gt;

      &lt;transaction src=&quot;./table/reference_generator.sql&quot; /&gt;
      &lt;transaction src=&quot;./data/reference_generator.sql&quot; /&gt;
    &lt;/sql&gt;
  &lt;/target&gt;

&lt;/project&gt;
</pre>
<p>It is of course important that the JDBC driver referenced (in the example com.mysql.jdbc.Driver) is available to Ant.  A simple way of doing this is to add the relevant jar to Ant&#8217;s lib directory.</p>
<p><b>MySQL Stored Procedures</b><br />
The above technique works for MySQL stored procedures, with one minor change.  When writing a MySQL stored procedure, the delimiter to use must be explicitly set (as ; is used within the stored procedures statements).</p>
<p>To set this delimiter, the &#8216;delimiter&#8217; attribute within the sql tag must be provided.</p>
<p>For example:</p>
<pre class="brush: xml;">
&lt;!-- Usage: ant createsp -Dfile=./dir/file.sql--&gt;
  &lt;target name=&quot;createsp&quot;&gt;
    &lt;sql driver=&quot;${sql.driver}&quot; url=&quot;${sql.url}&quot; userid=&quot;${sql.username}&quot; password=&quot;${sql.password}&quot; delimiter=&quot;//&quot; &gt;
      &lt;transaction src=&quot;${file}&quot; /&gt;
    &lt;/sql&gt;
  &lt;/target&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://nedlowe.co.uk/wordpress/?feed=rss2&amp;p=32</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
