<?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>Cake Solutions Team Blog &#187; Spring</title>
	<atom:link href="http://www.cakesolutions.net/teamblogs/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cakesolutions.net/teamblogs</link>
	<description>void magic() { }</description>
	<lastBuildDate>Tue, 07 Feb 2012 12:02:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Scalaz monads in Spring</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/02/03/scalaz-monads-in-spring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=scalaz-monads-in-spring</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/02/03/scalaz-monads-in-spring/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 12:00:50 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Scalaz IO]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=2005</guid>
		<description><![CDATA[I won&#8217;t give you the category-theory based explanation of monads. Instead, I&#8217;m going to show you the application of monads, but not on Ints and Strings, but on ordinary domain instances; instances that we persist using Hibernate. Finally, we&#8217;ll run &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/02/03/scalaz-monads-in-spring/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I won&#8217;t give you the category-theory based explanation of <em>monads</em>. Instead, I&#8217;m going to show you the application of monads, but not on <code>Int</code>s and <code>String</code>s, but on ordinary domain instances; instances that we persist using Hibernate. Finally, we&#8217;ll run the entire example in the Spring Framework.</p>
<p>Why the complexity, you ask? My team often found the simple examples understandable, but they struggled to see the application of the monads to day-to-day business code. &#8220;Sure, we write monads that read a <code>String</code> from a file, chain it to monad that converts the <code>String</code> to <code>Int</code>, but we&#8217;re having to generate reports,&#8221; they said.</p>
<h2>The service</h2>
<p>Let&#8217;s write a <code>ReportService</code> that generates reports and then produces a combined report by combining the individual reports into one. Its API is:</p>
<pre class="brush:[scala]">
class ReportService {

  def produce()

  def combine()

}
</pre>
<p>Where the <code>produce</code> function generates the individual reports (pages, if you like); and the <code>combine</code> function takes the already generated reports and assembles the aggregate. We keep these reports in the database (and the content on the disk) and we map the RDBMS records to the <code>Record</code> instances. We are using Hibernate, leading the definition of the <code>Report</code> class:</p>
<pre class="brush:[scala]">
@Entity
case class Report() {
  @Id
  @GeneratedValue
  @BeanProperty
  var id: Long = _
  @Version
  @BeanProperty
  var version: Int = _
  @BeanProperty
  var fileName: String = _

}
</pre>
<p>As I said earlier, we are using Hibernate to manipulate the <code>Record</code> instances, so our <code>ReportService</code> will need to depend on the <code>SessionFactory</code>. Because we&#8217;re running in the Spring Framework, we can have the dependency injected in. We just have to give the appropriate metadata to the Spring Framework&#8217;s DI core:</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {

  def produce()

  def combine()

}
</pre>
<p>We&#8217;ll start with the <code>produce()</code> function. The task is to generate [a fixed number of] reports. So, we&#8217;ll need a <code>for</code> loop whose every iteration creates a <code>Report</code> instance and saves it to the DB.</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {

  @Transactional
  def produce() {
    for (i < - 0 to 100) {
      val report = Report()
      val content = "Report %d".format(i)
      report.fileName = "%d".format(i)

      // save the report's content

      sessionFactory.getCurrentSession.saveOrUpdate(report)
    }
  }

}
</pre>
<p>So far, so good. We have the fancy Scala <code>for</code> loop, but the code remains very similar to its Java equivalent. Now, let's deal with the IO. To save a report, we need to:</p>
<ul>
<li>create / open a file into which the content is going to go,</li>
<li>produce the report's content,</li>
<li>write the content to the file.</li>
</ul>
<ul>
<p>So, we have three operations. We go from <code>Report</code> to <em>operation giving</em> <code>File</code>, second that goes from <em>operation giving</em> <code>File</code> and <em>operation giving</em> <code>Data</code> to <em>operation giving</em> <code>Unit</code>. So, let's write these operations and define what we mean by <code>Data</code>:</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {
  type Data = Array[Char]
  import scalaz._
  import scalaz.effects._

  def reportToFile(report: Report) = io {
    new File("/Users/janmachacek/Tmp/r/%s".format(report.fileName))
  }
  def dataToFile(data: IO[Data])(file: File) = io {
    println("Written " + new String(data.unsafePerformIO) + " to " + file)
  }

  ...

}
</pre>
<p>The function <code>reportToFile</code> is the one that takes a <code>Report</code> and returns an <em>operation that gives</em> <code>File</code>. The <em>operation that gives</em> is whatever the <code>io</code> function returns. Then I have the <code>dataToFile</code> function that takes an <em>operation that takes </em>operation that gives <code>Data</code> and returns an <em>operation that gives <code>Unit</code></em>. Figure 1 shows a picture of what we're trying to do.</p>
<p>Figure 1. The operations and the links between them</p>
<p><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2012/02/monads.png" alt="" title="monads" width="475" height="375" /></p>
<p><em>We would like to wire the three operations together to give us a new operation that combines the three together!</em></p>
<p>This is crucial concept: we're not just pushing data around, we're creating a new operation that combines the smaller operations to do something useful for us. So, let's drop in the real syntax:</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {
  type Data = Array[Char]
  import scalaz._
  import scalaz.effects._

  def reportToFile(report: Report) = io {
    new File("/Users/janmachacek/Tmp/r/%s".format(report.fileName))
  }
  def dataToFile(data: IO[Data])(file: File) = io {
    println("Written " + new String(data.unsafePerformIO) + " to " + file)
  }

  @Transactional
  def produce() {
    for (i &lt;- 0 to 100) {
      val report = Report()
      val content = "Report %d".format(i)
      report.fileName = "%d".format(i)

      (reportToFile(report) &gt;&gt;=
         dataToFile(io {content.toCharArray})).unsafePerformIO

      sessionFactory.getCurrentSession.saveOrUpdate(report)
    }
  }

}
</pre>
<p>Let's explore the mystical <code>(reportToFile(report) &gt;&gt;= dataToFile(io {content.toCharArray})).unsafePerformIO</code> line. We have <code>reportToFile</code> takes a <code>Report</code> and makes a <em>thing</em> that makes a <code>File</code>. Then we have <code>dataToFile</code> which takes a <em>thing</em> that makes <code>Data</code> and <em>thing</em> that makes <code>File</code>. We treat these <em>things</em> as black boxes--they do something obscure, unknown and unknowable. But these <em>things</em> have a "screen" on them; and we can look at that "screen" and obtain the current value.</p>
<p>And that's the principle of monads. They are opaque things that can return some value and they can be chained together to form new things that combine whatever the component things do.</p>
<p>And that explains the <code>unsafePerformIO</code> call. The <code>(reportToFile(report) &gt;&gt;= dataToFile(io {content.toCharArray}))</code> simply returns a new monad, but we must "look at its screen"; make it compute a value, in other words. And that's what the <code>unsafePerformIO</code> function does.</p>
</ul>
</pre>
<p>Onwards, then! Let&#8217;s implement the <code>combine</code> function that selects all existing reports, and merges them into a one fat report that it then saves.</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {
  type Data = Array[Char]
  import scalaz._
  import scalaz.effects._
  import scala.collection.JavaConversions._

  def reportToFile(report: Report) = io {
    new File("/Users/janmachacek/Tmp/r/%s".format(report.fileName))
  }
  def dataToFile(data: IO[Data])(file: File) = io {
    println("Written " + new String(data.unsafePerformIO) + " to " + file)
  }
  def fileToData(file: File) = io {
    Source.fromFile(file).toArray
  }

  @Transactional
  def produce() {
    ...
  }

  @Transactional
  def combine() {
    val reports =
      sessionFactory.getCurrentSession.createCriteria(classOf[Report]).
        list().asInstanceOf[java.util.List[Report]].toList

    val out = Report()
    out.fileName = "out.txt"

    // take the reports and make one big fat report out

    sessionFactory.getCurrentSession.saveOrUpdate(out)
  }

}
</pre>
<p>The <code>combine</code> selects all <code>Report</code> records, and (using the function in scala.collection.JavaConversions._) converts the <code>java.util.List[Report]</code> into <code>scala.collections.immutable.List[Report]</code>. How do we now combine the reports? Let&#8217;s think about it:</p>
<ul>
<li>If the <code>reports</code> contains just one item, then the result is that one item,</li>
<li>If the <code>reports</code> contains two items, then we need some function that takes two <code>Report</code>s and makes the combined <code>Report</code>,</li>
<li>If the <code>reports</code> contains many (i.e. more than two!) items, then we take the first two and combine them into one (using the function from the previous step). Then we take the combined report and combine it with the third item; then we take the combined report and combine it with the fourth item; and so on, until the end.</li>
</ul>
<ul>
<p>So, we need a function that combines two reports into one and then an operation that implements the algorithm we described earlier. The name for the operation is <code>foldl1</code> and Figure 2 shows how it works:</p>
<p>Figure 2. foldl1 function</p>
<p><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2012/02/foldl.png" alt="" title="foldl" width="566" height="185" /></p>
<p>The arrows in the image are our function and <code>report<sub>1</sub>, report<sub>2</sub>, ..., report<sub>n</sub></code> is our list. Hence the code of the <code>combine</code> function becomes:</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {

  ...

  @Transactional
  def combine() {
    val reports =
      sessionFactory.getCurrentSession.createCriteria(classOf[Report]).
        list().asInstanceOf[java.util.List[Report]].toList

    val out = Report()
    out.fileName = "out.txt"

    reports.foldl1 { (r1: Report, r2: Report) =>
      // read the r1 and r2 from the files,
      // combine them and write to out
      out
    }

    sessionFactory.getCurrentSession.saveOrUpdate(out)
  }
}
</pre>
<p>We now have to read the report from a file into <code>Data</code> and the combine the two <code>Data</code>s representing the reports together. The good news is that we have already written the monads that deal with the report IO. All we have to do is to combine them to form new interesting monad that combines the reports.</p>
<pre class="brush:[scala]">
@Service
class ReportService @Autowired() (private val sessionFactory: SessionFactory) {

  ...

  @Transactional
  def combine() {
    val reports =
      sessionFactory.getCurrentSession.createCriteria(classOf[Report]).
        list().asInstanceOf[java.util.List[Report]].toList

    val out = Report()
    out.fileName = "out.txt"

    def combine(data: (Data, Data)) = io { data._1 ++ data._2 }

    reports.foldl1 { (r1: Report, r2: Report) =>
      (reportToFile(out) &gt;&gt;= dataToFile(
        (reportToFile(r1) &gt;&gt;= fileToData) &lt;|*|&gt;
        (reportToFile(r2) &gt;&gt;= fileToData) &gt;&gt;= combine)
      ).unsafePerformIO

      out
    }

    sessionFactory.getCurrentSession.saveOrUpdate(out)
  }
}
</pre>
<p>You already know about chaining the monads (using <code>&gt;&gt;=</code>), the new thing in the <code>reports.foldl1</code> function is the <code>&lt;|*|&gt;</code> operation. Think of this operation indeed as multiplication, but multiplication of the computed values of the monads. The monad on the left-hand side (<code>(reportToFile(r1) &gt;&gt;= fileToData)</code>) computes <code>Data</code>, the monad on the right-hand side (<code>(reportToFile(r2) &gt;&gt;= fileToData)</code>) computes <code>Data</code>. In this case, we have <code>Data</code> * <code>Data</code>, in other words a pair&#8211;tuple in computer speak&#8211;of <code>Data</code>. And that&#8217;s precisely what the <code>combine</code> function takes (its body simply appends the two arrays) and it returns the combined IO of <code>Data</code>&#8230; and we can use it as input of the <code>dataToFile</code> function, which is an IO monad that follows the <code>reportToFile(out)</code> monads.</p>
<p>The whole contraption represents our <em>report + report</em> function; which we give to the <code>foldl1</code> function. For completeness, we save the combined report using the injected <code>sessionFactory</code>.</p>
<h2>Summary</h2>
</p>
<p>This code combines dependency injection, load-time weaving (courtesy of the Spring Framework) with elegance and effectiveness of the Scala code. Finally, we take advantage of the IO monads in Scalaz to compose the individual trivial operations (report -> file, data -> file, etc.) to compose new operations that we use in the <code>produce</code> and <code>combine</code> functions.</p>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/02/03/scalaz-monads-in-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SBT &#8211; DocBook Plugin</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/01/20/sbt-docbook-plugin/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sbt-docbook-plugin</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/01/20/sbt-docbook-plugin/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 14:22:59 +0000</pubDate>
		<dc:creator>Ndidi</dc:creator>
				<category><![CDATA[Ndidi's Blog]]></category>
		<category><![CDATA[DocBook]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[sbt]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Specs2]]></category>
		<category><![CDATA[Specs2 Spring]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1858</guid>
		<description><![CDATA[Hey there! I&#8217;ve recently just started working with Cake Solutions, Scala and SBT. One of my first tasks was to improve the documentation in Specs2 Spring. SBT and DocBook As part of our Specs2 Spring project, we wanted to ensure users had &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/01/20/sbt-docbook-plugin/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hey there! I&#8217;ve recently just started working with <a href="http://www.cakesolutions.net/">Cake Solutions</a>, Scala and SBT. One of my first tasks was to improve the documentation in Specs2 Spring.</p>
<h2>SBT and DocBook</h2>
<p>As part of our <a href="https://github.com/janm399/specs2-spring">Specs2 Spring</a> project, we wanted to ensure users had access to Spec2 Spring&#8217;s documentation in a format they know and love, we figured we&#8217;d use <a href="http://www.docbook.org/">DocBook</a>, the multiformat-generating, markup language.</p>
<p>Fortunately a SBT plugin currently exists for DocBook, however it currently doesn&#8217;t have a few features we need.</p>
<p>We have forked the SBT DocBook plugin, because we needed to add support for XInclude, syntax highlighting, ePUB and many other improvements. Find it <a href="https://github.com/janm399/sbt-docbook-plugin">here</a>.</p>
<h2>The Setup</h2>
<p>Using it is pretty straight-forward. You should have a directory structure similar to this:</p>
<pre>MyProject
  build.sbt
  src/
    main/
      java/
      scala/
      docbook/
        main.xml
        chapter1.xml
        ...
  project/
    plugins.sbt</pre>
<p>Simply ensure all DocBook files are in the <code>src/main/docbook</code> directory. Note that if you have multiple DocBook files, the main file must be named <code>main.xml</code>. On the other hand, if there is just one file, feel free to name it anything you like.</p>
<p>Include the plugin in your <code>project/plugins.sbt</code> file as follows:</p>
<pre class="brush:[scala]">resolvers += ScalaToolsSnapshots

addSbtPlugin("de.undercouch" % "sbt-docbook-plugin" % "0.2-SNAPSHOT")</pre>
<p>That&#8217;s it!</p>
<h2>Run it!</h2>
<p>Generating documents in the format of your choice is pretty easy:</p>
<p><code><br />
$ sbt html<br />
</code></p>
<p><code><br />
$ sbt pdf<br />
</code></p>
<p><code><br />
$ sbt xhtml<br />
</code></p>
<p><code><br />
$ sbt manpage<br />
</code></p>
<p><code><br />
$ sbt eclipse-help<br />
</code></p>
<p>Checkout the readme for more options.</p>
<h2>How have we done it?</h2>
<p>Robust documentation is key to getting the community interested and involved in any project and modular documentation is key to the sanity of the project developers. An easy way to produce modular documentation is by using <a href="http://en.wikipedia.org/wiki/XInclude">XInclude</a>, sadly the plugin it uses, <a href="http://saxon.sourceforge.net/">Saxon</a> 6.5.3, for processing XSLT, cannot handle XInclude.</p>
<p>After extensive googling &amp; hacking, I eventually turned to <a href="http://xerces.apache.org/xerces2-j/">Xerces2</a> to resolve XInclude. The code looks a little something like this:</p>
<pre class="brush:[scala]">   private def transformDocBook(src: File, dst: File, styleSheet: String,
  cp: Classpath, log: Logger) {
    transform(src, dst, log) {
      //write output to temporary file. this avoids a bug in Saxon
      //that caused spaces in the output filename to be converted to
      //an escaped sequence (%20)
      val temp = File.createTempFile("sbt-docbook-plugin-", ".fo")
      val code = Fork.java(None, Seq[String](
      "-cp", cp.files.mkString(File.pathSeparator),
      "-Djavax.xml.parsers.DocumentBuilderFactory="+
        "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl",
      "-Djavax.xml.parsers.SAXParserFactory=" +
        "org.apache.xerces.jaxp.SAXParserFactoryImpl",
      "-Dorg.apache.xerces.xni.parser.XMLParserConfiguration=" +
        "org.apache.xerces.parsers.XIncludeParserConfiguration",
      "com.icl.saxon.StyleSheet",
      "-o", temp.toString,
        src.toString, styleSheet
      ), log)

      //copy temporary file to real output file
      temp #&gt; dst !

      //delete temporary file (if this files it will be deleted on exit)
      if (!temp.delete()) {
        temp.deleteOnExit()
      }
      code
    }
  }</pre>
<p>So what&#8217;s going on here? Well <code><a href="http://harrah.github.com/xsbt/latest/api/index.html#sbt.Fork$$ForkJava">Fork.java</a></code> makes it possible for us to run a separate java process, <code>"-cp"</code> sets up it&#8217;s classpath, <code>cp.files.mkString(File.pathSeparator)</code> ensures that the correct path separator is used for your file system, the first 2 <code>-D</code> options set Xerces as Saxon&#8217;s xml parser, the last <code>-D</code> option turns on the XInclude feature and <code>-o</code> set&#8217;s Saxon&#8217;s output file or directory!</p>
<p>Maintaining Specs2 Spring and any other documentation has been made a little easier!</p>
<p>The next focus will be on improving the plugin&#8217;s output for documentation split into multiple files, in particular EPUB..</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/01/20/sbt-docbook-plugin/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>This week in #Scala (16/12/2011)</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/12/15/this-week-in-scala-16122011/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=this-week-in-scala-16122011</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/12/15/this-week-in-scala-16122011/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 17:37:32 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[Mark's Blog]]></category>
		<category><![CDATA[Akka]]></category>
		<category><![CDATA[Cake pattern]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[intellij idea]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala ide]]></category>
		<category><![CDATA[setak]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1628</guid>
		<description><![CDATA[Welcome to another week in #Scala! Once again there&#8217;s plenty to tell you about, so read on: &#160; New Stuff #Scala IDE for #Eclipse 2.0.0 Release Candidate 4 available now! This release adds compatibility with Groovy IDE &#8211; in addition &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/12/15/this-week-in-scala-16122011/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Welcome to another week in #Scala! Once again there&#8217;s plenty to tell you about, so read on:</p>
<p>&nbsp;</p>
<p><strong>New Stuff</strong></p>
<p><strong><a href="http://www.scala-ide.org/2011/12/the-scala-ide-for-eclipse-2-0-0-rc4-for-scala-2-9-1-and-2-8-3-snapshot-available-now/" target="_blank">#Scala IDE for #Eclipse</a></strong> 2.0.0 Release Candidate 4 available now! This release adds compatibility with Groovy IDE &#8211; in addition to lots of bug fixes and improvements.</p>
<p><strong><a href="http://mir.cs.illinois.edu/setak/" target="_blank">Setak</a></strong> has been released! Setak is A Framework for Stepwise Deterministic Testing of Akka Actors. It allows programmers to specify the order of messages during the execution of a test. It also makes it easy to check test assertions that require actors to be in a stable state. For more information hit the link.</p>
<p><strong><a href="http://www.stackmob.com/2011/12/welcome-to-stackmob-open-beta/">Stackmob is now in public beta</a></strong>, not much else to say on that! Click through for details.</p>
<p><strong><a href="http://blog.typesafe.com/akka-20-pre-release-milestone-1" target="_blank">AKKA 2.0 Milestone 1 is out now</a></strong>, loads of new and improved features, including:</p>
<ul>
<li>Modular configuration</li>
<li>Mandatory Supervisor Hierarchies</li>
<li>Location Transparency</li>
<li>Many other additions and refinements</li>
</ul>
<p>Click the link for more details.</p>
<p><strong><a href="https://groups.google.com/group/akka-user/browse_thread/thread/351b44ed21bd15d" target="_blank">AKKA 1.3-RC4</a></strong> is now available to download.</p>
<p>&nbsp;</p>
<p><strong>Blogs and tutorials</strong></p>
<ul>
<li>Havoc Pennington (@havocp) blogged about &#8216;<a href="http://blog.ometer.com/2011/12/09/configuring-the-typesafe-stack/" target="_blank">Configuring the Typesafe Stack</a>&#8216;, covering the changes to akka.conf and Play application.conf in #playframework and #akka 2.0. Hit the link to read more.</li>
<li>New post on the tech behind @klout including #playframework and #akka&#8230; &#8216;<a href="http://corp.klout.com/blog/2011/12/find-your-klout/" target="_blank">Akka helps Klout’s search go fast!</a>&#8216;</li>
<li>visi.io posted an interesting blog: &#8216;<a href="http://blog.visi.io/mmm-sweet-tasty-state-monads" target="_blank">Sweet tasty state monads</a>&#8216;, the title says it all &#8211; it&#8217;s well worth a look.</li>
<li>Pavel Fatin (@pavelfatin) posted A couple of new Intellij IDEA blogs, <a href="http://blog.jetbrains.com/scala/2011/12/13/cherish-your-packages" target="_blank">Chained packages</a> and <a href="http://blog.jetbrains.com/scala/2011/12/15/whats-new-in-scalatest-integration" target="_blank">What’s new in ScalaTest integration</a></li>
<li>An excellent presentation by Daniel Spiewak (@djspiewak) on <a href="http://www.infoq.com/presentations/Functional-Data-Structures-in-Scala" target="_blank">Functional Data Structures in Scala</a> is now available on infoq.</li>
<li>Checkout the cake blogs on <a href="http://www.cakesolutions.net/teamblogs/2011/12/10/type-safe-dsl/" target="_blank">Using Scala to build type-safe DSL</a>, <a href="http://www.cakesolutions.net/teamblogs/2011/12/14/pattern-matching/" target="_blank">Pattern Matching</a> and <a href="http://www.cakesolutions.net/teamblogs/2011/12/15/dependency-injection-vs-cake-pattern/" target="_blank">Spring DI vs. the Cake Pattern</a>!</li>
<li>Finally, more #Scala debates &#8211; this time a <a href="http://gridgaintech.wordpress.com/2011/12/11/offbeat-scala-by-the-end-of-2011-no-drama-but-frustration-is-growing/" target="_blank">post by Nikita Ivanov of GridGain</a> (@gridgain) discussing their experiences with the language.</li>
</ul>
<p>&nbsp;</p>
<p>Feel free to drop me a <a href="mailto:markh@cakesolutions.net" target="_blank">mail</a> or message @markglh on twitter with any Scala news!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/12/15/this-week-in-scala-16122011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency injection vs. Cake pattern</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/12/15/dependency-injection-vs-cake-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dependency-injection-vs-cake-pattern</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/12/15/dependency-injection-vs-cake-pattern/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 16:09:07 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Ani's Blog]]></category>
		<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Cake pattern]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Play]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1545</guid>
		<description><![CDATA[Typically, the argument comes down to is Spring Framework better than Play Framework?, is Lift better than Spring Framework?, is Grails better than everything else?. In this post, we will explore the world of contemporary JEE applications, paying extra attention &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/12/15/dependency-injection-vs-cake-pattern/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Typically, the argument comes down to <em>is <a title="Spring Framework" href="http://www.springframework.org" target="_blank">Spring Framework</a> better than <a title="Play Framework" href="http://www.playframework.org/" target="_blank">Play Framework</a>?</em>, <em>is <a title="Lift" href="http://liftweb.net/" target="_blank">Lift</a> better than <a title="Spring Framework" href="http://www.springframework.org" target="_blank">Spring Framework</a>?</em>, <em>is <a title="Grails" href="http://grails.org/" target="_blank">Grails</a> better than everything else?</em>. In this post, we will explore the world of contemporary JEE applications, paying extra attention to the usual DI frameworks and frameworks that implement the Cake pattern.</p>
<p>For more detailed discussion of the Cake pattern, see Mark&#8217;s <a href="http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth/" title="Cake pattern in depth">Cake pattern in depth</a></p>
<p>Before we rush into condemning one or the other, we feel that what you need to think about what kind of application you&#8217;re writing. We&#8217;ll go as far as to say that if you need JMS, JMX, scheduling, WebFlow, &#8230;, then you should stick with the Spring Framework. By all means implement the components that make up your Spring application in Scala! If these JEE dinosaurs do not come anywhere near your application, then Play 2 in Scala, using the Cake pattern might just be the perfect thing for you!</p>
<h2>Dependency injection</h2>
<p>Spring Framework, we have multiple modules; each module contains the code that is appropriate for the tier that the module implements. The code means the Java interfaces &amp; their implementations as well as the Spring configuration (typically in the <code>META-INF/spring/module-context.xml</code> file). The types of the dependencies are checked at compile-time: if we haven&#8217;t defined the <code>UserService</code> interface, for example, and tried to use it in the <code>UserController</code>, the compilation would fail. However, the compiler cannot check that the appropriate implementation of the <code>UserService</code> will be available to be injected to the <code>UserController</code> at runtime. The application is loosely coupled, which is good, but we must supply appropriate metadata (the annotations &amp; the Spring XML) so that Spring can construct the application.</p>
<blockquote><p>Dependency-injection applications must provide valid metadata so that the DI framework can construct their components &amp; satisfy the dependencies between them at runtime.</p></blockquote>
<p>Let&#8217;s write a trivial application that contains a repository and a service. We will follow the recommended code to interfaces approach. This gives us the following code in the repository:</p>
<pre class="brush:[java]">public interface UserRepository {
  List&lt;User&gt; findAll();
}

@Repository
public class ORMUserRepository implements UserRepository {
  private SessionFactory sessionFactory = // construct the SF
  public List&lt;User&gt; findAll() {
    // not real Hibernate code, but close enough
    return sessionFactory.getCurrentSession().query(...);
  }
}</pre>
<p>We now combine this code with the Spring context file, which instructs the DI core to create the <code>ORMUserRepository</code> component.</p>
<pre class="brush:[xml]">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="..."&gt;

  &lt;context:annotation-config/&gt;
  &lt;context:component-scan base-package="...repository"/&gt;

&lt;beans/&gt;</pre>
<p>We implement the code in the services in using a similar pattern: we have the <code>UserService</code> interface and we implement it in some class. Crucially, we will rely on Spring to inject a valid implementation of the <code>UserRepository</code> to the instance of the <code>DefaultUserService</code> at runtime, using the configuration we provide.</p>
<pre class="brush:[java]">public interface UserService {
  List&lt;User&gt; findAll();
}

@Service
public class DefaultUserService implements UserService {
  private final UserRepository userRepository;

  @Autowired
  public DefaultUserService(final UserRepository userRepository) {
    if (userRepository == null)
      throw new IllegalArgumentException("Off Santa's list!");
    this.userRepository = userRepository;
  }

  public List&lt;User&gt; findAll() {
    return this.userRepository.findAll();
  }
}</pre>
<p>The services module needs its configuration, too. And so, we give the familiar <code>/META-INF/spring/module-context.xml</code>:</p>
<pre class="brush:[xml]">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="..."&gt;

  &lt;context:annotation-config/&gt;
  &lt;context:component-scan base-package="...services"/&gt;

&lt;beans/&gt;</pre>
<p>We have the components and the metadata. All we need now is to let Spring Framework create all the components. In other words, the <code>ApplicationContext</code> implementation that the Spring Framework provides will become our application:</p>
<pre class="brush:[java]">public class App {

  public static void main(String[] args) {
    ApplicationContext application =
      new ClassPathXmlApplicationContext(
        "classpath*:/META-INF/spring/module-context.xml"));

    UserService service = application.getBean(UserService.class);

    // use it!
    service.findAll();
  }
}</pre>
<p><em>The Spring Framework became our application! All we have is a shell that boots-up Spring</em>, as shown on Figure 1.</p>
<p>Figure 1. Spring DI application</p>
<p><a href="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/springapp1.png"><img title="springapp" src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/springapp1.png" alt="" width="568" height="795" /></a></p>
<h2>The Cake Pattern</h2>
<p>If you are writing new Scala application, you might not want to take in all the baggage that Spring Framework brings with it. (Slf4j, anyone?)</p>
<p>You would typically use the Cake Pattern to achieve something akin to dependency injection. Jonas Boner explained the Cake Pattern in one of his infamous <a title="Real-World Scala: Dependency Injection (DI)" href="http://jboner.github.com/2008/10/06/real-world-scala-dependency-injection-di.html" target="_blank">Real-World Scala Series blog post</a>. What we would try here is to use the Cake pattern to implement the same DI scenario in Scala and then compare that with its corresponding Spring implementation. In doing that we would hope to clear out some of the misty clouds over Scala and DI.</p>
<p>We also want to have a repository and a service, but without the XML configuration file. So, we need not only the repository and service interfaces themselves, but we also need components in which they &#8220;live&#8221;. Starting with the repository, we have:</p>
<pre class="brush:[scala]">trait UserRepositoryComponent {
  def userRepository : UserRepository

  trait UserRepository {
    def findAll: List[User]
  }
}

trait ORMUserRepositoryComponent extends UserRepositoryComponent {
  def userRepository = new ORMUserRepository(sf) //we need to actually instantiate the session factory here

  class ORMUserRepositry(val sf: SessionFactory) extends UserRepository {
    def findAll: List[User] = sf.query(...)
  }
}</pre>
<p>Good. We have the repository tier interface the <code>UserRepositoryComponent</code> provides a way to get to the <code>UserRepository</code> instance. We have also shown an implementation of the repository interfaces: the <code>ORMUserRepositoryComponent</code>&#8216;s <code>userRepository</code> function gives an ORM-based implementation of the <code>UserRepository</code>.</p>
<p>Now, we would like to define the interface to the services tier:</p>
<pre class="brush:[scala]">trait UserServiceComponent {
  def userService: UserService

  trait UserService {
    def findAll: List[User]
  }
}</pre>
<p>OK, we have the repository interface &amp; implementation and the service interface. The implementation of the service will need to have access to some implementation of the repository interface. Naturally, we don&#8217;t want to specify which concrete repository interface implementation we want to use. In fact, we would like to let the users of our code specify arbitrary implementation of the repository interfaces. Good thing we have the composition inheritance!</p>
<pre class="brush:[scala]">trait DefaultUserServiceComponent extends UserServiceComponent {
  this: UserRepositoryComponent =&gt; 

  def userService = new DefaultUserService

  class DefaultUserService extends UserService {
    def findAll = userRepository.findAll
  }
}</pre>
<p>Notice in particular <code>this: UserRepositoryComponent =&gt;</code>. This means that the instance of <code>DefaultUserServiceComponent</code> depends on the <code>UserRepositoryComponent</code>. (It&#8217;s a little more subtle than that, but for the purposes of this post it will do.) This is in function equivalent to Spring&#8217;s <code>@Autowired public DefaultUserService(final UserRepository userRepository)</code>. Just like the Spring application we have created, the Scala code does nothing yet. We need to wire it together in some kind of application!</p>
<pre class="brush:[scala]">object Application {
  val userServiceComponent = new DefaultUserServiceComponent with ORMUserRepositoryComponent
  val userService = userServiceComponent.userService
}

val userService = Application.userService
userService.findAll</pre>
<p>In Scala, there is no <code>ApplicationContext</code>, so we have to implement our own application. But where&#8217;s the dependency injection? Here: <code>new DefaultUserServiceComponent with ORMUserRepositoryComponent</code>, notice the <code>with ORMUserRepositoryComponent</code>. Figure 2 shows the Scala application.</p>
<p>Figure 2. Scala DI</p>
<p><a href="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/cake-application1.png"><img title="cake application" src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/cake-application1.png" alt="" width="600" /></a></p>
<h2>The comparison</h2>
<p>As you can see, the two approaches are completely different in their implementation. DI in Spring Framework is a runtime business and the component separation is left to the way in which we structure the configuration files. DI in Scala/Cake is a compile-time business with sharper component separation. Figure 3 gives the overall comparison.</p>
<p>Figure 3. The big picture</p>
<p><a href="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/compare.png"><img title="compare" src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/compare.png" alt="" width="600" /></a></p>
<h2>Summary</h2>
<p>As we have shown here, both pattern represent in function a kind of dependency injection &amp; management. However, the crucial difference is that the dependency injection (in Spring Framework) is useful to manage components, leaving us to carefully design the components. The Cake Pattern allows us to inject &amp; manage functionality. We use traits to assemble components with the functionality we require. It is a different approach to design. Let me repeat:</p>
<p>In plain dependency injection, we create components and we assemble these components together to form an application.<br />
Using the Cake Pattern, we create pieces of functionality and we assemble the functionality to form the application.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/12/15/dependency-injection-vs-cake-pattern/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>We still like Spring!</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/11/28/we-still-like-spring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=we-still-like-spring</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/11/28/we-still-like-spring/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 08:14:13 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Spock]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tests]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1450</guid>
		<description><![CDATA[With all the recent Scala posts, you might think that we&#8217;ve abandoned our bread and butter, the Spring Framework. Absolutely not! Spring is still the most popular Java EE application framework; its dependency injection container allows us to combine the &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/11/28/we-still-like-spring/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>With all the recent Scala posts, you might think that we&#8217;ve abandoned our <em>bread and butter</em>, the <a href="http://www.springframework.org">Spring Framework</a>.</p>
<p><em>Absolutely not!</em></p>
<p>Spring is still the most popular Java EE application framework; its dependency injection container allows us to combine the old-school XML with annotations and Java-based configuration. On top of the DI, there is the convenient support for dynamic AOP, data access; then we have all the enterprisey code (transaction management, scheduling, management, &#8230;). Top if off with excellent MVC implementation and in just the core of the framework, you have an excellent starting point for your applications! <em>And that&#8217;s ignoring all the goodies in</em> Spring Integration,  Spring Batch, Spring Data, <em>and many, many others.</em>
</p>
<p>But if you are keen to try something a bit more exotic, take a look at <a href="http://cakesolutions.org/specs2-spring.html" title="Specs2 Spring" target="_blank">Specs2 Spring</a>, which is the Spring Framework testing extension to the <a href="https://github.com/etorreborre/specs2" title="Specs2" target="_blank">Specs2</a> Scala-based testing framework.</p>
<h2>Spock Extension to simplify integration testing with Spring</h2>
<p>The motivation for the post and the project is that most of my Spring test code was becoming too complex and&#8211;as a result&#8211;the test coverage was suffering. I was growing tired of explicit mocking and clumsy Java syntax. There had to be something better: Spock. But Spock was missing the full Spring integration I was looking for. No longer! My code at <a href="https://github.com/janm399/spock-spring-it">https://github.com/janm399/spock-spring-it</a> fixes it and this post describes my motivation and the solution.</p>
<p>Most Spring enterprise applications use some <code>DataSource</code>s, <code>TransactionManager</code>s and other JEE beasts. Now, we would like to use Spock to perform the necessary integration testing, but we don&#8217;t really want to create separate application context files for the tests.</p>
<p>Instead, we would like to set up the JNDI environment for the test code and use the same application context files for both testing and production. This is where this project helps: the annotations on our test classes specify the JNDI environment we wish to build for the test.</p>
<p>Verba docent, exempla trahunt, so I&#8217;ll start you off with a sample. Let there be:</p>
<pre class="brush:[java]">public interface FooService {
	int x(String query);
}

@Service
@Transactional
public class DefaultFooService implements FooService {
	private HibernateTemplate hibernateTemplate;

	@Autowired
	public DefaultFooService(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public int x(String query) {
		Document d = new Document();
		d.setTitle("x");

		this.hibernateTemplate.saveOrUpdate(d);

		return query.length();
	}
}
</pre>
<p>To get this running, we give the <code>META-INF/spring/module-context.xml</code> configuration file:</p>
<pre class="brush:[xml]">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="..."
	   xsi:schemaLocation="..."&gt;

	&lt;context:component-scan base-package="org.spockframework.springintegration"/&gt;

	&lt;jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/test"
		expected-type="javax.sql.DataSource"/&gt;
	&lt;jee:jndi-lookup id="hibernateProperties"
		jndi-name="java:comp/env/bean/hibernateProperties"
		expected-type="...HibernateProperties"/&gt;
	&lt;tx:jta-transaction-manager /&gt;
	&lt;tx:annotation-driven /&gt;

	&lt;bean id="sessionFactory"
		class="org...hibernate3.AnnotationSessionFactoryBean"&gt;
		&lt;property name="dataSource" ref="dataSource"/&gt;
		&lt;property name="packagesToScan"&gt;
			&lt;list&gt;
				&lt;value&gt;org...example.domain&lt;/value&gt;
			&lt;/list&gt;
		&lt;/property&gt;
		&lt;property name="hibernateProperties"
			value="#{hibernateProperties.asProperties()}"/&gt;
	&lt;/bean&gt;

	&lt;bean id="hibernateTemplate" class="org...hibernate3.HibernateTemplate"&gt;
		&lt;property name="sessionFactory" ref="sessionFactory"/&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>This context file is the same for both tests and for production. The &#8220;variable&#8221; items (<code>DataSource</code>, <code>TransactionManager</code> and our custom <code>HibernateProperties</code>) beans are looked up from JNDI.</p>
<p>To the test, then. We have simply</p>
<pre class="brush:[groovy]">@IntegrationTest
@ContextConfiguration(locations = "classpath*:/META-INF/spring/module-context.xml")
class FooServiceTest extends Specification {
	@Autowired
	FooService service

	def y() {
		expect:
		result == this.service.x(param)

		where:
		param	| 	result
		"one"	|	3
		"two"	|	3
		"four"	|	4
	}

}
</pre>
<p>If I wanted to have another integration test (perhaps testing another class), I would write:</p>
<pre class="brush:[groovy]">@IntegrationTest
@ContextConfiguration(locations = "classpath*:/META-INF/spring/module-context.xml")
class SomeOtherServiceTest extends Specification {
	@Autowired
	SomeOtherService service

	def "testing service operation"() {
		expect:
		count = this.service.work(filter)

		where:
		filter	| 	count
		"Jan"	|	2
		"Ani"	|	1
		"Joe"	|	0
	}

}
</pre>
<p>The interesting part is the <code>@IntegrationTest</code> annotation. It is defined as</p>
<pre class="brush:[java]">@Jndi(
	dataSources = @DataSource(name = "java:comp/env/jdbc/test",
		driverClass = JDBCDriver.class,
		url = "jdbc:hsqldb:mem:test"),
	mailSessions = @MailSession(name = "java:comp/env/mail/foo"),
	transactionManager =
		@TransactionManager(name = "java:comp/TransactionManager"),
	beans =
		@Bean(name = "java:comp/env/bean/hibernateProperties",
			type = HibernateProperties.class)
)
@Transactional
@TransactionConfiguration(defaultRollback = true)
@Retention(RetentionPolicy.RUNTIME)
public @interface IntegrationTest {
}
</pre>
<p>The reason why I have defined the <code>@IntegrationTest</code> annotation is because I want to use it on the two test classes: the <code>FooServiceTest</code> and <code>SomeOtherServiceTest</code>. Naturally, I could have used the <code>@Jndi</code> annotation on the test classes, but that would bring [too much] duplication.</p>
<p>The Spock extension understands the <code>@Jndi</code> annotation and its elements; it prepares the environment for the test and then executes the test in the usual Spock way.</p>
<p>In addition to the &#8220;webless&#8221; tests, I have now included Spring MVC web testing. This allows us to write simple<br />
tests for our controllers; the test environment is as close to the real servlet container environment as possible. The web testing extension builds on the JNDI support and adds the <code>@WebContextConfiguration</code> annotation. Here is a simple<br />
test code:</p>
<pre class="brush:[java]">@Controller
public class IndexController {
	private ManagementService managementService;

	@Autowired
	public IndexController(ManagementService managementService) {
		this.managementService = managementService;
	}

	@RequestMapping(value = "/home/{name}", method = RequestMethod.GET)
	public String home(@PathVariable String name, Model model) {
		model.addAttribute("message", name);
		Message message = new Message();
		message.setSourceText(name);
		message.setProcessedText(name.toUpperCase());
		this.managementService.save(message);
		return "home";
	}

}</pre>
<p>The Spock test for this simple controller is equally simple <code>IndexControllerTest</code>:</p>
<pre class="brush:[groovy]">@WebTest
class IndexControllerTest extends WebSpecification {
	@Autowired
	def ManagementService managementService;

	def home() {
		when:
		def param = "hello"
		def wo = get("/home/%s", param)

		then:
		wo.modelAttribute("message") == param
		wo.html().contains param
		this.managementService.get(Message, 1L).sourceText == param
	}

}
</pre>
<p>The code is quite simple: we make a HTTP GET request to <code>/hello/hello</code> (which will execute the <code>hello</code> method of the <code>IndexController</code>). We assert that the model contains the expected attribute, that the generated HTML contains the model attribute and that the message has been persisted. To complete the picture, here&#8217;s the <code>@WebTest</code> annotation:</p>
<pre class="brush:[java]">@Transactional
@TransactionConfiguration(defaultRollback = true)
@WebContextConfiguration(
	value = "/WEB-INF/sw-servlet.xml",
	contextConfiguration =
		@ContextConfiguration("classpath*:/META-INF/spring/module-context.xml")
)
@Jndi(
	dataSources = @DataSource(name = "java:comp/env/jdbc/test",
			driverClass = JDBCDriver.class, url = "jdbc:hsqldb:mem:test"),
	beans = @Bean(name = "java:comp/env/bean/hibernateProperties",
		type = HibernateProperties.class)
)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface WebTest {
}
</pre>
<p>Again, the intention of the <code>@WebTest</code> annotation is to allow me to re-use it on all web tests. Looking at its source, the most important annotation is the <code>@WebContextConfiguration</code>. It sets the name of the file from which we want to build the <code>WebApplicationContext</code> and sets the <code>contextConfiguration</code>: the location of the configuration files from which we will build the &#8220;server-side&#8221; part of our web application.</p>
<h2>Building automatically</h2>
<p>Now that you have the source code, we must configure Maven to include the Groovy compiler and to run all our Spock specifications as part of the tests. The configuration is actually quite simple: all we have to do is to include the appropriate <code>build</code> plugins. In fact, the entire portion of the <code>build</code> configuration is simply:</p>
<pre class="brush:[xml]">
...

&lt;build&gt;
  &lt;!-- Mandatory plugins for using Spock --&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.gmaven&lt;/groupId&gt;
      &lt;artifactId&gt;gmaven-plugin&lt;/artifactId&gt;
      &lt;version&gt;1.3&lt;/version&gt;
      &lt;configuration&gt;
        &lt;providerSelection&gt;1.7&lt;/providerSelection&gt;
      &lt;/configuration&gt;
      &lt;executions&gt;
        &lt;execution&gt;
          &lt;goals&gt;
            &lt;goal&gt;compile&lt;/goal&gt;
            &lt;goal&gt;testCompile&lt;/goal&gt;
          &lt;/goals&gt;
        &lt;/execution&gt;
      &lt;/executions&gt;
      &lt;dependencies&gt;
        &lt;dependency&gt;
          &lt;groupId&gt;org.codehaus.gmaven.runtime&lt;/groupId&gt;
          &lt;artifactId&gt;gmaven-runtime-1.7&lt;/artifactId&gt;
          &lt;version&gt;1.3&lt;/version&gt;
          &lt;exclusions&gt;
            &lt;exclusion&gt;
              &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
              &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
            &lt;/exclusion&gt;
          &lt;/exclusions&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
          &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
          &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
          &lt;version&gt;1.7.5&lt;/version&gt;
        &lt;/dependency&gt;
      &lt;/dependencies&gt;
    &lt;/plugin&gt;
    &lt;!-- Optional plugins for using Spock --&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.spockframework&lt;/groupId&gt;
      &lt;artifactId&gt;spock-maven&lt;/artifactId&gt;
      &lt;version&gt;${project.version}&lt;/version&gt;
      &lt;!-- you need to specify a concrete version number here --&gt;
      &lt;executions&gt;
        &lt;execution&gt;
          &lt;goals&gt;
            &lt;goal&gt;find-specs&lt;/goal&gt;
          &lt;/goals&gt;
        &lt;/execution&gt;
      &lt;/executions&gt;
    &lt;/plugin&gt;

    ...
  &lt;/plugins&gt;
&lt;/build&gt;

...
</pre>
<h2>Downloads &amp; Summary</h2>
</p>
<p>So, get your hands on the source code at <a href="https://github.com/janm399/spock-spring-it">https://github.com/janm399/spock-spring-it</a>: it is ready to be compiled and used in your projects. A <em>proper</em> documentation &amp; downloads is coming soon to <a href="http://www.cakesolutions.org">http://cakesolutions.org</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/11/28/we-still-like-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why Java</title>
		<link>http://www.cakesolutions.net/teamblogs/2010/08/23/why-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-java</link>
		<comments>http://www.cakesolutions.net/teamblogs/2010/08/23/why-java/#comments</comments>
		<pubDate>Mon, 23 Aug 2010 16:33:00 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JVM]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=652</guid>
		<description><![CDATA[At Cake Solutions, we have been using Java for quite a few years. Recently, I had to formulate why our customers should chose Java over other languages. It was easy to come up with geeky reasons, but purely technical reasons &#8230; <a href="http://www.cakesolutions.net/teamblogs/2010/08/23/why-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At Cake Solutions, we have been using Java for quite a few years. Recently, I had to formulate why our customers should chose Java over other languages. It was easy to come up with <i>geeky</i> reasons, but purely technical reasons on their own are not enough. It turns out that modern Java EE applications are successful, interesting and exciting because of all the tools we have in the Java world&#8211;it boils down to the fact that I believe that a lot of the innovation we see in contemporary computing runs on the JVM and with JDK 1.7, we should see even more exciting developments.<br />
In the meantime, <a href='http://www.cakesolutions.net/teamblogs/wp-content/uploads/2010/08/whyjvm.pdf'>download the Why Java PDF</a>, where I try to explain why you should use JVM-based platform over anything else.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2010/08/23/why-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Publish or perish</title>
		<link>http://www.cakesolutions.net/teamblogs/2010/03/31/publish-or-perish/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=publish-or-perish</link>
		<comments>http://www.cakesolutions.net/teamblogs/2010/03/31/publish-or-perish/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 18:10:31 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Book]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring 3]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=578</guid>
		<description><![CDATA[As the old adage goes, one needs to publish or be forgotten. It&#8217;s been quite some time since we gave you Pro Spring 2.5; in that time, Spring 3.0, then 3.0.1 came out and we&#8217;re all eagerly awaiting Spring 3.1. &#8230; <a href="http://www.cakesolutions.net/teamblogs/2010/03/31/publish-or-perish/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As the old adage goes, one needs to publish or be forgotten. It&#8217;s been quite some time since we gave you Pro Spring 2.5; in that time, Spring 3.0, then 3.0.1 came out and we&#8217;re all eagerly awaiting Spring 3.1.<br />
Now, I&#8217;ve been fighting off the writing bug for quite some time, but no more. I am starting work on the new Spring &#8220;book&#8221;, except this time, it will not be a book at all. I will publish the PDFs of the various chapters here on our blog and I will also run the best parts of the text in the Open Source Journal&#8211;yes, the printed edition.<br />
So, keep an eye on this space for the first chapter&#8211;give me 2 &#8211; 3 weeks from now!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2010/03/31/publish-or-perish/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>October North West Spring User Group Meeting</title>
		<link>http://www.cakesolutions.net/teamblogs/2009/10/19/october-sug-northwest/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=october-sug-northwest</link>
		<comments>http://www.cakesolutions.net/teamblogs/2009/10/19/october-sug-northwest/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 08:36:16 +0000</pubDate>
		<dc:creator>Andrew Chalkley</dc:creator>
				<category><![CDATA[Andrew C's Blog]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Integration]]></category>
		<category><![CDATA[Spring User Group]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=469</guid>
		<description><![CDATA[Last Tuesday was the North West Spring User Group. I was asked to deliver my jQuery talk that I gave to the South Spring User Group back in September last year. It&#8217;s always good talking about jQuery as it&#8217;s relatively &#8230; <a href="http://www.cakesolutions.net/teamblogs/2009/10/19/october-sug-northwest/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Last Tuesday was the North West Spring User Group. I was asked to deliver my jQuery talk that I gave to the South Spring User Group back in <a href="http://skillsmatter.com/podcast/java-jee/jquery">September</a> last year.</p>
<p>It&#8217;s always good talking about jQuery as it&#8217;s relatively straight forward for the audience to read and has a shallow learning curve (if you know CSS already). One of the other pleasures talking about jQuery, and other front end tech, is that you can always show interactive demos to &#8220;wow&#8221; the audience&#8230;</p>
<p>Here are my slides followed by a link to my demo code:</p>
<div style="width:425px;text-align:left" id="__ss_2273365"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/chalkley/jquery-sug-group-introduction" title="jQuery SUG Group Introduction">jQuery SUG Group Introduction</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=jquery-091019025326-phpapp02&#038;stripped_title=jquery-sug-group-introduction" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=jquery-091019025326-phpapp02&#038;stripped_title=jquery-sug-group-introduction" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/chalkley">Andrew Chalkley</a>.</div>
</div>
<p>I brought some of my demo code up to date showing examples using the <a href="http://docs.jquery.com/Events/live">live</a>, event delegation functionality with jQuery. You can view my demo <a href="http://cakesolutions.net/jquery_demo/jquery.html">here</a> or download it zipped <a href="http://cakesolutions.net/jquery_demo/jquery.zip">here</a>.</p>
<p>If you have any queries about the above or want assist you in a jQuery, Javascript and AJAX project <a href="http://www.cakesolutions.net/contact.html">contact us</a>.</p>
<h2>Spring Integration</h2>
<p>Jonas Partner from OpenCredo also gave a presentation on the evening on Spring Integration. His slides are below:</p>
<div style="width:425px;text-align:left" id="__ss_2292034"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/chalkley/spring-integration-2292034" title="Spring Integration">Spring Integration &#8211; Jonas Partner</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=nwsugspringintegration-091020075822-phpapp01&#038;stripped_title=spring-integration-2292034" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=nwsugspringintegration-091020075822-phpapp01&#038;stripped_title=spring-integration-2292034" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/chalkley">Jonas Partner</a>.</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2009/10/19/october-sug-northwest/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Today&#8217;s web applications</title>
		<link>http://www.cakesolutions.net/teamblogs/2009/09/22/todays-web-applications/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=todays-web-applications</link>
		<comments>http://www.cakesolutions.net/teamblogs/2009/09/22/todays-web-applications/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 16:40:18 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[LDW]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=459</guid>
		<description><![CDATA[I gave a talk on today&#8217;s Java EE and related web applications at yesterday’s London Digital Week event at Skills Matter. I had a full room of geeks keen to find out what I think about web application development. I &#8230; <a href="http://www.cakesolutions.net/teamblogs/2009/09/22/todays-web-applications/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I gave a talk on today&#8217;s Java EE and related web applications at yesterday’s London Digital Week event at <a href="http://skillsmatter.com">Skills Matter</a>. I had a full room of geeks keen to find out what I think about web application development. I hope that all attendees learned at least one new thing and that they&#8217;ll all find the time to try out Spring, Ruby on Rails or Grails.<br />
To get started, you can download the source code of the talk from <a href="http://github.com/janm399/ldw/tree/master">http://github.com/janm399/ldw/tree/master</a>; the PDF version of the talk is available at <a href="http://github.com/janm399/ldw/raw/master/talk/ldw-pdf.pdf">http://github.com/janm399/ldw/raw/master/talk/ldw-pdf.pdf</a>.</p>
<p>I&#8217;m looking forward to seeing most of you again at the next Java User Group or Spring User Group event!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2009/09/22/todays-web-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>That&#8217;s what I call performance</title>
		<link>http://www.cakesolutions.net/teamblogs/2009/08/27/thats-what-i-call-performance/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=thats-what-i-call-performance</link>
		<comments>http://www.cakesolutions.net/teamblogs/2009/08/27/thats-what-i-call-performance/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 15:00:22 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Performance tuning]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=445</guid>
		<description><![CDATA[We are completing work on caching and routing tier we added to a lived-in system. The performance increase is very substantial and I will write a lot more about how we achieved this next week. For now, I&#8217;ll wet your &#8230; <a href="http://www.cakesolutions.net/teamblogs/2009/08/27/thats-what-i-call-performance/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We are completing work on caching and routing tier we added to a lived-in system. The performance increase is very substantial and I will write a lot more about how we achieved this next week.<br />
For now, I&#8217;ll wet your appetite with a screenshot that says it all<br />
<div id="attachment_446" class="wp-caption alignleft" style="width: 435px"><a href="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2009/08/Picture-1.png"><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2009/08/Picture-1.png" alt="Service node statistics" title="Service node statistics" width="425" height="631" class="size-full wp-image-446" /></a><p class="wp-caption-text">Service node statistics</p></div><br />
P.S. Yes, we&#8217;re talking about the <code>RDTSC</code> and <code>System.nanoTime()</code>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2009/08/27/thats-what-i-call-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

