Sunday, June 12, 2011

Scalatra MongoDB template project using SBT 0.10.x

I spent some time this weekend getting a basic Scalatra/Casbah/MongoDB project (much like the one I covered in this post) set up using SBT 0.10.0.

If you have looked at the newest version of SBT, you know that a lot has changed. SBT 0.7.x projects will not build under the newer versions without a bit of migration. I ran into some hiccups along the way, so I set up a template project to avoid having to figure it out again. It uses Nathen Hamblen's fantastic giter8(g8) tool to allow you to set up a new project in seconds. Hopefully other g8 users find this template useful.

Changes in SBT 0.10.x

I just want to note some of the changes I ran into in setting up this very simple project:

  • build.sbt file - SBT 0.10.x offers an alternative to the /project/build/Project.scala configuration file - you can put a *.sbt file in the root of your project and configure your project there using the new SBT DSL. You can still configure your project using Scala, but the API and file locations have changed. See the SBT documentation for details.

  • "jetty" context for the Jetty dependency - this one confused me as I didn't see it documented anywhere. The Jetty dependency in build.sbt should not use the "test" scope as it did with SBT 0.7.x but rather the "jetty" scope. Using "test" will cause the jetty-run command to silently fail in a most unhelpful way.

  • Jetty support no longer built-in - Unlike SBT 0.7.x which provided commands like jetty-run, jetty-stop and prepare-webapp for any Project extending DefaultWebProject, SBT 0.10.x requires a plugin to support web applications. See the project's homepage for setup and my template project for an example.


Template Project

You'll need to install SBT 0.10.x - README

You'll also need to install g8

Both tools are very easy one-time installs and worth having. Once they are installed, you should be able to run:


g8 JanxSpirit/scalatra-mongodb
cd *name-of-app*
sbt
> update
> jetty-run


You'll then be able to browse to the test resource to make sure it's working.

What's inside

The servlet provides two resources:
  1. 'test' - a 'Hello World' type resource just to make sure everything is working.

  2. 'msgs' - GET msgs to see all records currently in the database and a form to add another record - the form issues a POST to the same resource to add records

The project includes a few basic tests to get you started. Run 'sbt test' to see the test output.

The template allows you to configure where your MongoDB server is running, the name of your servlet and other parameters.

All source code is here: https://github.com/JanxSpirit/scalatra-mongodb.g8 I'd welcome any comments or suggestions or pull requests. Happy coding!

1 comment:

  1. Sir, you saved me hours and hours. Thanks so much for putting this together!

    ReplyDelete