<?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; Jan&#8217;s Blog</title>
	<atom:link href="http://www.cakesolutions.net/teamblogs/category/jans-blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cakesolutions.net/teamblogs</link>
	<description>void magic() { }</description>
	<lastBuildDate>Fri, 03 Feb 2012 13:05:28 +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>Specs2 Spring 0.4</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/02/02/specs2-spring-0-4/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=specs2-spring-0-4</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/02/02/specs2-spring-0-4/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 09:12:53 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Acceptance testing]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[Specs2]]></category>
		<category><![CDATA[Specs2 Spring]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1967</guid>
		<description><![CDATA[We&#8217;re pleased to release version 0.4 of Specs2 Spring! 0.4 follows the very short-lived Maven Central practice-release 0.3. We now include support for Spring 2.5, 3.0 and 3.1; for the latest verion of Spring, we include bean profiles and environment &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/02/02/specs2-spring-0-4/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re pleased to release version 0.4 of Specs2 Spring!</p>
<p>0.4 follows the very short-lived Maven Central practice-release 0.3. We now include support for Spring 2.5, 3.0 and 3.1; for the latest verion of Spring, we include bean profiles and environment variables settable from the test annotations. We have also included support for raw SessionFactory and HibernateTemplate to work with the most popular ORM tool. The updates include:</p>
<ul>
<li>Supports Spring 2.5 through 3.1, including environment values and bean profiles in 3.1,</li>
<li>Test data setup (using BeanTables) now works with HibernateTemplate as well as SessionFactory in Hibernate 4</li>
<li>The @Bean annotation’s type value is now clazz to make it usable from Scala code</li>
</ul>
<p>Most excitingly, Specs2 Spring is now available in <a href="http://search.maven.org/#search%7Cga%7C1%7Corg.specs2" title="Maven Central" target="_blank">Maven Central</a> and <a href="https://oss.sonatype.org/index.html#nexus-search;quick~org.specs2" title="Sonatype OSS">Sonatype OSS</a>! All you need to do now is to include the dependency in your pom.xml:</p>
<pre class="brush:[xml]">
&lt;dependency&gt;
    &lt;groupId&gt;org.specs2&lt;/groupId&gt;
    &lt;artifactId&gt;spring_2.9.1&lt;/artifactId&gt;
    &lt;version&gt;0.4&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>To get started, download the <a href="http://www.cakesolutions.org/static/specs2-spring/0.4/api/index.html#package" title="ScalaDoc" target="_blank">ScalaDocs</a> and <a href="http://www.cakesolutions.org/static/specs2-spring/0.4/main.pdf" title="User guide" target="_blank">PDF user guide</a>; check out the <a href="http://www.cakesolutions.org/specs2-spring.html" target="_blank">http://www.cakesolutions.org/specs2-spring.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/02/02/specs2-spring-0-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Publishing SBT projects to Nexus</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/01/28/publishing-sbt-projects-to-nexus/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=publishing-sbt-projects-to-nexus</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/01/28/publishing-sbt-projects-to-nexus/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 08:02:16 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Maven Central SBT]]></category>
		<category><![CDATA[SBT GPG]]></category>
		<category><![CDATA[SBT release]]></category>
		<category><![CDATA[Sonatype SBT]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1951</guid>
		<description><![CDATA[Specs2 Spring is available on Sonatype OSS and Maven Central! But how did we get there and what should you do to get the hosting, synchronisation to Maven Central and how do you automate the deployment process? Let&#8217;s tackle one &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/01/28/publishing-sbt-projects-to-nexus/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.cakesolutions.org/specs2-spring.html">Specs2 Spring</a> is available on <a href="https://oss.sonatype.org/content/repositories/releases/org/specs2/spring_2.9.1/" target="_blank">Sonatype OSS</a> and <a href="http://search.maven.org/#search%7Cga%7C1%7Corg.specs2" target="_blank">Maven Central</a>! But how did we get there and what should you do to get the hosting, synchronisation to Maven Central and how do you automate the deployment process? Let&#8217;s tackle one thing at a time:</p>
<h2>Sonatype OSS support</h2>
<p>The first thing to is to open an issue in Sonatype&#8217;s JIRA, asking them to set up the Nexus repository for you. Once that&#8217;s done, you will be able to publish your snapshots and releases to Sonatype; the releases are then synchronised to Maven Central. The first few pages of <a href="https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide" target="_blank">Sonatype OSS Maven Repository Usage Guide</a> will show you how to get started.</p>
<h2>Building and publishing</h2>
<p>Now, this is the interesting bit. We are using SBT to build the project and we&#8217;d like to be able to run <code>sbt publish</code> to compile, package and publish the project to Sonatype automatically. Before we can do that, we need to configure GPG and SBT plugin that uses GPG to sign the artefacts. The plugin is <code>xsbt-gpg-plugin</code>, which will use GPG to sign the artefacts&#8211;properly signed artefacts are the requirement for Maven Central synchronisation. So, with the plugin, your <code>project/plugins.sbt</code> file should contain:</p>
<pre class="brush:[scala]">
...
resolvers += Resolver.url("scalasbt", /* no new line */
  new URL("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases")) /* no new line */
  (Resolver.ivyStylePatterns)

addSbtPlugin("com.jsuereth" % "xsbt-gpg-plugin" % "0.5")
...
</pre>
<p>If you do not have GPG, you must also install &#038; configure it for your platform; if you do not have your keys, you must also generate key pair and then publish your public key. I cannot quite show you how to do this on Windows (sorry, get a Mac!). On OS X, you can use <a href="http://www.gpgtools.org/index.html" title="GPG Tools" target="_blank">GPG Tools</a>. Download and install it; the first thing GPG Tools will prompt you to do is to generate your key, protected by a passphrase. (I recommend that you keep the passphrase <em>very long</em>, as <a href="http://xkcd.com" title="XKCD" target="_blank">XKCD</a> points out in Figure 1!)</p>
<p>Figure 1. Key strengths</p>
<p><img src="http://imgs.xkcd.com/comics/password_strength.png"/></p>
<p>Before I can release the artefacts in Sonatype OSS releases and in Maven Central, I need to publish my public keys (so that others can verify that the artefacts are intact and that it was I who has produced them). To do that, you can use the GPG Keychain Access (see Figure 2) tool or use the <code>gpg</code> command-line program.</p>
<p>Figure 2. GPG Keychain Access</p>
<p><a href="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2012/01/gpgkeychainaccess.png"><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2012/01/gpgkeychainaccess-300x152.png" alt="" title="gpgkeychainaccess" width="300" height="152" /></a></p>
<p>We are programmers, so let&#8217;s turn to the command line: we need to export a key, but to do that, we need to know its identifier:</p>
<pre class="brush:[bash]">
$ gpg --list-secret-keys
/Users/janmachacek/.gnupg/secring.gpg
-------------------------------------
sec   2048R/90A468A9 2012-01-30 [expires: 2016-01-30]
uid                  Jan Machacek &lt;jan.machacek@gmail.com&gt;
ssb   2048R/A9ED23D0 2012-01-30

$ gpg --send-keys 90A468A9
</pre>
<p>Your public key is now uploaded to the default key server (specified in <code>~/.gnupg/gpg.conf</code>) and it will be distributed to other key servers over the next few minutes. Once that happens, you&#8217;ll be ready to release your artefacts to Maven Central.</p>
<h3>Releasing</h3>
<p>Before we&#8217;ll configure the JAR signing, we must deal with the publish process. We set the <code>publishTo</code> (and several other settings) in <code>build.sbt</code> to use the Sonatype repository like so:</p>
<pre class="brush:[scala]">

publishTo &lt;&lt;= version { v: String =&gt;
  val nexus = "https://oss.sonatype.org/"
  if (v.trim.endsWith("SNAPSHOT"))
    Some("snapshots" at nexus + "content/repositories/snapshots")
  else
    Some("releases" at nexus + "service/local/staging/deploy/maven2")
}
</pre>
<p>Before we can publish our SBT-based project, we must ensure that its generated Maven POMs match the strict requirements of Sonatype and Maven Central. So, we must include the following code in your <code>build.sbt</code>:</p>
<pre class="brush:[scala]">
publishMavenStyle := true

publishArtifact in Test := false

pomIncludeRepository := { x =&gt; false }

pomExtra := (
  &lt;url&gt;http://www.cakesolutions.org/specs2-spring.html&lt;/url&gt;
  &lt;licenses&gt;
    &lt;license&gt;
      &lt;name&gt;BSD-style&lt;/name&gt;
      &lt;url&gt;http://www.opensource.org/licenses/bsd-license.php&lt;/url&gt;
      &lt;distribution&gt;repo&lt;/distribution&gt;
    &lt;/license&gt;
  &lt;/licenses&gt;
  &lt;scm&gt;
    &lt;url&gt;git@github.com:janm399/specs2-spring.git&lt;/url&gt;
    &lt;connection&gt;scm:git:git@github.com:janm399/specs2-spring.git&lt;/connection&gt;
  &lt;/scm&gt;
  &lt;developers&gt;
    &lt;developer&gt;
      &lt;id&gt;janmachacek&lt;/id&gt;
      &lt;name&gt;Jan Machacek&lt;/name&gt;
      &lt;url&gt;http://cakesolutions.org&lt;/url&gt;
    &lt;/developer&gt;
  &lt;/developers&gt;
)
</pre>
<p>Now, before we even attempt to run <code>sbt publish</code>, we need to specify the credentials for the Sonatype repository. But we don&#8217;t want to do that in the files we push to the VCS! Instead, we&#8217;ll create file <code>~/.sbt/sonatype.sbt</code>, which sets the <code>credentials</code> setting to the Sonatype ones:</p>
<pre class="brush:[scala]">
credentials += Credentials("Sonatype Nexus Repository Manager",
                           "oss.sonatype.org",
                           "your-sonatype-username",
                           "your-sonatype-password")
</pre>
<p>The work is done! We&#8217;ve modified </p>
<ul>
<li><code>~/.sbt/sonatype.sbt</code> with the Sonatype OSS credentials</li>
<li><code>project/plugins.sbt</code> with the <code>xsbt-gpg-plugin</code> plugin to sign the artefacts</li>
<li><code>build.sbt</code> to include the release settings</li>
</ul>
<p>Now we can run <code>sbt publish</code>, supply our key phrase go GPG and push the artefacts to Sonatype. If you are publishing snapshot release, then your work is done. If you are publishing a &#8220;real&#8221; release, keep reading.</p>
<h3>Promoting</h3>
<p>Once you&#8217;ve published your non-snapshot release, you will need to go to the Sonatype Nexus, login, select the staging repository and close it. (Again, follow the Sonatype Nexus guide for details.) Closing will verify that the Maven POMs are well formed, that the artefacts&#8217; signatures are valid. If all is well, your repository will end up in Maven Central within a few hours&#8217; time!</p>
<h2>Summary</h2>
<p>Publishing SBT-based projects to Sonatype and then Maven Central is easy&#8211;once you&#8217;ve dealt with the details of the Maven POMs. For complete views of the <code>build.sbt</code> and <code>project/plugins.sbt</code> files, take a look at Specs2 Spring&#8217;s sources at <a href="https://www.github.com/janm399/specs2-spring" target="_blank">https://www.github.com/janm399/specs2-spring</a>.</p>
<p>Josh Suereth (<a href="http://jsuereth.com/" target="_blank">http://jsuereth.com/</a>), the maintainer of the <code>xsbt-gpg-plugin</code> SBT plugin maintains a page where he outlines the latest details of the SBT deployment process. <a href="http://scala-sbt.org/using_sonatype.html" target="_blank">Clicky-here</a> to see Josh&#8217;s instructions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/01/28/publishing-sbt-projects-to-nexus/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Specs2 Spring from sources</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/01/23/specs2-spring-from-sources/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=specs2-spring-from-sources</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/01/23/specs2-spring-from-sources/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 19:13:59 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[SBT Docbook plugin]]></category>
		<category><![CDATA[Specs2 Spring]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1931</guid>
		<description><![CDATA[Specs2 Spring is going into Maven Central as soon as possible (I&#8217;ve submitted a request at https://issues.sonatype.org/browse/OSSRH-2760), which means that all you&#8217;ll have to do to use it in your projects is to add: &#60;dependency&#62; &#60;groupId&#62;org.specs2&#60;/groupId&#62; &#60;artifactId&#62;spring_${scala.version}&#60;/artifactId&#62; &#60;version&#62;0.3&#60;/version&#62; &#60;scope&#62;test&#60;/scope&#62; &#60;/dependency&#62; &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/01/23/specs2-spring-from-sources/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Specs2 Spring is going into Maven Central as soon as possible (I&#8217;ve submitted a request at <a href="https://issues.sonatype.org/browse/OSSRH-2760" target="_blank">https://issues.sonatype.org/browse/OSSRH-2760</a>), which means that all you&#8217;ll have to do to use it in your projects is to add:</p>
<pre class="brush:[xml]">
&lt;dependency&gt;
  &lt;groupId&gt;org.specs2&lt;/groupId&gt;
  &lt;artifactId&gt;spring_${scala.version}&lt;/artifactId&gt;
  &lt;version&gt;0.3&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>Where <code>scala.version</code> property is <code>2.9.1</code>; or, if you prefer SBT, simply add to <code>libraryDependencies</code>:</p>
<pre class="brush:[scala]">
libraryDependencies ++= Seq(
  "org.specs2" %% "spring" % "0.3"
)
</pre>
<h2>What to do in the next few days/weeks</h2>
<p>But before that happens, you&#8217;ll need to build Specs2 Spring yourself. The good news is that it&#8217;s not at all difficult. You&#8217;ll need:</p>
<ol>
<li>Paul Phillips&#8217;s SBT Extras at <a href="https://github.com/paulp/sbt-extras">https://github.com/paulp/sbt-extras</a></li>
<li>Clones of <a href="https://github.com/janm399/sbt-docbook-plugin">https://github.com/janm399/sbt-docbook-plugin</a> and <a href="https://github.com/janm399/specs2-spring">https://github.com/janm399/specs2-spring</a></li>
</ol>
<p>Once you download the SBT Extras shell script, put it somewhere you remember and add it to your <code>PATH</code>. In my case, I copied the SBT Extras <code>sbt</code> script to <code>/usr/share/scala/sbt</code> and I&#8217;ve modified <code>/etc/profile</code> to say:</p>
<pre class="brush:[bash]">
export PATH=$PATH:/usr/share/scala/sbt
</pre>
<p>Next, clone the two repositories to some directory, say <code>~/sandbox</code>. Then you need to publish both projects to your local Ivy repository (this is where they are going to be picked up from later on). </p>
<pre class="brush:[bash]">
~/sandbox$ cd sbt-docbook-plugin
~/sandbox/sbt-docbook-plugin$ sbt publish-local
~/sandbox/sbt-docbook-plugin$ cd ../specs2-spring
~/sandbox/specs2-spring$ sbt publish-local
</pre>
<p>And you&#8217;re ready to go. The <code>"de.undercouch" % "sbt-docbook-plugin" % "0.2-SNAPSHOT"</code> <code>"org.specs2" % "spring" % "0.3"</code> are now available in your local Ivy repository; and you can use them in your Maven or SBT projects.</p>
<p>If you would like to contribute, and if you use <a href="http://www.jetbrains.com/idea">IntelliJ IDEA</a>, you can generate the IntelliJ IDEA project files by running <code>sbt gen-idea</code> in both projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/01/23/specs2-spring-from-sources/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mixin composition using reflection</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/01/23/mixin-composition-using-reflection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mixin-composition-using-reflection</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/01/23/mixin-composition-using-reflection/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 13:00:35 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Reflection mixins]]></category>
		<category><![CDATA[Reflection with]]></category>
		<category><![CDATA[Scala 2.9.1]]></category>
		<category><![CDATA[Scala reflection]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1922</guid>
		<description><![CDATA[I wanted to be able to construct Scala beans in my Spring application context, but I also wanted to be able to specify the mixins to be included in the constructed bean: &#60;?xml version="1.0" encoding="UTF-8"?&#62; &#60;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" xmlns:scala="http://www.springframework.org/schema/scala" &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/01/23/mixin-composition-using-reflection/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I wanted to be able to construct Scala beans in my Spring application context, but I also wanted to be able to specify the mixins to be included in the constructed bean:</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"
  xmlns:scala="http://www.springframework.org/schema/scala"
  xsi:schemaLocation=...&gt;

  &lt;scala:bean class="org.cakesolutions.scala.services.UserService" &gt;
    &lt;scala:with trait="org.cakesolutions.scala.services.Mixin1" /&gt;
    &lt;scala:with trait="org.cakesolutions.scala.services.Mixin2" /&gt;

    &lt;scala:property name="dependency" value="Injected" /&gt;
  &lt;scala:bean&gt;

&lt;/beans&gt;
</pre>
<p>The difficulty is that <code>Class.forName</code> function does not allow me to specify the mixins. In the end, I modified a very hacky solution on Stack Overflow (which did not quite work in Scala 2.9 and only used one mixin). The solution involves generating classes that are similar to the classes that the Scala compiler generates when we run something like <code>new Cat with Eating with Speaking</code>. So, here it is in its full gory:</p>
<pre class="brush:[scala]">
class ScalaBeanFactory(private val beanType: Class[_ &lt;: AnyRef],
                       private val mixinTypes: Seq[Class[_ &lt;: AnyRef]]) {
  val loader = new DynamicClassLoader
  val clazz = loader.buildClass(beanType, mixinTypes)

   def getTypedObject[T] = getObject.asInstanceOf[T]

   def getObject = {
     clazz.newInstance()
   }

   def getObjectType = null

   def isSingleton = true

}

object DynamicClassLoader {
  private var id = 0
  def uniqueId = synchronized {  id += 1; "Klass" + id.toString }
}

class DynamicClassLoader extends java.lang.ClassLoader(getClass.getClassLoader) {

  def buildClass(t: Class[_ &lt;: AnyRef], vs: Seq[Class[_ &lt;: AnyRef]]) = {
    val id = DynamicClassLoader.uniqueId

    val classDef = new StringBuilder

    classDef.append("class ").append(id)
    classDef.append(" extends ").append(t.getCanonicalName)
    vs.foreach(c => classDef.append(" with %s".format(c.getCanonicalName)))

    val settings = new Settings(null)
    settings.usejavacp.value = true
    val interpreter = new IMain(settings)

    interpreter.compileString(classDef.toString())

    val r = interpreter.classLoader.getResourceAsStream(id)
    val o = new ByteArrayOutputStream
    val b = new Array[Byte](16384)
    Stream.continually(r.read(b)).takeWhile(_ &gt; 0).foreach(o.write(b, 0, _))
    val bytes = o.toByteArray

    defineClass(id, bytes, 0, bytes.length)
  }

}
</pre>
<p>The code cannot yet deal with constructors with parameters and does not copy annotations from the parent class&#8217;s constructor (should it do that?). However, it gives us a good starting point that is usable in the <code>scala</code> Spring namespace. Of course, don&#8217;t just take my word for it, verify it in a Specs2 specification:</p>
<pre class="brush:[scala]">
class ScalaBeanFactorySpec extends Specification {

  "getTypedObject mixes-in the specified traits" in {
    val f1 = new ScalaBeanFactory(classOf[Cat],
                                  Seq(classOf[Speaking], classOf[Eating]))

    val c1 = f1.getTypedObject[Cat with Eating with Speaking]

    c1.isInstanceOf[Cat with Eating with Speaking] must_==(true)

    /*
    c1.speak    // in trait Speaking
    c1.eat      // in trait Eating
    c1.meow     // in class Cat
    */
  }

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/01/23/mixin-composition-using-reflection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What can Scala do for you?</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/01/20/what-can-scala-do-for-you/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-can-scala-do-for-you</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/01/20/what-can-scala-do-for-you/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 14:17:48 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala complexity]]></category>
		<category><![CDATA[Scala usefulness]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1894</guid>
		<description><![CDATA[There are many new languages on the Java platform alongside the official Java language. Many have heard about Scala and many are considering using it in their code. So, how can Scala make your systems better? Is it really incredibly &#8230; <a href="http://www.cakesolutions.net/teamblogs/2012/01/20/what-can-scala-do-for-you/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There are many new languages on the Java platform alongside the official Java language. Many have heard about <a href="http://scala-lang.org" target="_blank">Scala</a> and many are considering using it in their code. So, how can Scala make your systems better? Is it really incredibly complex language that is simply far too difficult to use? Is it only suitable for very niche areas of development? Or is it a true general-purpose language, the Java of the future?</p>
<h2>What is Scala</h2>
<p>Scala is a type-safe, object-functional language. Scala allows you to build scalable (no, really?) systems by attempting to address the complexity of large systems. Its functional nature allows you to focus on the procedures in your system rather than the components in which these procedures live. Finally, Scala remains object-orieted, giving you the familiar inheritance, encapsulation and polymorphism.</p>
<p>In Scala, a functions is a first-class type; and as such can be assigned to a variable or passed as argument. You can kiss good-bye to the anonymous implementations of interfaces containing exactly one method: replace them with functions. But Scala goes further: its functions can accept functions as parameters and return functions; you can supply only some parameters of a function and the Scala compiler will create a new function that takes the remaining parameters! Finally, Scala functions can also have multiple parameter lists!</p>
<pre class="brush:[scala]">
def curry(i: Int)(j: Int) = i * j
val f = (x: Double, y: Double) =&gt; x * y
val fWithXEq5 = f(5, _: Double)
val oneTimeX = curry(1)_

fWithXEq5(3)   // == 15
curry(1)(2)    // == 2
oneTimeX(2)    // == 2
</pre>
<p>In Scala, you compose functionality through composition inheritance. You can think of this as multiple implementation inheritance with some terms and conditions; the closest equivalent in Java would be an interface with method bodies. With careful design, you can inject functionality to the objects that you construct; while keeping the elements (<code>trait</code>s in Scala speak) completely isolated and independent.</p>
<pre class="brush:[scala]">
trait Speakable {
  def sound: String

  def speak() {
    val voice = VoiceManager.getInstance().getVoice("kevin16")
    voice.allocate()
    voice.speak(sound)
    voice.deallocate()
  }
}

abstract class Animal {
  def sound: String
}
class Dog extends Animal {
  def sound = "Woof"
}
class Cat extends Animal {
  def sound = "Meow"
}
class SpeakingCat extends Cat with Speakable 

val cat = new Cat with Speakable
val dog = new Dog with Speakable
val muteDog = new Dog
val speakingCat = new SpeakingCat

cat.speak()           // OK, meows
dog.speak()           // OK, woofs
speakingCat.speak()   // OK, meows
muteDog.speak()       // Does not compile
</pre>
<p>Notice that I was able to mix-in the <code>Speakable</code> trait to either individual instances or create a new subclass of <code>Cat</code> with the speaking trait mixed-in.</p>
<p>You can also express meaning in the types in your code; meaning that in Java is impossible to convey in the source code and we must rely on the programmers&#8217; common sense.</p>
<pre class="brush:[scala]">
abstract class Animal {
  type SuitableFood &lt;: Food
}
class Cat extends Animal {
  type SuitableFood = CatFood
}
class Dog extends Animal {
  type SuitableFood = DogFood
}

abstract class Food
class CatFood extends Food
class LuxuryCatFood extends CatFood
class DogFood extends Food

def feed[A &lt;: Animal, F &lt;: A#SuitableFood](animal: A, food: F) =
  // somehow feed food to animal
</pre>
<p>I have expressed the common sense knowledge that a cat will eat cat food (just about), it will certainly eat luxury cat food, but will not touch dog food. The function <code>feed</code> enforces this at compile time!</p>
<pre class="brush:[scala]">
feed(new Cat, new CatFood)       // OK
feed(new Cat, new LuxuryCatFood) // OK
feed(new Cat, new DogFood)       // Don't be silly; does not compile!
</pre>
<h4>See! Too complicated</h4>
<p>You might be thinking, &#8220;this is exactly the complexity I don&#8217;t want in my code!&#8221; Yes, the code I&#8217;ve shown is more complex than your Java code, but it <em>does so much more!</em> It is impossible to express the concepts I&#8217;ve shown in Java as clearly and as succinctly as I can do in Scala. Yes, Scala code can be complex, but not because the language is inherently and needlessly complex, but because it can solve very complicated problems.</p>
<h4>All right, it&#8217;s not complex, but it&#8217;s not really useful</h4>
<p>Scala is brilliantly useful, because it <em>compiles to the standard Java byte code</em> and because it can use all your existing Java code. Combine Java and Scala and implement polyglot codebase that uses the best language to solve your problems! Look&#8211;you can even have use Scala with <a href="http://www.springframework.org" target="_blank">Spring Framework</a>!</p>
<pre class="brush:[scala]">
@Controller
class UserController @Autowired() (private val userService: UserService) {

  @RequestMapping(value = "/users", method = RequestMethod.GET)
  @ModelAttribute("users")
  def index = userService.findAll

}
</pre>
<h2>Find out more!</h2>
<p>Try out Scala, ask us for advice, guidance and mentoring, and you will have polyglot codebase that uses the best language to solve your problems! I&#8217;d be delighted to show you how to combine Scala in traditional Java EE applications either by implementing discrete portion of your application in Scala or even implementing most of your application in Scala, but using your existing Java.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/01/20/what-can-scala-do-for-you/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maven to SBT</title>
		<link>http://www.cakesolutions.net/teamblogs/2012/01/04/maven-to-sbt/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maven-to-sbt</link>
		<comments>http://www.cakesolutions.net/teamblogs/2012/01/04/maven-to-sbt/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 15:35:08 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Building Scala]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Multi-project SBT]]></category>
		<category><![CDATA[sbt]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1752</guid>
		<description><![CDATA[Find out how to move multi-module Maven projects into multi-project SBT projects, without sacrificing the plugins you were happily using in Maven. <a href="http://www.cakesolutions.net/teamblogs/2012/01/04/maven-to-sbt/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Typical [enterprise] Java projects use multi-module Maven configuration. You have the <em>parent</em> <code>pom.xml</code> file at the <em>root</em> of your project and you refer to the modules from the parent <code>pom.xml</code>. The motivation for this structure is that you want to configure the compiler, testing and perhaps the reporting components once and apply them to all modules; also, the modules depend on each other and you need to use the multi-module project to compile the modules in the right order.</p>
<p>Think about a typical JEE application: you have the <em>domain</em>, <em>repository</em>, <em>services</em> and <em>web app</em>; the dependencies between the modules are that:</p>
<ul>
<li><em>domain</em> does not have any dependencies</li>
<li><em>repository</em> depends on <em>domain</em></li>
<li><em>services</em> depends on <em>domain</em> and <em>repository</em></li>
<li><em>web app</em> depends on <em>domain</em> and <em>services</em></li>
</ul>
<p>In this post, I am not going to be talking about Spring Java EE application. I will show you how I have moved <a href="http://www.cakesolutions.org/specs2-spring.html" target="_blank">Specs2 Spring</a> from Maven to SBT. </p>
<p>Specs2 Spring was a multi-module Maven project, with five modules: </p>
<ul>
<li><em>org.specs2.spring</em> with no dependencies</li>
<li><em>org.specs2.spring-example</em> depends on <em>org.specs2.spring</em></li>
<li><em>org.specs2.spring.web</em> depends on <em>org.specs2.spring</em></li>
<li><em>org.specs2.spring.web-example</em> depends on <em>org.specs2.spring.web</em></li>
<li><em>org.specs2.spring.documentation</em> with no dependencies</li>
</ul>
<p>In addition to expressing the structure in the Maven poms, I needed to configure the Scala compiler to run during the <code>compile</code> and <code>testCompile</code> phases. Also, I wanted to generate DocBooks as part of the build process. All this made the parent <code>pom.xml</code> rather verbose, reaching 215 lines of XML; the most notable ones being:</p>
<pre class="brush:[xml]">
&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt;

  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;org.specs2&lt;/groupId&gt;
  &lt;artifactId&gt;parent&lt;/artifactId&gt;
  &lt;version&gt;0.3&lt;/version&gt;
  &lt;packaging&gt;pom&lt;/packaging&gt;

  &lt;properties&gt;
      ...
    &lt;specs2.version&gt;1.7&lt;/specs2.version&gt;

  &lt;/properties&gt;

  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.scala-lang&lt;/groupId&gt;
      &lt;artifactId&gt;scala-library&lt;/artifactId&gt;
      &lt;version&gt;2.9.1&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;

  &lt;modules&gt;
    &lt;module&gt;org.specs2.spring&lt;/module&gt;
    &lt;module&gt;org.specs2.spring.web&lt;/module&gt;
    &lt;module&gt;org.specs2.spring.documentation&lt;/module&gt;

    &lt;module&gt;org.specs2.spring-example&lt;/module&gt;
    &lt;module&gt;org.specs2.spring.web-example&lt;/module&gt;
  &lt;/modules&gt;

  &lt;build&gt;
    &lt;pluginManagement&gt;
      &lt;plugins&gt;
        &lt;plugin&gt;
          &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
          &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
          &lt;version&gt;2.0.2&lt;/version&gt;
        &lt;/plugin&gt;
        &lt;plugin&gt;
          &lt;groupId&gt;org.scala-tools&lt;/groupId&gt;
          &lt;artifactId&gt;maven-scala-plugin&lt;/artifactId&gt;
          &lt;version&gt;2.15.3-SNAPSHOT&lt;/version&gt;
        &lt;/plugin&gt;
      &lt;/plugins&gt;
    &lt;/pluginManagement&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.7.2&lt;/version&gt;
        &lt;configuration&gt;
          &lt;classesDirectory&gt;target/classes&lt;/classesDirectory&gt;
          &lt;includes&gt;
            &lt;include&gt;**/*Test.class&lt;/include&gt;
          &lt;/includes&gt;
          &lt;argLine&gt;-Xmx1024M -XX:MaxPermSize=256m&lt;/argLine&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
        &lt;configuration&gt;
          &lt;source&gt;1.6&lt;/source&gt;
          &lt;target&gt;1.6&lt;/target&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.1&lt;/version&gt;
        &lt;configuration&gt;
          &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.scala-tools&lt;/groupId&gt;
        &lt;artifactId&gt;maven-scala-plugin&lt;/artifactId&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;/plugin&gt;

      &lt;plugin&gt;
        &lt;groupId&gt;com.agilejava.docbkx&lt;/groupId&gt;
        &lt;artifactId&gt;docbkx-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;2.0.13&lt;/version&gt;
        &lt;configuration&gt;
          &lt;xincludeSupported&gt;true&lt;/xincludeSupported&gt;
          &lt;highlightSource&gt;1&lt;/highlightSource&gt;
          &lt;foCustomization&gt;
            ${project.basedir}/src/docbkx/styles/pdf/custom.xsl
          &lt;/foCustomization&gt;
        &lt;/configuration&gt;
        &lt;dependencies&gt;
          &lt;dependency&gt;
            &lt;groupId&gt;org.docbook&lt;/groupId&gt;
            &lt;artifactId&gt;docbook-xml&lt;/artifactId&gt;
            &lt;version&gt;4.4&lt;/version&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
            &lt;groupId&gt;net.sf.xslthl&lt;/groupId&gt;
            &lt;artifactId&gt;xslthl&lt;/artifactId&gt;
            &lt;version&gt;2.0.1&lt;/version&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
            &lt;groupId&gt;net.sf.offo&lt;/groupId&gt;
            &lt;artifactId&gt;fop-hyph&lt;/artifactId&gt;
            &lt;version&gt;1.2&lt;/version&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
          &lt;/dependency&gt;
        &lt;/dependencies&gt;

        &lt;executions&gt;
          &lt;execution&gt;
            &lt;phase&gt;pre-site&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;generate-html&lt;/goal&gt;
              &lt;goal&gt;generate-pdf&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;

&lt;/project&gt;
</pre>
<p>This parent <code>pom.xml</code> refers to <em>modules</em>, which must be sub-directories with another <code>pom.xml</code> file in them. The <code>org.specs2.spring/pom.xml</code> with no dependencies amongst the project modules simply listed all other dependencies:</p>
<pre class="brush:[xml]">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt;

  &lt;parent&gt;
    &lt;groupId&gt;org.specs2&lt;/groupId&gt;
    &lt;artifactId&gt;parent&lt;/artifactId&gt;
    &lt;version&gt;0.3&lt;/version&gt;
  &lt;/parent&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;org.specs2&lt;/groupId&gt;
  &lt;artifactId&gt;spring&lt;/artifactId&gt;
  &lt;packaging&gt;jar&lt;/packaging&gt;
  &lt;version&gt;0.3&lt;/version&gt;

  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    ...
  &lt;/dependencies&gt;

&lt;/project&gt;
</pre>
<p>The <em>org.specs2.spring-example</em> module depends on the <em>org.specs2.spring</em> module, so its <code>pom.xml</code> had to include the <em>org.specs2.spring-example</em> module like so:</p>
<pre class="brush:[xml]">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt;

  &lt;parent&gt;
    &lt;groupId&gt;org.specs2&lt;/groupId&gt;
    &lt;artifactId&gt;parent&lt;/artifactId&gt;
    &lt;version&gt;0.3&lt;/version&gt;
  &lt;/parent&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
  &lt;groupId&gt;org.specs2&lt;/groupId&gt;
  &lt;artifactId&gt;spring-example&lt;/artifactId&gt;
  &lt;packaging&gt;jar&lt;/packaging&gt;
  &lt;version&gt;0.3&lt;/version&gt;

  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.specs2&lt;/groupId&gt;
      &lt;artifactId&gt;spring&lt;/artifactId&gt;
      &lt;version&gt;0.3&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
      &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;
    ...
  &lt;/dependencies&gt;

&lt;/project&gt;
</pre>
<h2>Oh, the humanity!</h2>
<p>Quite. All this XML became a bit too uncomfortable to navigate around. Furthermore, most of the Scala projects out there use <a href="https://github.com/harrah/xsbt/wiki" target="_blank">SBT</a>, which promises to be as powerful, but much more concise build tool. So, I set out to replace Maven&#8217;s verbose XML with SBT&#8217;s&#8230; call it scripts.</p>
<h3>SBT Scripts?</h3>
<p>SBT is essentially a domain-specific language for building projects. SBT (the tool) then runs the Scala program that is assembled from the various script files as well as full-blown Scala sources. To make life easier, SBT maintains two sets of files: the <code>.sbt</code> files are decorated into the full Scala syntax and then compiled together with the grown-up Scala code. &lt;ins&gt;SBT decorates the body of the <code>.sbt</code> file to become a compilation unit (put simply, a class with all imports and functions resolved). Every block in the <code>.sbt</code> file then becomes a function in the resulting compilation unit. SBT uses empty lines to demarcate what is to become the functions, which is why every &#8220;statement&#8221; in the <code>.sbt</code> file needs to be on its own line and why you cannot have empty lines in multi-line &#8220;statements&#8221;. (Many thanks to @plalloni for clarification and comments!)&lt;/ins&gt; SBT then executes the resulting Scala program to build your project. There is much more detail at SBT&#8217;s documentation at <a href="https://github.com/harrah/xsbt/wiki" target="_blank">https://github.com/harrah/xsbt/wiki</a>. Let&#8217;s take a look at how I&#8217;ve transformed the multi-module Maven beast into SBT.</p>
<h2>Multi-module SBT</h2>
<p>First, let&#8217;s take a look at a typical SBT project. It contains the <code>build.sbt</code> file (that gets rewritten into the grown-up Scala program that then compiles your code, but you already knew that!).  A SBT project also needs the source files, which are in the usual Maven structure. So, a single SBT project typically looks like this:</p>
<pre>
src
  main
    java
    scala
    resources
  test
    java
    scala
    resources
build.sbt
</pre>
<p>SBT is smart enough to work out that the files in the <code>java</code> directory are to be compiled using the Java compiler; that the files in the <code>scala</code> directory need to be compiled using the Scala compiler and that the files in <code>resources</code> are not to be compiled, simply copied to the output.</p>
<p>Now, in Specs2 Spring, I have five projects, so the first approach was to include the <code>build.sbt</code> in every sub-project:</p>
<pre>
org.specs2.spring
  src
    ...
  build.sbt
org.specs2.spring-example
  src
    ...
  build.sbt
org.specs2.spring.web
  src
    ...
  build.sbt
org.specs2.spring.web-example
  src
    ...
  build.sbt
org.specs2.spring.documentation
  src
    ...
  build.sbt

build.sbt
</pre>
<p>The structure is clear[-ish]: we have five modules, each module&#8217;s <code>build.sbt</code> describes how it is to be built; and there is a main <code>build.sbt</code>, which should build all modules in the right sequence.</p>
<p>The situation is slightly more complicated. There is no provision for project dependencies in the simplified syntax of the <code>.sbt</code> files. (Recall that they are transformed into Scala by SBT.)<br />
In order to have multi-module SBT projects, we need to define a Scala source that represents the project build. We do so by creating the <code>project</code> directory at the same level as the modules and adding the <code>Build.scala</code> file, which contains object that extends <code>sbt.Build</code>. So, we have:</p>
<pre>
org.specs2.spring
  build.sbt
org.specs2.spring-example
  build.sbt
org.specs2.spring.web
  build.sbt
org.specs2.spring.web-example
  build.sbt
org.specs2.spring.documentation
  build.sbt

project
  Build.scala

build.sbt
</pre>
</p>
<p>The interesting file is the <code>Build.scala</code>, which defines the &#8220;modules&#8221; that make up the project and that sets the dependencies between the modules. It is surprisingly simple:</p>
<pre class="brush:[scala]">
import sbt._

object Specs2Spring extends Build {

  lazy val root =
    Project("specs2-spring", file("."))
            aggregate(core, coreExample, documentation, web, webExample)
  lazy val core =
    Project("org.specs2.spring", file("org.specs2.spring"))
  lazy val coreExample =
    Project("org.specs2.spring-example",
            file("org.specs2.spring-example")) dependsOn(core)

  lazy val web =
    Project("org.specs2.spring.web",
            file("org.specs2.spring.web")) dependsOn(core)
  lazy val webExample =
    Project("org.specs2.spring.web-example",
            file("org.specs2.spring.web-example")) dependsOn(web)

  lazy val documentation =
    Project("org.specs2.spring.documentation",
            file("org.specs2.spring.documentation"))
}
</pre>
<p>Notice that the object <code>Specs2Spring</code> extends <code>sbt.Build</code> and defines the variables that represent the projects. We have the <code>root</code> project, which is simply an <code>aggregate</code> of the remaining projects, which are each defined in their own variable. Projects can define dependencies using the <code>dependsOn</code> function, specifying the project variable of the dependency. How simple!</p>
<p>Now that we have the <code>Specs2Spring</code> project build source out of the way, let&#8217;s take a look at the smaller <code>build.sbt</code> files that complete the picture. By far the most complex is the <code>org.specs2.spring/build.sbt</code>:</p>
<pre class="brush:[scala]">
/** Project */
name := "specs2-spring"

version := "0.3"

organization := "org.specs2"

scalaVersion := "2.9.1"

crossScalaVersions := Seq("2.9.0")

/** Dependencies */
resolvers ++= Seq("snapshots-repo" at "http://scala-tools.org/repo-snapshots")

libraryDependencies &lt;&lt;= scalaVersion { scala_version =&gt; Seq(
  "org.specs2" %% "specs2" % "1.7.1",
  "junit" % "junit" % "4.7" % "optional",
  "org.springframework" % "spring-core" % "3.1.0.RELEASE",
  "org.springframework" % "spring-beans" % "3.1.0.RELEASE",
  "org.springframework" % "spring-jdbc" % "3.1.0.RELEASE",
  "org.springframework" % "spring-tx" % "3.1.0.RELEASE",
  "org.springframework" % "spring-orm" % "3.1.0.RELEASE",
  "org.springframework" % "spring-test" % "3.1.0.RELEASE",
  "org.hibernate" % "hibernate-core" % "3.6.0.CR1",
  "javax.mail" % "mail" % "1.4.1",
  "javax.transaction" % "jta" % "1.1",
  "com.atomikos" % "transactions-jta" % "3.7.0",
  "com.atomikos" % "transactions-jdbc" % "3.7.0",
  "org.apache.activemq" % "activemq-core" % "5.4.1"
  )
}

/** Compilation */
javacOptions ++= Seq()

javaOptions += "-Xmx2G"

scalacOptions ++= Seq("-deprecation", "-unchecked")

maxErrors := 20 

pollInterval := 1000

logBuffered := false

cancelable := true

testOptions := Seq(Tests.Filter(s =&gt;
  Seq("Spec", "Suite", "Unit", "all").exists(s.endsWith(_)) &#038;&#038;
    !s.endsWith("FeaturesSpec") ||
    s.contains("UserGuide") ||
    s.contains("index") ||
    s.matches("org.specs2.guide.*")))
</pre>
<p>In the <code>build.sbt</code> file, you can see that I specify some common settings (name, version, Scala version); the managed libraries (dependencies in Maven speak) and I configure the parameters of the compiler. But that&#8217;s all I need to do!</p>
<p>The remaining <code>build.sbt</code> files can be much simpler, because SBT compiles the <code>project/Build.scala</code> and all transformed <code>build.sbt</code> files into a single program that then builds your project. Let&#8217;s pick the <code>org.specs2.spring-example/build.sbt</code> as an example:</p>
<pre class="brush:[scala]">
libraryDependencies &lt;&lt;= scalaVersion { scala_version =&gt; Seq(
  "org.springframework" % "spring-core" % "3.1.0.RELEASE",
  "org.springframework" % "spring-beans" % "3.1.0.RELEASE",
  "org.springframework" % "spring-jdbc" % "3.1.0.RELEASE",
  "org.springframework" % "spring-tx" % "3.1.0.RELEASE",
  "org.springframework" % "spring-orm" % "3.1.0.RELEASE",
  "org.hibernate" % "hibernate-core" % "3.6.0.CR1",
  "org.hibernate" % "hibernate-validator" % "4.0.2.GA",
  "javassist" % "javassist" % "3.4.GA",
  "org.hsqldb" % "hsqldb" % "2.2.4"
  )
}
</pre>
<p><em>That is all!</em>; you can now run <code>sbt compile</code>, <code>sbt test</code>, <code>sbt publish-local</code> and many others. <code>sbt</code> is a shell script; one example is at <a href="https://github.com/harrah/xsbt/wiki/Getting-Started-Setup" target="_blank">https://github.com/harrah/xsbt/wiki/Getting-Started-Setup</a>, but Paul Phillips created far more powerful version, which you can download at <a href="https://github.com/paulp/sbt-extras" target="_blank">https://github.com/paulp/sbt-extras</a>.</p>
<h3>The devil in the detail</h3>
<p>Now, we have a successful multi-module project in SBT. Everything builds, all libraries are downloaded and the dependencies between the projects work as well. But what about DocBook? In Maven, I used to use the <code>com.agilejava.docbkx:docbkx-maven-plugin</code> plugin, which took care of generating the HTMLs and PDFs.</p>
<p>Luckily, SBT supports similar plugin infrastructure. All we need to do is to include the appropriate plugins in our project and we can run tasks that the plugins expose. To do what I just described, we need to create the <code>project/plugins.sbt</code> file that lists the required plugins <em>in the project that requires the plugin</em>. So, taking our <code>org.specs2.spring.documentation</code> module (or sub-project, if you like), we need to create the following structure:</p>
<pre>
org.specs2.spring
...
org.specs2.spring.documentation
  project
    plugins.sbt
  src
    main
      docbook
        ...
  build.sbt
...
project
  Build.scala
build.sbt
</pre>
<p>The interesting file is the <code>plugins.sbt</code>, which defines the plugins our project requires. The <code>org.specs2.spring.documentation/project/plugins.sbt</code> contains just a single line:</p>
<pre class="brush:[scala]">
addSbtPlugin("de.undercouch" % "sbt-docbook-plugin" % "0.2-SNAPSHOT")
</pre>
<p>The <code>"de.undercouch" % "sbt-docbook-plugin" % "0.2-SNAPSHOT"</code> plugin requires some properties to be set in the <code>build.sbt</code>, namely the <code>sourceFilter</code> and, because we have our own XSL for the PDF, the <code>docBookXslFoStyleSheet</code>. So, in the <code>org.specs2.spring.documentation/build.sbt</code>, we have:</p>
<pre class="brush:[scala]">
sourceFilter := "**/*.xml"

docBookXslFoStyleSheet in DocBook:= "src/docbkx/styles/pdf/custom.xsl"
</pre>
<p>I updated the plugin to the latest version of Scala and SBT and sent a pull request to the original author; my sources are at <a href="https://github.com/janm399/sbt-docbook-plugin" target="_blank">https://github.com/janm399/sbt-docbook-plugin</a> (for the future of the plugin, see the open issues).</p>
<h2>Summary</h2>
<p>So, what can you achieve? Put simply, the same build functionality in approximately quarter lines of code. Even if you do not use any of the advanced features of SBT, you have gained a more intuitive way of building Java and Scala applications; you can also release your libraries for the correct version of the Scala compiler (no more appending <code>_2.9.1</code>, <code>_2.9.0_1</code> and similar to your Maven dependencies!). The artefacts that SBT produces fit directly into the Scala repositories without additional effort.</p>
<p>With this structure, the project will build just like the Maven monster it replaced! As usual, the devil was in the details, so keep reading.</p>
<p>P.S. All SBT goodness is at the <del datetime="2012-01-04T20:29:07+00:00">SBT</del> master branch of <a href="https://github.com/janm399/specs2-spring" target="_blank">https://github.com/janm399/specs2-spring</a> <del datetime="2012-01-04T20:29:07+00:00">I will make some final modifications (namely get rid of the now superfluous root <code>project</code> directory) in preparation for the 0.4 release.</del> (With all the changes applied.)</p>
<p>P.P.S. All signs point to Specs2 Spring being available on the <a href="http://www.scala-tools.org" target="_blank">scala-tools.org</a> repo in the next few days!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2012/01/04/maven-to-sbt/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Spring I/O</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/12/30/spring-io/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=spring-io</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/12/30/spring-io/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 18:31:30 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[#SpringIO]]></category>
		<category><![CDATA[conferences]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1749</guid>
		<description><![CDATA[I&#8217;ll be speaking at Spring IO in Madrid in 17th to 18th February 2012. My talk will be Spring in Scala, showing how to make the most of Scala in your Spring applications. If you can, escape the winter blues, &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/12/30/spring-io/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/speaker_badge_springio_2012.png" alt="" title="speaker_badge_springio_2012" width="160" height="190" /></p>
<p>I&#8217;ll be speaking at <a href="http://www.springio.net">Spring IO</a> in Madrid in 17th to 18th February 2012. My talk will be <em>Spring in Scala</em>, showing how to make the most of Scala in your Spring applications.</p>
<p>If you can, escape the winter blues, come to Madrid and hopefully to my talk.</p>
<h2>Synopsis</h2>
<p>In his Spring in Scala talk, Jan will start by comparing Scala to the other languages on the Java platform. Find out that Scala code gets compiled to regular Java bytecode, making it accessible to your Spring code. You will also learn what functional programming means and how to see &#038; apply the patterns of functional programming in what we would call enterprise code.<br />
Throughout the talk, there will be plenty of code examples comparing the Spring bean in Java with their new form in Scala; together with plentiful references to the ever-growing Scala ecosystem, the talk will give you inspiration &#038; guidance on using Scala in your Spring applications.<br />
Come over and find your functional mojo!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/12/30/spring-io/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Specs2 Spring 0.3</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/12/29/specs2-spring-0-3/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=specs2-spring-0-3</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/12/29/specs2-spring-0-3/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 11:15:51 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Specs2 Spring]]></category>
		<category><![CDATA[Spring 3.1]]></category>
		<category><![CDATA[Spring 3.1 testing]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1738</guid>
		<description><![CDATA[Spring 3.1 brings bean profiles, allowing you to name sets of beans that will be included in your ApplicationContext according to your specifications. For example, I could have bean profiles named UCI and ACU. In both profiles, I will have &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/12/29/specs2-spring-0-3/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Spring 3.1 brings bean profiles, allowing you to name sets of beans that will be included in your <code>ApplicationContext</code> according to your specifications. For example, I could have bean profiles named <code>UCI</code> and <code>ACU</code>. In both profiles, I will have a bean that implements the <code>LegalRegulations</code> interface, but the implementations will be different. At runtime, I will specify which bean profiles I want to use and Spring will pick the appropriate beans for the given profile. Let me show you some code:</p>
<pre class="brush:[java]">
public interface LegalRegulations {
  boolean hasDoped(Rider rider);
}

@Component
@Profile("UCI")
public class UCILegalRegulations implements LegalRegulations {
  @Override
  public boolean hasDoped(Rider rider) {
    return true;
  }
}

@Component
@Profile("ACU")
public class ACULegalRegulations implements LegalRegulations {

  @Override
  public boolean hasDoped(Rider rider) {
    return false;
  }
}
</pre>
<p>Now, I have two beans that implement the same interface. Depending on which country we run the application in, we want to use the appropriate implementation of the <code>LegalRegulations</code> interface. Notice in the code above the <code>@Profile</code> annotation with a constant that specifies the name of the profile in which the bean should be included.</p>
<p>In addition to the <em>profiled</em> beans, I have other beans that are included in every profile. The last bean that I will show you is the <code>SomeComponent</code> bean (which just so happens to be implemented in Scala).</p>
<pre class="brush:[scala]">
@Component
class SomeComponent
  @Autowired()(private val hibernateTemplate: HibernateTemplate) {

  def findAll(entityType: Class[_]) =
    this.hibernateTemplate.loadAll(entityType)

  def generate(count: Int) {
    for (c &lt;- 0 until count) {
      val rider = new Rider()
      rider.setName("Rider #" + c)
      rider.setUsername("user " + c)
      this.hibernateTemplate.saveOrUpdate(rider)
    }
  }

  def getByUsername(username: String) = {
    val riders = this.hibernateTemplate.findByCriteria(
      DetachedCriteria.forClass(classOf[Rider]).add(
        Restrictions.eq("username", username)))
    riders.get(0).asInstanceOf[Rider]
  }

}
</pre>
<p>This bean depends on the <code>HibernateTemplate</code>, which in turn depends on <code>SessionFactory</code>; the <code>SessionFactory</code> depends on a <code>DataSource</code>, which is looked up in JNDI. The Spring context file for the application is simply</p>
<pre class="brush:[xml]">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans" ... &gt;

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

  &lt;tx:jta-transaction-manager /&gt;

  &lt;tx:annotation-driven /&gt;

  &lt;jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/test"
    expected-type="javax.sql.DataSource"/&gt;

  &lt;bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;
    &lt;property name="packagesToScan"&gt;
      &lt;list&gt;
        &lt;value&gt;org.specs2.springexample&lt;/value&gt;
      &lt;/list&gt;
    &lt;/property&gt;
    &lt;property name="hibernateProperties"&gt;
      &lt;value&gt;
        hibernate.show_sql=true
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
        hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
        hibernate.cache.use_structured_entries=true
        hibernate.hbm2ddl.auto=create-drop
      &lt;/value&gt;
    &lt;/property&gt;
  &lt;/bean&gt;

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

&lt;/beans&gt;
</pre>
<h2>Testing it</h2>
<p>Now, to test the application, I need to prepare the JNDI environment and specify the profile that I want to use for testing. Nothing is easier in Specs2 Spring. All I need to do is to create the class that contains the specifications; that extends <code>org.specs2.spring.Specification</code> and is annotated with the Specs2 Spring annotations. (There is much more detail at <a href="http://www.cakesolutions.org/specs2-spring.html" target="_blank">http://www.cakesolutions.org/specs2-spring.html</a>.) In this post, I will show just the code that is necessary to test the trivial <em>rider manager</em> application.</p>
<pre class="brush:[scala]">
@Transactional
@TransactionConfiguration (defaultRollback = true)
@ContextConfiguration(
  Array("classpath*:/META-INF/spring/module-context.xml"))
@UseProfile(Array("ACU"))
@SystemEnvironment(Array("efoo=bar;ebaz=null"))
@SystemProperties(Array("pfoo=bar;pbaz=null"))
@DataSource(name = "java:comp/env/jdbc/test",
  driverClass = classOf[JDBCDriver], url = "jdbc:hsqldb:mem:test")
@TransactionManager(name = "java:comp/TransactionManager")
class ApplicationSpec extends Specification
  with HibernateDataAccess with BeanTables {

  @Autowired var regulations: LegalRegulations = _
  @Autowired var someComponent: SomeComponent = _

  "no-one dopes!" in {
    "age" | "username" | "name"    | "teamName" |
       32 ! "wheeler"  ! "Wheeler" ! "Wheelers" |
       30 ! "nemesis"  ! "Nemesis" ! "Baddies"  |> insert[Rider]

    val rider = this.someComponent.getByUsername("wheeler")
    regulations.hasDoped(rider) must be_== (false)
  }

}
</pre>
<p>Specs2 Spring understands all the annotations and prepares the JNDI environment (the <code>DataSource</code> and the <code>TransactionManager</code>), then creates the Spring <code>ApplicationContext</code> using the configuration files specified in <code>@ContextConfiguration</code> annotation with the <code>ACU</code> profile (see the <code>@UseProfile(Array("ACU"))</code> annotation). It also specifies the system environment and system properties to be <code>efoo =&gt; "bar"</code> and <code>ebaz =&gt; null</code> and <code>pfoo =&gt; "bar"</code> and <code>pbaz =&gt; null</code>. Presumably, some beans use the <code>@Value</code> annotation with the SPEL expression that extracts the value from the environment.</p>
<h2>Getting it</h2>
<p>If you want to get your hands on Specs2 Spring 0.3, go to <a href="https://github.com/janm399/specs2-spring" target="_blank">https://github.com/janm399/specs2-spring</a>. If you find a bug or if you&#8217;d like a feature to be included, please do create an issue at <a href="https://github.com/janm399/specs2-spring/issues" target="_blank">https://github.com/janm399/specs2-spring/issues</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/12/29/specs2-spring-0-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Merry Christmas</title>
		<link>http://www.cakesolutions.net/teamblogs/2011/12/22/merry-christmas/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=merry-christmas</link>
		<comments>http://www.cakesolutions.net/teamblogs/2011/12/22/merry-christmas/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 09:18:32 +0000</pubDate>
		<dc:creator>Jan Machacek</dc:creator>
				<category><![CDATA[Jan's Blog]]></category>
		<category><![CDATA[Merry Christmas]]></category>

		<guid isPermaLink="false">http://www.cakesolutions.net/teamblogs/?p=1716</guid>
		<description><![CDATA[import annotation.tailrec abstract class Tree(val left: Tree) { def o = new Ball(this) def x = new Spike(this) def * = new Candle(this) def oxo = new BigBall(this) def oo = new DoubleBall(this) def *** = new ElectricCandle(this) def / &#8230; <a href="http://www.cakesolutions.net/teamblogs/2011/12/22/merry-christmas/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.cakesolutions.net/teamblogs/wp-content/uploads/2011/12/merrychristmas.png" alt="" title="merrychristmas" width="293" height="236" /></p>
<pre class="brush:[scala]">

import annotation.tailrec

abstract class Tree(val left: Tree) {
  def o = new Ball(this)
  def x = new Spike(this)
  def * = new Candle(this)
  def oxo = new BigBall(this)
  def oo = new DoubleBall(this)
  def *** = new ElectricCandle(this)

  def / = new LeftNeedle(this)
  def \ = new RightNeedle(this)
  def | = new Trunk(this)

}
class Top(star: Star) extends Tree(star)
abstract class Needle(left: Tree) extends Tree(left)
class LeftNeedle(left: Tree) extends Needle(left)
class RightNeedle(left: Tree) extends Needle(left) {

  def |||() {
    |||(true)
  }

  @tailrec
  final def |||(sparkle: Boolean) {
    val f = (t: Tree) =&gt;
      t match {
        case _: LeftNeedle =&gt; "/"
        case _: RightNeedle =&gt; "\\"
        case _: Trunk =&gt; "|"
        case _: Ball =&gt; "o"
        case _: Spike =&gt; "x"
        case _: Candle =&gt; "*"
        case _: BigBall =&gt; "oxo"
        case _: DoubleBall =&gt; "oo"
        case _: ElectricCandle =&gt; "***"
      }

    def walk(t: Tree, depth: Int): List[String] = {
      def walkLevel(t: Tree, acc: String,
                    f: (Tree) =&gt; String): (Tree, String) = {
        val fx = (t: Tree) =&gt; if (sparkle) f(t).toUpperCase else f(t)
        t match {
          case l: LeftNeedle =&gt; (l.left, fx(l) + "." + acc)
          case t: Tree =&gt; walkLevel(t.left, fx(t) + "." + acc, f)
        }
      }

      t match {
        case r: RightNeedle =&gt;
          val l = walkLevel(r, "", f)
          l._2 +: walk(l._1, depth + 1)
        case s: Star =&gt;
          List("--&gt;*&lt;-- ", "\\-/.")
      }
    }

    val tree = "||| " +: walk(this, 0)

    tree.reverse.foreach({l =&gt;
      val numSpaces = 30 - (l.length() / 2)
      val padding = " " * numSpaces
      print(padding)
      println(l)
    })

    Thread.sleep(500)

    |||(!sparkle)
  }

}
class Trunk(parent: Tree) extends Tree(parent)

abstract class Decoration(left: Tree) extends Tree(left)
class Star extends Decoration(null)
class Candle(left: Tree) extends Decoration(left)
class Ball(left: Tree) extends Decoration(left)
class Spike(left: Tree) extends Decoration(left)
class BigBall(left: Tree) extends Decoration(left)
class DoubleBall(left: Tree) extends Decoration(left)
class ElectricCandle(left: Tree) extends Decoration(left)

trait DecorationBuilder {
 def \-/ = new PartialDecoration
}
class PartialDecoration {
 def --&gt;*&lt;-- = new Star
}

object ChristmasTree extends DecorationBuilder {

  def main(args: Array[String]) {
           \-/.
         --&gt;*&lt;--
            .
           /.\
         ./.|.\.
         /.oxo.\
       ./.*.|.x.\.
       /.oo.|.oo.\
     ./.oxo.|.***.\.
     /.*.oo.|.*.oo.\.
           |||
  }

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cakesolutions.net/teamblogs/2011/12/22/merry-christmas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

