This week in #Scala (20/01/2012)

Welcome to this week in #Scala. It’s been another busy week so lets get started!

 

New Stuff

JUnit interface 0.8 for sbt has been released. This is an implementation of sbt’s test interface for JUnit 4 which allows you to run JUnit tests from sbt. Changes for version 0.8 include ANSI colors for the log messages and updated documentation.

Google-analytics 2.4-0.9 built for Lift 2.4 and Scala 2.8.1 to 2.9.1.

imap-idle 2.4-0.92, this provides push-like email to your Lift web application via the IMAP IDLE feature.

SBT native packager 0.1.0 is out now. This plugin supports the generation of native packages for many platforms, including support for RPM, DEB & MSI (via WIX).

coffeescripted-sbt 0.2.1 is now available. This Sbt plugin compiles CoffeeScript Sources into JavaScript.

less-sbt 0.1.4 goes hand in hand with coffeescripted-sbt and enables you to type less css in your sbt projects.

sff4s 0.1.1 (simple future facade for Scala) is a Scala wrapper around several future implementations.

xsbt-gpg-plugin 0.5 aims to provide PGP signing for XSBT (SBT 0.11+ versions).

Scala 2.10.0 Milestone 1 is out! This release includes many changes and fixes, the most notable being:

  • Preliminary Reflection API
  • faster inliner
  • scaladoc improvements (Thanks docspree folks!)
  • virtualized pattern matcher

Click the link for more information.

 

Blogs and tutorials

 

As usual feel free to drop me a mail or message @markglh on twitter with any Scala news!

Posted in Mark's Blog | Tagged , , , , , , | Leave a comment

This week in #Scala (13/01/2012)

Welcome to another week in @Scala. It’s been a busy week so lets get started:

 

New Stuff

Equinox Weaving Launcher is now available. This is an Eclipse component which adds a new launch configuration type allowing Eclipse Applications and JUnit plug-in tests to be launched with Equinox Weaving enabled. It was developed to simplify the development workflow for the Scala IDE for Eclipse, and it can be used to support development of other Eclipse applications which use Equinox Weaving.

AKKA 1.3-RC6 is the latest release candidate for the upcoming AKKA 1.3. Check the link for further details.

sbt-git-plugin 0.4 - a SBT plugin that enabled cross-platform GIT support.

groll 1.1.1  and 1.1.0 were released this week. Groll is a plugin for sbt to view and navigate through the Git history.

Scalding is now open source. Scalding is a Scala API for Cascading – a thin Java library and API that sits on top of Apache Hadoop’s MapReduce layer.

Lift 2.4 Final is out now! This version of the web framework adds plenty of new features and improvements:

  • Lots of enhancements to JSON support
  • Record improvments
  • Squeryl/Record support for Crudify
  • Singificant enhancement to MongoDB support (including better support for reference records and binary fields)
  • Support for BsonDSL (BSON types to JsonDSL)
  • Significant enhancements to Mailer functionality
  • Significant enhancements to the CSS Selector transformers
  • Enhancements to Snippet resolution like sub-packages based resolution, Loc-based snippet resolution of Screen and Wizard, etc.
  • Significant improvement to REST support including stateless Async/Continuations on Jetty 7, Jetty 8 and Tomcat/Glassfish
  • Ability to get html5 compliant templates using data-lift attribute
  • Numerous localization modules

For more information follow the link .

 

Blogs and tutorials

 

As usual feel free to drop me a mail or message @markglh on twitter with any Scala news!

Posted in Mark's Blog | Tagged , , , , , | 6 Comments

This week in #Scala (06/01/2012)

Happy new year and welcome to another this week in #Scala!

 

New Stuff

Lift 2.4-RC1 is now out with plenty of bug fixes since the previous release. 2.4 final should be heading our way very soon!

Specs2 version 1.7.1 by Eric Torreborre (@etorreborre) is out! This release includes various bug fixes and new features, including the ability to enforce dependencies between packages.

Groll 1.0.0 has been released. Groll is a sbt plugin to view and navigate the Git history.

Setak has been updated, adding support for testing #Akka non-stable systems.

Akka 2.0 pre-release Milestone 2 is now available. This new release includes another 70 closed tickets, better documentation and much more, click through for more details.

Scala IO 0.3.0 has been released, with plenty of improvements and fixes – follow the link for more information.

Shapeless 1.0.1 has been released. This is just a minor update but still includes several useful fixes and improvements. Shapeless also has a development mailing list which can be found here.

 

Blogs and tutorials

 

As usual feel free to drop me a mail or message @markglh on twitter with any Scala news!

Posted in Mark's Blog | Tagged , , , , , , , , | 2 Comments

Configuring Jenkins plugin for SBT

As a logical next step of moving Specs2 Spring from Maven to SBT, I have now got Specs2 Spring building comfortably in our local Jenkins using the SBT goodness. The process was pretty straight forward!

First, I installed the sbt-plugin for Jenkins from the list of available plugins under Manage Plugin.

Manage plugin

Once the plugin installation completes and Jenkins is restarted, I verified that sbt-plugin is now available as one of the installed Jenkins plugins.

sbt-plging installed

Now that sbt-plugin is available on Jenkins, I had to configure a sbt launcher jar. I downloaded the very latest sbt launcher jar [0.11.2] from here, and saved it on our Jenkins build server. In order to complete the configuration, I had to specify the name and location of the sbt launcher jar under Jenkins configuration.

configure sbt plugin

Jenkins sbt plugin allows you to install multiple versions of sbt launcher jar files giving you the option of choosing the most appropriate one for your project.

All that remained now was to create a Jenkins build job which used sbt-launcher to build Spec2Spring. To do that I simply selected Build using sbt from Add build step.

add job step 1

Finally, I selected my preferred sbt launcher and specified the actions I wanted to run. And that was all I had to do!

add job step 2

-Dsbt.log.noformat=true sbt flag keeps the console output clean and tidy!

Note: To avoid frequent OutOfMemory errors, add something like the following JVM flags to your Jenkins build configuration (notice in particular the stack and perm gen size parameters):

-XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx512M -Xss16M

Posted in Ani's Blog | Tagged , , , , , | 1 Comment

Maven to SBT

Typical [enterprise] Java projects use multi-module Maven configuration. You have the parent pom.xml file at the root of your project and you refer to the modules from the parent pom.xml. 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.

Think about a typical JEE application: you have the domain, repository, services and web app; the dependencies between the modules are that:

  • domain does not have any dependencies
  • repository depends on domain
  • services depends on domain and repository
  • web app depends on domain and services

In this post, I am not going to be talking about Spring Java EE application. I will show you how I have moved Specs2 Spring from Maven to SBT.

Specs2 Spring was a multi-module Maven project, with five modules:

  • org.specs2.spring with no dependencies
  • org.specs2.spring-example depends on org.specs2.spring
  • org.specs2.spring.web depends on org.specs2.spring
  • org.specs2.spring.web-example depends on org.specs2.spring.web
  • org.specs2.spring.documentation with no dependencies

In addition to expressing the structure in the Maven poms, I needed to configure the Scala compiler to run during the compile and testCompile phases. Also, I wanted to generate DocBooks as part of the build process. All this made the parent pom.xml rather verbose, reaching 215 lines of XML; the most notable ones being:

<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">

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.specs2</groupId>
  <artifactId>parent</artifactId>
  <version>0.3</version>
  <packaging>pom</packaging>

  <properties>
      ...
    <specs2.version>1.7</specs2.version>

  </properties>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>2.9.1</version>
    </dependency>
  </dependencies>

  <modules>
    <module>org.specs2.spring</module>
    <module>org.specs2.spring.web</module>
    <module>org.specs2.spring.documentation</module>

    <module>org.specs2.spring-example</module>
    <module>org.specs2.spring.web-example</module>
  </modules>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.0.2</version>
        </plugin>
        <plugin>
          <groupId>org.scala-tools</groupId>
          <artifactId>maven-scala-plugin</artifactId>
          <version>2.15.3-SNAPSHOT</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.7.2</version>
        <configuration>
          <classesDirectory>target/classes</classesDirectory>
          <includes>
            <include>**/*Test.class</include>
          </includes>
          <argLine>-Xmx1024M -XX:MaxPermSize=256m</argLine>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

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

        <executions>
          <execution>
            <phase>pre-site</phase>
            <goals>
              <goal>generate-html</goal>
              <goal>generate-pdf</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

This parent pom.xml refers to modules, which must be sub-directories with another pom.xml file in them. The org.specs2.spring/pom.xml with no dependencies amongst the project modules simply listed all other dependencies:

<?xml version="1.0" encoding="UTF-8"?>
<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">

  <parent>
    <groupId>org.specs2</groupId>
    <artifactId>parent</artifactId>
    <version>0.3</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.specs2</groupId>
  <artifactId>spring</artifactId>
  <packaging>jar</packaging>
  <version>0.3</version>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    ...
  </dependencies>

</project>

The org.specs2.spring-example module depends on the org.specs2.spring module, so its pom.xml had to include the org.specs2.spring-example module like so:

<?xml version="1.0" encoding="UTF-8"?>
<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">

  <parent>
    <groupId>org.specs2</groupId>
    <artifactId>parent</artifactId>
    <version>0.3</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.specs2</groupId>
  <artifactId>spring-example</artifactId>
  <packaging>jar</packaging>
  <version>0.3</version>

  <dependencies>
    <dependency>
      <groupId>org.specs2</groupId>
      <artifactId>spring</artifactId>
      <version>0.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    ...
  </dependencies>

</project>

Oh, the humanity!

Quite. All this XML became a bit too uncomfortable to navigate around. Furthermore, most of the Scala projects out there use SBT, which promises to be as powerful, but much more concise build tool. So, I set out to replace Maven’s verbose XML with SBT’s… call it scripts.

SBT Scripts?

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 .sbt files are decorated into the full Scala syntax and then compiled together with the grown-up Scala code. <ins>SBT decorates the body of the .sbt file to become a compilation unit (put simply, a class with all imports and functions resolved). Every block in the .sbt 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 “statement” in the .sbt file needs to be on its own line and why you cannot have empty lines in multi-line “statements”. (Many thanks to @plalloni for clarification and comments!)</ins> SBT then executes the resulting Scala program to build your project. There is much more detail at SBT’s documentation at https://github.com/harrah/xsbt/wiki. Let’s take a look at how I’ve transformed the multi-module Maven beast into SBT.

Multi-module SBT

First, let’s take a look at a typical SBT project. It contains the build.sbt 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:

src
  main
    java
    scala
    resources
  test
    java
    scala
    resources
build.sbt

SBT is smart enough to work out that the files in the java directory are to be compiled using the Java compiler; that the files in the scala directory need to be compiled using the Scala compiler and that the files in resources are not to be compiled, simply copied to the output.

Now, in Specs2 Spring, I have five projects, so the first approach was to include the build.sbt in every sub-project:

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

The structure is clear[-ish]: we have five modules, each module’s build.sbt describes how it is to be built; and there is a main build.sbt, which should build all modules in the right sequence.

The situation is slightly more complicated. There is no provision for project dependencies in the simplified syntax of the .sbt files. (Recall that they are transformed into Scala by SBT.)
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 project directory at the same level as the modules and adding the Build.scala file, which contains object that extends sbt.Build. So, we have:

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

The interesting file is the Build.scala, which defines the “modules” that make up the project and that sets the dependencies between the modules. It is surprisingly simple:

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"))
}

Notice that the object Specs2Spring extends sbt.Build and defines the variables that represent the projects. We have the root project, which is simply an aggregate of the remaining projects, which are each defined in their own variable. Projects can define dependencies using the dependsOn function, specifying the project variable of the dependency. How simple!

Now that we have the Specs2Spring project build source out of the way, let’s take a look at the smaller build.sbt files that complete the picture. By far the most complex is the org.specs2.spring/build.sbt:

/** 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 <<= scalaVersion { scala_version => 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 =>
  Seq("Spec", "Suite", "Unit", "all").exists(s.endsWith(_)) &&
    !s.endsWith("FeaturesSpec") ||
    s.contains("UserGuide") ||
    s.contains("index") ||
    s.matches("org.specs2.guide.*")))

In the build.sbt 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’s all I need to do!

The remaining build.sbt files can be much simpler, because SBT compiles the project/Build.scala and all transformed build.sbt files into a single program that then builds your project. Let’s pick the org.specs2.spring-example/build.sbt as an example:

libraryDependencies <<= scalaVersion { scala_version => 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"
  )
}

That is all!; you can now run sbt compile, sbt test, sbt publish-local and many others. sbt is a shell script; one example is at https://github.com/harrah/xsbt/wiki/Getting-Started-Setup, but Paul Phillips created far more powerful version, which you can download at https://github.com/paulp/sbt-extras.

The devil in the detail

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 com.agilejava.docbkx:docbkx-maven-plugin plugin, which took care of generating the HTMLs and PDFs.

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 project/plugins.sbt file that lists the required plugins in the project that requires the plugin. So, taking our org.specs2.spring.documentation module (or sub-project, if you like), we need to create the following structure:

org.specs2.spring
...
org.specs2.spring.documentation
  project
    plugins.sbt
  src
    main
      docbook
        ...
  build.sbt
...
project
  Build.scala
build.sbt

The interesting file is the plugins.sbt, which defines the plugins our project requires. The org.specs2.spring.documentation/project/plugins.sbt contains just a single line:

addSbtPlugin("de.undercouch" % "sbt-docbook-plugin" % "0.2-SNAPSHOT")

The "de.undercouch" % "sbt-docbook-plugin" % "0.2-SNAPSHOT" plugin requires some properties to be set in the build.sbt, namely the sourceFilter and, because we have our own XSL for the PDF, the docBookXslFoStyleSheet. So, in the org.specs2.spring.documentation/build.sbt, we have:

sourceFilter := "**/*.xml"

docBookXslFoStyleSheet in DocBook:= "src/docbkx/styles/pdf/custom.xsl"

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 https://github.com/janm399/sbt-docbook-plugin (for the future of the plugin, see the open issues).

Summary

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 _2.9.1, _2.9.0_1 and similar to your Maven dependencies!). The artefacts that SBT produces fit directly into the Scala repositories without additional effort.

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.S. All SBT goodness is at the SBT master branch of https://github.com/janm399/specs2-spring I will make some final modifications (namely get rid of the now superfluous root project directory) in preparation for the 0.4 release. (With all the changes applied.)

P.P.S. All signs point to Specs2 Spring being available on the scala-tools.org repo in the next few days!

Posted in Jan's Blog | Tagged , , , , | 8 Comments

Spring I/O

I’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, come to Madrid and hopefully to my talk.

Synopsis

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 & apply the patterns of functional programming in what we would call enterprise code.
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 & guidance on using Scala in your Spring applications.
Come over and find your functional mojo!

Posted in Jan's Blog | Tagged , | Leave a comment

Specs2 Spring 0.3

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 a bean that implements the LegalRegulations 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:

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;
  }
}

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 LegalRegulations interface. Notice in the code above the @Profile annotation with a constant that specifies the name of the profile in which the bean should be included.

In addition to the profiled beans, I have other beans that are included in every profile. The last bean that I will show you is the SomeComponent bean (which just so happens to be implemented in Scala).

@Component
class SomeComponent
  @Autowired()(private val hibernateTemplate: HibernateTemplate) {

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

  def generate(count: Int) {
    for (c <- 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]
  }

}

This bean depends on the HibernateTemplate, which in turn depends on SessionFactory; the SessionFactory depends on a DataSource, which is looked up in JNDI. The Spring context file for the application is simply

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" ... >

  <context:component-scan base-package="org.specs2.springexample"/>

  <tx:jta-transaction-manager />

  <tx:annotation-driven />

  <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/test"
    expected-type="javax.sql.DataSource"/>

  <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan">
      <list>
        <value>org.specs2.springexample</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        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
      </value>
    </property>
  </bean>

  <bean id="hibernateTemplate"
    class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"/>
  </bean>

</beans>

Testing it

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 org.specs2.spring.Specification and is annotated with the Specs2 Spring annotations. (There is much more detail at http://www.cakesolutions.org/specs2-spring.html.) In this post, I will show just the code that is necessary to test the trivial rider manager application.

@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)
  }

}

Specs2 Spring understands all the annotations and prepares the JNDI environment (the DataSource and the TransactionManager), then creates the Spring ApplicationContext using the configuration files specified in @ContextConfiguration annotation with the ACU profile (see the @UseProfile(Array("ACU")) annotation). It also specifies the system environment and system properties to be efoo => "bar" and ebaz => null and pfoo => "bar" and pbaz => null. Presumably, some beans use the @Value annotation with the SPEL expression that extracts the value from the environment.

Getting it

If you want to get your hands on Specs2 Spring 0.3, go to https://github.com/janm399/specs2-spring. If you find a bug or if you’d like a feature to be included, please do create an issue at https://github.com/janm399/specs2-spring/issues.

Posted in Jan's Blog | Tagged , , | Leave a comment

This week in #Scala (23/12/2011)

Welcome to another this week in #Scala, Christmas edition :) It looks like everyones been pretty busy this past week as there have been loads of blogs and releases, so lets get cracking:

 

New Stuff

Specs2 version 1.7 is out! Specs2 is a library for writing executable acceptance and unit software specifications. More information on version 1.7 can be found on implicit.ly

sbt-protobuf v0.2.2 has been released. sbt-protobuf is a plugin for sbt that transforms *.proto files into gazillion-loc java files

shapeless 1.0 by Miles Sabin (@milessabin). Shapeless is an exploration of generic (aka polytypic) programming in Scala and is well worth checking out! Miles has written a blog on the project here.

sbteclipse 2.0.0-M1. sbteclipse is an sbt plugin for creating Eclipse project definitions. Version 2.0.0 is a complete rewrite of the 1.x branch.

sbt-cloudbees-plugin 0.4.0. This plugin for SBT lets you deploy apps to the CloudBees RUN@Cloud PaaS. Version 4.0 has been a major rewrite to make use of the more idiomatic task functionaltiy within SBT 0.10+.

Scala Micro-Benchmarking Template, a scala wrapper for Google’s caliper by Daniel Capo Sobral (@dcsobral).

Scala IDE for Eclipse 2.0 Final Release available now! This huge update includes a new website, screencasts and documentation – along with countless improvements and new features.

 

Blogs and tutorials

 

This is the last blog from me until the new year, so I’ll wish everyone a happy Christmas and new year from me and everyone here at Cake Solutions!

As usual feel free to drop me a mail or message @markglh on twitter with any Scala news!

Posted in Mark's Blog | Tagged , , , , , , , , , , | 1 Comment

Merry Christmas


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) =>
      t match {
        case _: LeftNeedle => "/"
        case _: RightNeedle => "\\"
        case _: Trunk => "|"
        case _: Ball => "o"
        case _: Spike => "x"
        case _: Candle => "*"
        case _: BigBall => "oxo"
        case _: DoubleBall => "oo"
        case _: ElectricCandle => "***"
      }

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

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

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

    tree.reverse.foreach({l =>
      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 -->*<-- = new Star
}

object ChristmasTree extends DecorationBuilder {

  def main(args: Array[String]) {
           \-/.
         -->*<--
            .
           /.\
         ./.|.\.
         /.oxo.\
       ./.*.|.x.\.
       /.oo.|.oo.\
     ./.oxo.|.***.\.
     /.*.oo.|.*.oo.\.
           |||
  }

}
Posted in Jan's Blog | Tagged | Leave a comment

What can you expect at Cake Solutions

If you’re here, you know that we are looking for a new programmer to join our team. If you are considering joining us, I think it’s only fair that I explain what you can expect once you sign up.

Joy of discovering

There is no doubt that the work will be challenging. Not as in death marches towards unreachable deadlines, but challenging as in conceptually hard code. I, and the rest of the team, will want to see clear & skeptical thinking and good ideas. In fact, I would love to hire someone who is much smarter than I am!

You will get to write some boring code, there will be reports to implement, importers and exporters to write. I am looking for a person that will try to find elegant & flexible way to deal with those “boring” things! Are you stuck repeating yet another piece of JasperReports boilerplate? Create a library that simplifies it; and publish it at cakesolutions.org. Write a blog, explain what motivated you to create the library and what problem it solves.

Beyond the day-to-day programming, there will be plenty of opportunities to work on some very clever code. I can’t tell you about the details of the projects, but expect polyglot Java applications deployed in the cloud; expect custom hardware talking to the system; expect mobile applications (also with some custom hardware) that display & communicate with the system. Beyond the work for our clients, I will give you all the support and mentoring I am capable of to help you with your open source work.

I am the editor of the Open Source Journal and I’ve published various books with Apress and, if you dare, I will help you to do the same.

You know you want to!

Sounds good? I thought so.

Now, update your CV and send it over to janm${zavinac}cakesolutions.net, where ${zavinac} is @ (also Czech pub food, see Wikipedia). List your programming experience, include all your published work (publicly accessible projects, articles, books). Include all other technical experience you have, but do not say, for example, that you have Oracle RDBMS experience when all you’ve done is run $ sqlplus SCOTT/TIGER@//DB/ORCL; SELECT * FROM USER; I also don’t care that you know how to install Windows 95–that was 15 years ago!

Posted in Jan's Blog | Tagged | Leave a comment