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.

This entry was posted in CoffeeScript, jQuery, Play Framework, Scala. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • Joaquin Garrido

    Hey, you cheater, you can’t reset the step numbers after 12!  ;P

    • http://www.jamesward.com James Ward

      Haha.  Well, you can always just git clone the github repo and start there.  :)

      • Joaquin Garrido

         Oooo, touché

  • jayfallon

    Really nice. Probably the first Heroku tutorial I’ve completed that actually deployed and worked on the platform the first time..

  • Hannu Leinonen

    In Play 2 it seems to be play eclipse instead of play eclipsify.

    • http://www.jamesward.com James Ward

      Hmmm…  I tried “play eclipse” and it didn’t work.  It suggested “eclipsify”.  Did “eclipsify” not work for you?

      • Hannu Leinonen

        This is what it says:

        [play-project] $ play-version
        [info] 2.0-RC2
        [play-project] $ eclipsify
        [error] Not a valid command: eclipsify (similar: eclipse)
        [error] Not a valid project ID: eclipsify
        [error] Not a valid configuration: eclipsify
        [error] Not a valid key: eclipsify
        [error] eclipsify
        [error]          ^
        [play-project] $ eclipse
        [info] About to create Eclipse project files for your project(s).
        [info] Successfully created Eclipse project files for project(s): play-project
        [play-project] $

        • http://www.jamesward.com James Ward

          I’m totally confused now…

          [foobar] $ play-version
          [info] 2.0-RC2
          [foobar] $ eclipse
          [error] Not a valid command: eclipse (similar: eclipsify, license, help)
          [error] Not a valid project ID: eclipse
          [error] Not a valid configuration: eclipse
          [error] Not a valid key: eclipse (similar: deliver, licenses, eclipse-pre-tasks)
          [error] eclipse
          

          I have no idea why we are getting different behavior with this.  Odd.

          • Hannu Leinonen

             Me too. I’m on Linux if that makes difference.

          • http://www.jamesward.com James Ward

            Ah.  That’s probably it!  Good work solving the mystery!

          • Felipe Butcher

            That’s because of the version. They changed the name from eclipsify to eclipse in recent versions.

  • http://twitter.com/VijayAnnadi Vijay Annadi

    Ran into this compilation error:

    type mismatch;
    found : play.api.data.Form[String]
    required: String 

    in: app/controllers/Application.scala at line 15.

    def index = Action {
    Ok(views.html.index(barForm)) <===== At this line
    }

    What am I missing? Thanks!

    • http://www.jamesward.com James Ward

      That is odd.  Can you cross reference your code with the code at:
      https://github.com/jamesward/play2bars-scala

      Let me know if you find a difference.  Maybe I missed something.

      • Ja11946

        James,
        I received the same error with the barForm… says it a type mismatch, required string… in Eclipse
        Thanks for your help

        • http://www.jamesward.com James Ward

          Hmmm….  Did you try the code from my github repo?  I’m not sure why this would be a problem.

          • http://www.menole.de/ Michael Mende

            you might want to check your template, (first line I guess)

          • W K

            I have run into this problem with Eclipse (with scala-ide) vs Play. Eclipse showed these errors, but the test app compiled and ran without a problem in Play. Now I have a weird state in Eclipse where the project shows no errors, but if I open Application.scala, there is an error flag on that line. Presumably this is because it was compiled behind Eclipse’s back, and now some state is out of sync.

          • xyz

            I meet the same issue, but just close eclipse and reopen it the error is gone.

    • user514949

      The problem is that you did not update the ‘app/views/index.scala.html’ template

      the ‘views.html.index(String) was generated by it, and until it is updated it would expect a String.

  • http://twitter.com/mariussoutier Marius Soutier

    Is there an easy way to create two different confs for dev and for prod?

    • http://www.jamesward.com James Ward

      Yeah, check out this example:
      https://github.com/jamesward/zentasks/blob/master/conf/prod.conf

      And then start Play with:

      web: target/start -Dhttp.port=${PORT} -Dconfig.file=conf/prod.conf
      • http://twitter.com/mariussoutier Marius Soutier

        Cool, and is it possible to use multiple Procfiles to set up different environments for CI, QA and Prod?

        • http://www.jamesward.com James Ward

          You would have one Heroku app per environment and then use an environment variable to adjust the config file to use, like:

          web: target/start -Dhttp.port=${PORT} -Dconfig.file=conf/${ENV_NAME}.conf

          You can set the the ENV_NAME variable for an app by running:

          heroku config:add ENV_NAME=prod
          • http://twitter.com/mariussoutier Marius Soutier

            Ok nice. One last thing, we put one small Play2 app on Heroku (locally it’s about 15 MB including compiled classes), but now Heroku reports the repo size to be 105 MB and a slug size of 95 MB.

          • http://www.jamesward.com James Ward

            I noticed that those are larger than expected.  We need to investigate further for a future Play RC.  Ultimately this is due to multiple copies of jars in different places.  We need to find a way to trim out what isn’t needed.

          • http://www.jamesward.com James Ward
  • dsstng

    Is it wise to already use play 2.0 for commercial projects?

    • http://www.jamesward.com James Ward

      I think it depends on when you need to ship by.  Since Play 2 is in RC I’d guess it will ship this summer.  If that aligns with your project then go for it.  Otherwise stick with Play 1 for now.

  • Rob Coon

    Saw your demo in Seattle, very impressive.  I meant to mention a recommendation in your jQuery–changing “$(“#bars”).append “Bar ” + item.name + “”" to ”
    $(“#bars”).append $(“”).text(item.name)” should prevent the majority of people attempting to inject js into your page.

  • Srinsriram

    Worked locally perfectly (on windows). So thanks for that given that all the components (heroku, scala, play, git) are new to me.   The upload to heroku was fine (it seemed to deploy the slug).. However accessing the URL indicated a problem (app crash).. and the logs indicate that

    2012-02-25T03:10:18+00:00 heroku[web.1]: Starting process with command `target/tart -Dhttp.port=17468 -DapplyEvolutions.default=true -Ddb.default.driver=someplace on amazon aws2012-02-25T03:10:18+00:00 app[web.1]: sh: target/start: not found

    I’d imagine that it should’ve prompted me to initialized the db (as it did locally).. what am I missing?

    • http://www.jamesward.com James Ward

      Is “target/tart” a typo?

  • ssam

    No, the t was deleted in the cut ‘n paste to the comment.. It was target/start 

    2012-02-25T14:51:35+00:00 heroku[web.1]: Starting process with command `target/start -Dhttp.port=18233 -DapplyEvolutions.default=true -Ddb.default.driver=blahblah etc.

    • http://www.jamesward.com James Ward

      Ok.  That is good.  Then something must have gone wrong when the slug file was created (on git push).  At that point “sbt stage” is supposed to run which generates the target/start script.  Can you try to run “sbt stage” locally and see if that works?  If you don’t have sbt locally then try “play stage”.

  • ssam

    Getting an error in Build.scala after “play stage” ..  a coding error.. maybe I incorrectly did the cut’n paste to Build.scala.. I see that the val already existed.. This time around it did work locally..  Need to get the mental model (which does not as yet exist). Now I just assume that I need to push it again.

    [error] C:Documents and SettingsSriramDesktopplayfoobarprojectBuild.scala:18: appDependencies is already defined as value appDependencies[error]      val appDependencies = Seq([error]          ^

  • Srinsriram

    I assume that play has a built-in copy of sbt for play stage to work..  Do I need to install sbt as a standalone as well?

    • http://www.jamesward.com James Ward

      You can either use play’s sbt (built-in) or install your own sbt.

      Yeah, just git commit -am the changes, then git push heroku master.

  • Srinsriram

    I destroyed my original app.. and  created a new one.. in the git push step, it seems to remember the old app name (even though its destroyed) with the message “No such app as ” and hangs.  Can’t one associate a git repo with a new heroku app? 

    • http://www.jamesward.com James Ward

      This is managed through git remotes.  You can do something like:
      git remote rm heroku
      git remote add heroku git@heroku.com:soft-spring-1234.git

      BTW: You probably didn’t need to destroy and recreate the app.

  • ssam

    Thanks  much! The Slug size approaches 80 mb (is that reasonable?) and apparently no db initialization was needed (as was the case in the local install). In the earlier case (when Build.scala was buggy) the remote build process didn’t display any errors (and completed a lot faster).   

    • http://www.jamesward.com James Ward

      See the discussion above about slug size.

      I would have expected the build to fail with a faulty Build.scala, but sbt is a bit immature.

  • bill

    In 

    $ -> $.get “/listBars”, (data) ->
    $.each data, (index, item) ->
    $(“#bars”).append “Bar ” + item.name + “”
    what is the “$ -> …” pattern? I’ve never seen that before and it’s hard to google for punctation :)

    • HighLight

      Search JQuery with CoffeeScript :)

  • http://www.anjan.net/ Anjanpathak

    I must thank you for this post. Everything work as expected.

  • http://profiles.google.com/pawelstawicki Paweł Stawicki

    I’m trying to run similar application, but when trying to push to heroku, I’m getting:

    [error] {file:/tmp/build_lhsutbwdl8uo/project/}default-be7cb3/*:update: sbt.ResolveException: unresolved dependency: play#sbt-plugin;2.0-RC2: not found
           Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?  !     Failed to build app with SBT 0.11.0
     !     Heroku push rejected, failed to compile Scala app
    Any ideas why I’m getting that? I noticed you use play 2.0-RC2 too.

    • http://www.jamesward.com James Ward

      Do you have a project/build.properties file containing:
      sbt.version=0.11.2

      • http://profiles.google.com/pawelstawicki Paweł Stawicki

        That’s correct. If I create the app by “play new helloworld” and try to push it to heroku, I get the same result.

        • http://www.jamesward.com James Ward

          It looks like they broke something in RC2.  Can you try RC3 instead?  Just update the following line in project/plugins.sbt to update to RC3:
          addSbtPlugin("play" % "sbt-plugin" % "2.0-RC3")

  • Mats Strandberg

    Hi!
    Thanks for a great post!
    Things may have changed with Play 2.0?
    I’m trying this with Play 2.0 and get thing like:
    not found: object anorm       [error] import anorm._       [error]        ^

    Importing anorm works fine locally, without having to add any dependencies.

    Any ideas?

    • http://www.jamesward.com James Ward

      Yeah.  I need to update this for the 2.0 release.  Hopefully I’ll have this done in the next day or so.

    • http://www.jamesward.com James Ward

      I’ve tested this locally and I’m not getting that error.  But if you cloned from my github repo then pull it again because I just updated it to the 2.0 release.  Does that help?

  • Mats Strandberg

    Tanks for you quick reply.
    I just made a fresh clone (after your “update for 2.0″ push).
    Works fine with ‘play run’ but when doing ‘git push heroku master’ 
    I get the same result. 
    Problem with:

    - import anorm.NotAssigned
    - import play.templates._
    - import com.codahale.jerkson.Json

    At least anorm and play.templates should there as part of Play 2.

    • Mats Strandberg

       …
             [info] downloading http://repo.typesafe.com/typesafe/releases/play/play-test_2.9.1/2.0/play-test_2.9.1-2.0.jar
             [info]   [SUCCESSFUL ] play#play-test_2.9.1;2.0!play-test_2.9.1.jar (55ms)
             [info] Done updating.
             [info] Compiling 6 Scala sources and 1 Java source to /tmp/build_30huwkfvm8emt/target/scala-2.9.1/classes…
             [error] /tmp/build_30huwkfvm8emt/app/controllers/Application.scala:6: not found: object anorm
             [error] import anorm.NotAssigned
             [error]        ^
             [error] /tmp/build_30huwkfvm8emt/target/scala-2.9.1/src_managed/main/views/html/index.template.scala:4: object templates is not a member of package play
             [error] import play.templates._
             [error]             ^
             [error] /tmp/build_30huwkfvm8emt/app/models/Bar.scala:6: not found: object anorm
             [error] import anorm._
             [error]        ^
             [error] /tmp/build_30huwkfvm8emt/app/controllers/Application.scala:32: object codahale is not a member of package com
             [error]   import com.codahale.jerkson.Json
             [error]              ^
             [error] class file needed by Router is missing.
             [error] reference value codehaus of package org refers to nonexisting symbol.
             [error] 5 errors found
             [error] {file:/tmp/build_30huwkfvm8emt/}foobar/compile:compile: Compilation failed
             [error] Total time: 2 s, completed Mar 21, 2012 2:54:55 PM
       !     Failed to build app with SBT 0.11.0
       !     Heroku push rejected, failed to compile Scala app

      • http://www.jamesward.com James Ward

        Ah crap.  Just reproduced locally by running: sbt clean stage

        I’ll look further into this.

  • Mats Strandberg

    My clone of your play2bars-scala now works! As well as my own project and also Tobias project is OK :
    https://twitter.com/#!/jarlund/status/182714391408553984
    Apparently some repo file fixed by Play(?).
    Thanks again for your time and this page!

    • http://www.jamesward.com James Ward

      Great!  I just tried it and it worked for me too.  I had to clear out my .ivy2 cache though.

  • at0mz

    Hi,  :)
    How about the Play 2.1-SNAPSHOT version ? Could it be deploy to heroku ?

    • http://www.jamesward.com James Ward

      That should work as long as you’ve set the dependency and repos correctly.

      • at0mz

        Hi, help me please I got an error.

        [warn]   ::          UNRESOLVED DEPENDENCIES         ::
        [warn]   ::::::::::::::::::::::::::::::::::::::::::::::
        [warn]   :: play#sbt-plugin;2.1-SNAPSHOT: not found
        [warn]   ::::::::::::::::::::::::::::::::::::::::::::::
        [warn]
        [warn]   Note: Some unresolved dependencies have extra attributes.  Check that these dependencies exist with the requested attributes.
        [warn]           play:sbt-plugin:2.1-SNAPSHOT (sbtVersion=0.11.2, scalaVersion=2.9.1)
        [warn]
        [error] {file:/tmp/build_1ek66cq934nc3/project/}default-103227/*:update: sbt.ResolveException: unresolved dependency: play#sbt-plugin;2.1-SNAPSHOT: not found
        Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?  !     Failed to build app with SBT 0.11.0

        In plugin.sbt file, 

        // The Typesafe snapshots repositoryresolvers += “Typesafe Snapshots” at “http://repo.typesafe.com/typesafe/snapshots/”// Use the Play sbt plugin for Play projectsaddSbtPlugin(“play” % “sbt-plugin” % “2.1-SNAPSHOT”)

        How to fix it ? 

        Thanks in advance :)

        • http://www.jamesward.com James Ward

          It looks like there is something wrong with their snapshot repo.  This file is 404-ing:
          http://repo.typesafe.com/typesafe/snapshots/play/sbt-plugin/scala_2.9.1/sbt_0.11.2/2.1-SNAPSHOT/ivys/ivy.xml

          You could compile Play 2.1 locally and then setup a local file repo with something like:
          Resolver.file(“localRepo”, file(“repository/local”))(Resolver.ivyStylePatterns),

          • at0mz

            Hi,

            Now, I can push my project on Heroku but I got some error.

            2012-03-23T09:24:26+00:00 heroku[web.1]: Starting process with …….: No such file or directorypp[web.1]: /usr/bin/env: sh2012-03-23T09:24:27+00:00 heroku[web.1]: Process exited with status 1272012-03-23T09:24:27+00:00 heroku[web.1]: State changed from starting to crashed2012-03-23T09:24:27+00:00 heroku[web.1]: State changed from crashed to created2012-03-23T09:24:27+00:00 heroku[web.1]: State changed from created to starting

            My Procfile,

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

          • http://www.jamesward.com James Ward

            We are making progress. :)  You can test this locally by running:
            sbt stage
            target/start

            First, make sure that works.

          • at0mz

            After I ran “play stage” command, everything is ok.

            [info] Your application is ready to be run in place: target/start[info][success] Total time: 14 s, completed Mar 23, 2012 4:56:48 PM

            I’m use Windows.

            How to run “target/start” in Windows ?

            Thanks :D

          • http://www.jamesward.com James Ward

            Ah shoot.  I think they only generate that for unix.  You can look in there to see what they are doing (probably just setting the classpath and running a java -jar command).

  • http://twitter.com/ilcavero ilcavero

    I noticed that the slug generated by Play 2 applications is quite large (near 80mb), does this make heroku/play a less than ideal match?

  • BALA MANI

    Hai!

     I need your help:

    Build.scala
    ————–

         val appDependencies = Seq(
          // Add your project dependencies here,
           “net.vz.mongodb.jackson” % “mongo-jackson-mapper” % “1.4.1″,
           “org.mongodb” % “mongo-java-driver” % “2.7.3″,
           “com.mongodb.casbah” % “casbah_2.9.0-1″ % “2.1.5.0″
           
           
        )

    Application.config
    ———————-

    mongodb.host=localhost
    mongodb.port=27017
    mongodb.database=testDb

    But I can’t able to connect my application to Mongodb.  How do i connect?

    Help me ?

    By
    bdeveloper01

    • http://www.jamesward.com James Ward
      • BALA MANI

        Sir!
          Thanks for your replay!
          It is Scala related model. I need Java related Model

         Scala
         sbt plugin

         ”com.fasterxml” % “jackson-module-scala” % “1.9.3″

        lly i need for java

         Thanking you Sir!
         by
         bdeveloper01

  • Suresh

    James,
    I am trying to deploy computer database java sample application on Heroku. Deployment is complete but getting the following error while accessing the pages 
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:63)
    [play_2.9.1-2.0.jar:2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at akka.actor.Actor
    $class.apply(Actor.scala:290) [akka-actor-2.0.jar:2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m play.core.ActionInvoker$
    $anonfun$receive$1$$anon$1: Execution exception
    [[PersistenceException: models.Computer is NOT an Entity Bean
    registered with this server?]]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    play.core.ActionInvoker.apply(Invoker.scala:61) [play_2.9.1-2.0.jar:
    2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    akka.actor.ActorCell.invoke(ActorCell.scala:617) [akka-actor-2.0.jar:
    2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m Caused by:
    javax.persistence.PersistenceException: models.Computer is NOT an
    Entity Bean registered with this server?
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    akka.dispatch.Mailbox.processMailbox(Mailbox.scala:179) [akka-
    actor-2.0.jar:2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    com.avaje.ebeaninternal.server.core.DefaultServer.createQuery(DefaultServer.java:
    1031) ~[ebean-2.7.3.jar:na]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    com.avaje.ebeaninternal.server.core.DefaultServer.createQuery(DefaultServer.java:
    988) ~[ebean-2.7.3.jar:na]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    com.avaje.ebeaninternal.server.core.DefaultServer.find(DefaultServer.java:
    1024) ~[ebean-2.7.3.jar:na]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at play.db.ebean.Model
    $Finder.query(Model.java:258) ~[play_2.9.1-2.0.jar:2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at play.db.ebean.Model
    $Finder.where(Model.java:706) ~[play_2.9.1-2.0.jar:2.0]
    [32m2012-04-07T09:00:37+00:00 app[web.1]:←[0m at
    models.Computer.page(Computer.java:48) ~[computer-
    database_2.9.1-1.0.jar:1.0]
    Can you please help…. source is the same as the github (https://github.com/playframework/ Play20/tree/master/samples/java/computer-database)-Suresh

    • http://www.jamesward.com James Ward

      I responded to your StackOverflow question.

      • Suresh

        Thanks, James. Issue is resolved, it was because of some changes from my side. 

  • Marvin

    Hi James, 

    I am trying out your sample application, and file index.coffee never got compiled during build, I don’t see index.js in /public/javascripts. I tried to compile in the Play console and within Eclipse without success. Do I need to add something to Build.scala? Or how can I tell which files and directories are included in the build?Thanks

    • http://www.jamesward.com James Ward

      That gets generated by the Play 2 asset compiler when it’s needed.  You won’t see it in the public directory since it gets handled in a special way.

      • Marvin

        Hi James, 
        Thanks for your reply, I found out the hard way. Play2 stored the index.js under an obscure subdirectory of /target/scala-2.9.1/resource_managed/..
        I also had a mis-spelled index.js in the html file so I didn’t see the list of bars. The Play2′s  documentation contains lots of outdated information that sent me on a few wild goose chases so far. Even the “Your first Application” tutorial got the Procfile for Heroku wrong, I got the correct syntax from your tutorial. Thanks again for the tutorial and your help. 

        Marvin

        • http://www.jamesward.com James Ward

          Glad you figured it out.  The location of the compiled index.js shouldn’t matter.  Why do you need to know where it is?

          What was wrong with the Play 2 doc’s Procfile?  We should fix it if it’s wrong.

  • motobass4321

     I am getting a 404 for /assets/stylesheets/main.css.  The favicon and jquery library are served though.

    • http://www.jamesward.com James Ward

      That is due to a bug in Play 2.  If the file is empty then Play returns a 404.  If you open the main.css file and add a line or something then it won’t 404 anymore.

  • Ratul

     Hi,

    After I deployed my application to heroku, all of static content requests for images, javascripts, css are giving a 404 response. I am not using the main.css at all – instead I am using them as shown in the tutorials. What is way out?

    • http://www.jamesward.com James Ward

      Make sure your public directory and it’s contents are in the git repo.

  • li-o

    Hi,

    Nice article! I’ve one question, if I change ‘-DapplyEvolutions.default=true’ to ‘false’ evolutions is still ran. Even if I remove the whole parameter, evolutions is still ran. Is that a bug? Or am I doing something wrong?

    Thanks!

    • http://www.jamesward.com James Ward

      You mean when you run on Heroku or run locally?

      • li-o

        When in run on Heroku

        • http://www.jamesward.com James Ward

          That is odd.  Maybe the default is true.  Or you have changed the default value in the application.conf file.

  • http://www.facebook.com/profile.php?id=601895552 James Lei

    Strange, I got Js error: ReferenceError, data is not defined. What wrong with the coffeescript code?

    • http://www.jamesward.com James Ward

      Make sure you have the indentation correct.

  • Richard

    I’m a bit late to the party, but I’d like to do this tutorial. I have the same issue as Vijay with barForm not working as a val ref or a String (type mismatch). In following your advice to compare with the GitHub version I see that the page is no longer there. Has it been taken down? Or do you have further advice for resolving this issue. I tried the basic restart of Eclipse and also running from the command line, but no go…
    …foobar/target/scala-2.9.1/src_managed/main/views/html/index.template.scala:27: not found: value form
    [error] “”"),_display_(Seq[Any](/*6.10*/helper/*6.16*/.inputText(form(“name”)))),format.raw/*6.40*/(“”"

    Thanks for your tuts! Would like to try more…

  • sfgsdfgs

    can not read a json object in views of play20 framework

    • http://www.jamesward.com James Ward

      Can you give more details?

  • http://www.facebook.com/adamwilloughbyknox Adam Willoughby-Knox

    Thanks so much for the great tut. It is really helping me get started with play / json.

    I get anested id in my json, is that expected ? I’m used to mysql so not being able to see the db is weird to me, i guess that is the next tut.


    [{"id":{"id":1},"name":"test 1"},{"id":{"id":2},"name":"test 2"},{"id":{"id":3},"name":"and another thing"}]

    • http://www.jamesward.com James Ward

      That is probably just a problem with how the case class is getting auto-serialized. You could do manual serialization. But I think this is much better in Play 2.1.

  • codee

    I don’t think anyone had my problem, so I must be doing something wrong that is totally trivial and obvious to the rest of the world. Hopefully, someone can help.

    a) I did set my environment PATH

    b) “play help” works everywhere except inside the heroku template for play! that I downloaded

    c) after restarting and with new windows the problem remains

    d) I am working on Ubuntu

    This is the problem I am having:

    Getting org.scala-sbt sbt ${{sbt.version}} …

    :: problems summary ::
    :::: WARNINGS
    module not found: org.scala-sbt#sbt;${{sbt.version}}

    ==== local: tried

    /home/XX/play-2.1.0/repository/local/org.scala-sbt/sbt/${{sbt.version}}/ivys/ivy.xml

    ==== Maven2 Local: tried

    file:///home/XX/.m2/repository/org/scala-sbt/sbt/${{sbt.version}}/sbt-${{sbt.version}}.pom

    ==== typesafe-ivy-releases: tried

    http://repo.typesafe.com/typesafe/ivy-releases/org.scala-sbt/sbt/${{sbt.version}}/ivys/ivy.xml

    ==== Maven Central: tried

    http://repo1.maven.org/maven2/org/scala-sbt/sbt/${{sbt.version}}/sbt-${{sbt.version}}.pom

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: UNRESOLVED DEPENDENCIES ::

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: org.scala-sbt#sbt;${{sbt.version}}: not found

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
    unresolved dependency: org.scala-sbt#sbt;${{sbt.version}}: not found
    Error during sbt execution: Error retrieving required libraries
    (see /home/XX/play-2.1.0/framework/sbt/boot/update.log for complete log)
    Error: Could not retrieve sbt ${{sbt.version}}

    • http://www.jamesward.com James Ward

      That is pretty odd. What happens if you run the play command using it’s full path?

      • codee

        same thing happens. Also a “which play” gives me the correct version. I have a feeling something gets overwritten, so that it doesn’t know how to set the variable correctly any more (sbt.version) which is set correctly in framework/project/build.properties Somehow it doesn’t get that part inside the project directory.

        • http://www.jamesward.com James Ward

          Perhaps something with your Play install is bad. Maybe try to reinstall. Or it could be something funky in your ~/.sbt dir.

          • codee

            reinstall ? (argh) – it took forever to install this morning… but ended with “success”

            .sbt includes nothing except a directory called staging which includes nothing.

          • http://www.jamesward.com James Ward

            How did you install it?

          • codee

            Download from here: http://www.playframework.com/

            Follow README file instructions for linux

            I just created a new project using “play new test”

            It creates an entire “project/” directory including its own project/build.properties file that the template didn’t have. Now play help works.

            On the command “play run” I am still having problems though.

            [info] Loading project definition from /home/XX/git/heroku/playappstart/project
            [info] Updating {file:/home/XX/git/heroku/playappstart/project/}default-64e53c…
            [info] Resolving org.scala-sbt#precompiled-2_10_0;0.12.2 …
            [info] Done updating.
            [info] Set current project to default-d2960f (in build file:/home/XX/git/heroku/playappstart/)
            [info] Updating {file:/home/XX/git/heroku/playappstart/}default-d2960f…
            [info] Resolving org.scala-lang#scala-library;2.9.2 …
            [info] Done updating.
            java.lang.RuntimeException: No main class detected.
            at scala.sys.package$.error(package.scala:27)
            [trace] Stack trace suppressed: run last compile:run for the full output.
            [error] (compile:run) No main class detected.
            [error] Total time: 0 s, completed Mar 25, 2013 4:42:16 PM

          • codee

            I need to be more clear – on the self generated project “play run” works. Just not on the template. Did I miss a step that would have created the “project/” directory in the template?

          • codee

            The template from Heroku : java.heroku.com: Webapp with play! Framework that I used to generate my project.

          • http://www.jamesward.com James Ward

            Oh! That is a Play 1 app!

          • codee

            ok — well bummer – I missed that. Thanks for your quick help.

          • http://www.jamesward.com James Ward

            What “template” are you referring to?

  • David

    I rewritten the demo app (JAVA version), but when i submit some name the coffeescript is not executed. I have no idea whats happening.

    • http://www.jamesward.com James Ward

      Check your browser console to see if there are any errors.

  • Jason Zwolak

    Is this really the recommended way to create objects from the database? My RowParsers are getting really long; how many times do I have to type “firstName” in my User model before I have a simple CRUD model? I count 6 in my application. Ruby on Rails: 0! I like the idea of taking control of the SQL, but it would be nice to have a more terse way to create parsers and create / update methods. Currently I have to create everything by hand for all my columns. This is getting tedious. Any ideas?

  • Zhou Fengfeng

    Hi, James! I got a problem.When i ran command ‘run’ with sbt, it didn’t work.This is what it says:

    java.lang.RuntimeException: No main class detected.

    at scala.sys.package$.error(package.scala:27)

    [trace] Stack trace suppressed: run last compile:run for the full output.

    [error] (compile:run) No main class detected.

    [error] Total time: 0 s, completed 2014-3-5 21:48:34

    I ran it in current dir.

    • http://www.jamesward.com James Ward

      What version of Play are you using?

      • Zhou Fengfeng

        play-2.2.0.and i want to tell you that i have solved the problem. sorry for that.

  • akash


  • View James Ward's profile on LinkedIn