Tutorial: Play Framework 2 with Scala, Anorm, JSON, CoffeeScript, jQuery & Heroku

Play Framework 2 RC2 has been released and it is quickly becoming a mature and productive way to build modern web apps. Lets walk through building a quick app with Play 2, Scala, Anorm, JSON, CoffeeScript, and jQuery. Once the app works locally we will deploy it on the cloud with Heroku. (Note: This is the Play 2 + Scala version of my Play 1 + Java tutorial.) You can grab the completed source from GitHub.

Step 1) Download and install Play 2 RC2

Step 2) Create a new application:

play new foobar

When prompted select to use Scala as the language.

Step 3) In the newly created “foobar” directory generate the IDE config files if you’d like to use one. For IntelliJ, run:

play idea

Note: This generates an iml file which is not directly importable as a project. Instead you need to create a new project without a module and then import the module from the generated iml file. If you need help with this, follow instructions 8 – 10 in my Play 1 + Scala IntelliJ article.

For Eclipse, run:

play eclipsify

Step 4) Start the Play server:

play run

Test that it works by visiting: http://localhost:9000

Step 5) Play 2 with Scala doesn’t provide an ORM by default. Instead the default RDBMS persistence provider is Anorm (Anorm is Not an Object Relational Mapper). This simple application will just have one persistence object: a Bar with a primary key and a name. Anorm requires a SQL schema creation / destruction script since it doesn’t do auto schema creation. Create a new file named “conf/evolutions/default/1.sql” containing:

# --- First database schema
 
# --- !Ups
 
CREATE TABLE bar (
  id                        SERIAL PRIMARY KEY,
  name                      VARCHAR(255) NOT NULL
);
 
# --- !Downs
 
DROP TABLE IF EXISTS bar;

Anorm can use a Scala “case class” as a Value Object and a singleton object as the persistence / CRUD interface. Create the Bar case class and object in a file named “app/models/Bar.scala” with the following contents:

package models
 
import play.api.db._
import play.api.Play.current
 
import anorm._
import anorm.SqlParser._
 
case class Bar(id: Pk[Long], name: String)
 
object Bar {
 
  val simple = {
    get[Pk[Long]]("id") ~
    get[String]("name") map {
      case id~name => Bar(id, name)
    }
  }
 
  def findAll(): Seq[Bar] = {
    DB.withConnection { implicit connection =>
      SQL("select * from bar").as(Bar.simple *)
    }
  }
 
  def create(bar: Bar): Unit = {
    DB.withConnection { implicit connection =>
      SQL("insert into bar(name) values ({name})").on(
        'name -> bar.name
      ).executeUpdate()
    }
  }
 
}

The “simple” var provides a basic row parser that maps a database row values to the Bar case class. The “findAll” and “create” static functions just do the regular data access stuff. Notice how the “findAll” function uses the “simple” row parser to turn each row into a Bar.

Step 6) Configure the default data source to use an in-memory h2 database by adding the following values to the “conf/application.conf” file:

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"

Step 7) Create an Application controller function that will translate a HTTP POST into a Bar and then save it to the database by updating the “app/controllers/Application.scala” file to be:

package controllers
 
import play.api.data.Form
import play.api.data.Forms.{single, nonEmptyText}
import play.api.mvc.{Action, Controller}
import anorm.NotAssigned
 
import models.Bar
 
 
object Application extends Controller {
 
  val barForm = Form(
    single("name" -> nonEmptyText)
  )
 
  def index = Action {
    Ok(views.html.index(barForm))
  }
 
  def addBar() = Action { implicit request =>
    barForm.bindFromRequest.fold(
      errors => BadRequest,
      {
        case (name) =>
          Bar.create(Bar(NotAssigned, name))
          Redirect(routes.Application.index())
      }
    )
  }
 
}

The “barForm” maps request parameters to a Form object and can apply validations to the incoming data. The “addBar” static function handles a request and attempts to map the request parameters to the “barForm”. If it fails then the controller returns a BadRequest. If it succeeds then the Bar’s name is used to construct a new “Bar” which is saved into the database and a redirect to the index page is sent. The index function has been changed to pass the “barForm” to the template which will be updated in Step 9.

Step 8) Create a new route to map POST requests to the “/addBar” URL to the “Application.addBar” function by adding the following line to the “conf/routes” file:

POST    /addBar                     controllers.Application.addBar

Step 9) Update the “app/views/index.scala.html” template to take the Form parameter, extend the “main” template, and then use the Play 2 form helper to render the form on the web page:

@(form: play.api.data.Form[String])
 
@main("Welcome to Play 2.0") {
 
    @helper.form(action = routes.Application.addBar) {
        @helper.inputText(form("name"))
        <input type="submit"/>
    }
 
}

In your browser load http://localhost:9000, apply the database evolution, and test the form. If everything works when you submit the form you should just be redirected back to the index page.

Step 10) Create a JSON service to get all of the bars by adding a new function to the “app/controllers/Application.scala” file:

  import com.codahale.jerkson.Json
 
  def listBars() = Action {
    val bars = Bar.findAll()
 
    val json = Json.generate(bars)
 
    Ok(json).as("application/json")
  }

This new function returns the list of “Bar” objects from “Bar.findAll()” as serialized JSON.

Add a new GET request handler for requests to “/listBars” by adding the following to the “conf/routes” file:

GET     /listBars                   controllers.Application.listBars

Try it out by opening http://localhost:9000/listBars in your browser. You should see the Bar you created in Step 9.

Step 11) Create a new CoffeeScript file that will use jQuery to fetch the JSON serialized Bars and add each one to the page by creating a new “app/assets/javascripts/index.coffee” file containing:

$ ->
  $.get "/listBars", (data) ->
    $.each data, (index, item) ->
      $("#bars").append "<li>Bar " + item.name + "</li>"

This CoffeeScript uses jQuery to make a GET request to “/listBars”, iterate through the returned data, and add each item to the “bars” element on the page (which will be added in Step 12).

Step 12) Update the “app/views/index.scala.html” template to use the index.js script that is automatically compiled from the CoffeeScript source by adding the following to the “main” block:

    <script src="@routes.Assets.at("javascripts/index.js")" type="text/javascript"></script>
 
    <ul id="bars"></ul>

In your browser load http://localhost:9000 and verify that the bars are being displayed on the page and that adding new bars works as expected.

Great! You just built a Play 2 app with Scala, Anorm, JSON, CoffeeScript, and jQuery! All of the source code for this example is on GitHub. Now lets deploy it on the cloud with Heroku.

Step 1) Create an account on Heroku.com, install the Heroku Toolbelt, install git, and then login to Heroku from the command line:

heroku login

If this is the first time you’ve done this then new SSH keys for git will be created and associated with your Heroku account.

Step 2) Each application on Heroku has a Postgres database for testing. To use that database when running on Heroku we need to configure it. There are a few ways to do that with Play 2 but the easiest will be to override the database settings with the startup command line – which we will setup in Step 3. Before we do that we need to specify the Postgres JDBC driver as a project dependency. In the “project/Build.scala” file set the “appDependencies” like so:

    val appDependencies = Seq(
      "postgresql" % "postgresql" % "9.1-901-1.jdbc4"
    )

Step 3) To tell Heroku what process to run we need to create a file named “Procfile” (case sensitive) in the project’s root directory containing:

web: target/start -Dhttp.port=$PORT -DapplyEvolutions.default=true -Ddb.default.driver=org.postgresql.Driver -Ddb.default.url=$DATABASE_URL

Play 2 uses the Scala Build Tool (SBT) to build the project. When the project is deployed to Heroku the “sbt stage” command is run to compile the project. That process generates a “target/start” script that sets the Java classpath and starts the Play server. Heroku tells our application what HTTP port to listen on using the “PORT” environment variable so the “http.port” Java property is set accordingly. Also the default way to provide database (and other resource) connection strings to an application on Heroku is through environment variables. The DATABASE_URL environment variable will contain the database host, name, username, and password. So the “db.default.url” property is set with that value. Also the driver is set to the Postgres JDBC driver class.

Step 4) Heroku uses git as a means to uploading applications. Whether or not you use git for your SCM tool you can use git as the tool to upload an app to Heroku. In the root directory of your project create git repo, add the files to it, and then commit the files:

git init
git add Procfile app conf project public
git commit -m init

Note: Instead of doing a selective “git add” you can update the “.gitignore” file.

Step 5) Now we will provision a new application on Heroku using the Heroku CLI. Each application you create gets 750 free “dyno” hours per month. So as a developer you can use Heroku for free and only pay when you need to scale beyond one dyno. On the command line create a new application using the “cedar” stack:

heroku create -s cedar

This creates an HTTP endpoint and a git endpoint for your application. You can also use a custom name and point your own domain names at the application.

Step 6) The application is ready to be deployed to the cloud. From a command line do a “git push” to the master branch on Heroku:

git push heroku master

Once the files have been received by Heroku, Play Framework’s precompiler will be run, Heroku will assemble a “slug file”, and then the “slug” will be deployed onto a dyno.

Step 7) You can now open the application in your browser by navigating to the domain outputted following the “heroku create” or by simply running:

heroku open

You’ve deployed a Play 2 app with Scala, Anorm, JSON, CoffeeScript, and jQuery on the cloud with Heroku! For more details on how to use Heroku, check out the Heroku Dev Center. Let me know if you have any question.

Tutorial: Play Framework, JPA, JSON, jQuery, & Heroku

UPDATE: This tutorial is for Play 1.x (an old version). Check out my Play 2 Tutorial if you want to get started with the latest stuff. (Thanks to John Borys for pointing this out.)

If you are a Java developer then you really need to give Play Framework a try. It is really refreshing to take a few minutes, step out of the legacy-feeling world of traditional Java web app development and into something modern and fun. I want to walk you through a very simple tutorial where we will build a web application with Play Framework. The application will use JPA for persistence and expose access to the data through a JSON over HTTP interface. The client-side of the application will be built with jQuery. Lets get started.

Step 1) Download and install Play Framework 1.2.3

Step 2) Create a new Play app from the command line and then move to the new directory:

play new playbars
cd playbars

Optional Step 3) If you want to work in an IDE then you can run one of the following commands and then open the generated project in your IDE:

play idealize
play eclipsify

I won’t walk though the IDE specific steps here, but you can refer to the Play documentation on IDE integration if you want to get that setup. Note that IntelliJ IDEA has great support for Play Framework with a console right in the IDE.

Step 4) Start the Play server from the new project’s directory :

play run --%test

This starts Play in test mode which will automatically recompile any changes we make to the application. No packaging, redeploying, or restarting servers will be needed.

Step 5) Open the application in your browser:
http://localhost:9000

The default page provides you with great Play documentation on how to get started. But we will soon be changing that page. If you want to view the documentation locally after we change the page you can use these links:

Step 6) Lets start by creating a new JPA entity. Keeping it very simple, lets create a new “app/models/Bar.java” file containing:

package models;
 
import play.db.jpa.Model;
 
import javax.persistence.Entity;
 
@Entity
public class Bar extends Model {
 
    public String name;
 
}

This entity uses the standard JPA Entity annotation but also extends the Play Model class which provides some nice conveniences which you can read more about in the Play JPA docs. I’m using just a plain public property on this class but you can also use the Java Bean getter/setter stuff in you like.

Step 7) Create a simple unit / integration test for this Bar object by creating a “test/BarTest.java” file with the following contents:

import org.junit.*;
import java.util.*;
import play.test.*;
import models.*;
 
public class BarTest extends UnitTest {
 
    @Test
    public void integrationTest() {
        Bar bar = new Bar();
        bar.name = "a new bar";
        bar.save();
        assertNotNull(bar.id);
        assertTrue(Bar.findAll().size() >= 1);
        bar.delete();
        assertTrue(Bar.findAll().size() == 0);
    }
 
}

Step 8) Setup the default database by editing the “conf/application.conf” file and uncommenting the following line:

# db=mem

This sets up the default database to be an in-memory database.

Step 9) Run the application’s tests by opening the following URL in your browser:
http://localhost:9000/@tests

Select “BarTest” and then click the “Start!” button. The test should pass.

Step 10) Add the following two methods to the “app/controllers/Application.java” file:

    public static void addBar(Bar bar) {
        bar.save();
        index();
    }
 
    public static void listBars() {
        renderJSON(Bar.findAll());
    }

The addBar method takes a Bar, saves it, and then redirects back to the index page. Play will automatically parse request parameters and populate the Bar object. The listBars method queries for all of the Bars in the database and then outputs then as serialized JSON.

Step 11) Play has a very flexible model for mapping URLs to controllers. Lets setup two new routes that will map URLs to the new methods we’ve added to the Application controller. Add the following lines to the “conf/routes” file but make sure you either add them above the “Catch all” or simply remove the “Catch all” route:

POST    /                                       Application.addBar
GET     /bars.json                              Application.listBars

The first route handles HTTP POST requests to the “/” URL and handles them with the Application.addBar method. The second route handles requests to the “/bars.json” URL and handles them with the Application.listBars method.

Step 12) Lets add a FunctionalTest that will actually make requests to the Controller and test that our new routes and controller methods are working. Add the following method to the “test/ApplicationTest.java” file:

    @Test
    public void barTest() {
        Response addBarResponse = POST("/", APPLICATION_X_WWW_FORM_URLENCODED, "bar.name=foo");
        assertStatus(302, addBarResponse);
        Response listBarsResponse = GET("/bars.json");
        assertIsOk(listBarsResponse);
    }

This test adds a new Bar by doing an HTTP POST to “/” and passing it some form encoded data. Then a request is made to “/bars.json” and the response is checked to make sure there wasn’t an error. Since there isn’t a DELETE method (which could easily be added) there isn’t a good way to clean up what this test does.

Run the ApplicationTest Functional Test in the Play Framework Web Test Runner:
http://localhost:9000/@tests?select=ApplicationTest.class

Because the test didn’t clean up after itself you can now see the JSON from “/bars.json” in your browser by visiting:
http://localhost:9000/bars.json

Step 13) Now it is time to create the actual web UI for this application. A combination of plain HTML (via Play’s Groovy templates) and jQuery will be used. Play Framework uses a convention to render the HTML from the “app/views/Application/index.html” template when Application.index‘s render method is called. In the “index.html” file and you will see:

#{extends 'main.html' /}
#{set title:'Home' /}
 
#{welcome /}

You can also take a look at the referenced “app/views/main.html” file to see what the base template looks like. It does the standard HTML page stuff and then inserts the body of the “index.html” page into the “#{doLayout /}” section. The “main.html” template also loads jQuery and provides a way to insert some JavaScript into the head section of the page. In the “index.html” file, replace the “#{welcome /}” line with a form that will allow users to create new bars:

#{form @addBar()}
    <input type="text" name="bar.name"/>
    <input type="submit"/>
#{/form}

The “#{form @addBar()}” syntax is Groovy that creates a form tag and sets the form action to the URL that corresponds to the Application.addBar method. You can test this out by loading this page in your browser:
http://localhost:9000/

The form should be functional now. Enter the name of a bar and click the submit button. Because the “addBar” method calls the “index” method, after the POST, the browser is redirected back to the index page. You can verify that the data is being saved by loading the bars.json page again.

Now lets add some Ajax / jQuery to the “index.html” page that will get the JSON data and display it in the page. Add an empty ul tag with an id of “bars”:

<ul id="bars">
 
</ul>

Now we will insert the JavaScript into the correct place in the page by setting the “moreScripts” variable:

#{set 'moreScripts'}
<script type="text/javascript">
    $(function() {
        $.get("bars.json", function(data) {
            $.each(data, function(index, item) {
                $("#bars").append("<li>Bar " + item.name + "</li>");
            });
        });
    });
</script>
#{/set}

Using jQuery this bit of JavaScript adds a function handler for when the page is loaded, then in that function it makes a get request to “bars.json”. That request has a function handler for when the result comes back from the Ajax request. Inside that function handler the data is iterated through and each “bar” is appended into the page element with the id of “bars” – the ul tag.

Try out the application and make sure that you can still add new bars and see the list of all the bars in the database.

Now that everything works locally, lets deploy the app on the cloud using Heroku.

Step 1) Create an account on Heroku.com, install the Heroku Toolbelt and git and then login to Heroku from the command line:

heroku login

If this is the first time you’ve done this then new ssh keys for git will be created and associated with your Heroku account.

Step 2) Each application on Heroku has a Postgres database for testing. To use that database when running on Heroku we need to configure it. Play applications on Heroku run in “prod” mode. To set the database to use the Heroku database add the following lines to the “conf/application.conf” file:

%prod.db=${DATABASE_URL}
%prod.jpa.dialect=org.hibernate.dialect.PostgreSQLDialect
%prod.jpa.ddl=update

The default way to provide database (and other resource) connection strings to an application on Heroku, is through environment variables. The DATABASE_URL environment variable will contain the database host, name, username, and password. Play Framework knows how to handle that information and setup the JDBC connections.

Step 3) Heroku uses git as a means to uploading applications. Whether or not you use git for your SCM tool you can use git as the tool to upload an app to Heroku. In the root directory of your project create git repo, add the files to it, and then commit the files:

git init
git add app conf public test
git commit -m init

Note: Instead of doing a selective “git add” you can create a “.gitignore” file containing the files to not add to the git repo.

Step 4) Now we will provision a new application on Heroku using the Heroku CLI. Each application you create gets 750 free “dyno” hours per month. So as a developer you can use Heroku for free and only pay when you need to scale beyond one dyno. On the command line create a new application using the “cedar” stack:

heroku create -s cedar

This creates an HTTP endpoint and a git endpoint for your application. You can also use a custom name and point your own domain names at the application.

Step 5) The application is ready to be deployed to the cloud. From a command line do a “git push” to the master branch on Heroku:

git push heroku master

Once the files have been received by Heroku, Play Framework’s precompiler will be run, Heroku will assemble a “slug file”, and then the “slug” will be deployed onto a dyno.

Step 6) You can now open the application in your browser by navigating to the domain outputted following the “heroku create” or by simply running:

heroku open

You’ve built a Play Framework application with JPA, JSON, & jQuery and then deployed that application on the cloud with Heroku! Now get the code and check out a demo on Heroku. Let me know if you have any questions.