Ping Conference, Play Edition, Day 1

PingConf logo

Ping Conference, Play Edition, Day 1

A few days ago I attended Ping Conf, the first ever conference about Play, organized by Peter Hausel (@pk11), and Gawker Media in Budapest. ▸ Read more...

Playframework 2.2 Action Building and Action Composition

Play 2.2 Building and Composing Actions

New Results in 2.2

One of Play 2.2’s biggest changes is the complete overhaul of the Action and Results architecture. While it did work pretty well in earlier versions, there also used to be a great variety of Results to choose from:

  • Result
  • PlainResult
  • SimpleResult
  • AsyncResult
  • ChunkedResult

Play 2.2 reduces all this to SimpleResult (to be renamed to Result in 2.3). The previous result types have been deprecated and will be removed in Play 2.31.

This leads to the following mapping:

Play 2.0/2.1 Play 2.2
Result, SimpleResult, PlainResult SimpleResult
AsyncResult Future[SimpleResult]
ChunkedResult SimpleResut (via Status.chunked(Enumerator))



To produce a SimpleResult or Future[SimpleResult] easily, Actions now work differently than before.

The official documentation is sparse as always, so I want to give an overview over the changed principles of Actions and Action composition. This article doesn’t show many code examples because I created a new PlayBasics sub-project that walks you through the presented concepts.


On the top of the Action hierarchy sits EssentialAction2, already introduced with Play 2.1 and until now mostly used when dealing with EssentialFilters or streaming data directly from the request.

An EssentialAction is closer at Play’s implementation details than an Action. It is defined like this:

trait EssentialAction extends (RequestHeader => Iteratee[Array[Byte], SimpleResult])

So an EssentialAction extends a function from RequestHeader to an Iteratee. If that confuses you, just rewrite it as a class:

class EssentialAction extends Function1[-RequestHeader,+Iteratee[Array[Byte], SimpleResult]] { def apply(rh: RequestHeader): Iteratee[Array[Byte], SimpleResult] } ▸ Read more...

RequireJS Optimization with Play 2.1 and WebJars

RequireJS Optimization with Playframework 2.1 and WebJars


In a previous post I showed how to use WebJars with RequireJS in Play to manage web dependencies.

What that post lacked was to explain how to make your app production-ready, i.e. combine all your files into one, minify the result, and to map WebJars resources to CDN URLs 1. Play currently 2 offers nothing to do this automatically, so we need to some of the work by hand.

I will also continue to show how to integrate AngularJS with Play. Angular is an excellent framework for building complete Single Page Applications, and using Play as a REST backend is the perfect companion.

RequireJS Configuration

When you run play stage or play dist, Play runs the RequireJS optimizer. The optimizer cannot resolve the WebJars RequireJS plugin (as in webjars!angular.js) and throws an error 3. As shown before, you usually specify a main JavaScript file that is loaded by RequireJS when your web app is loaded. Accordingly, if we want to use different paths for our WebJars in production, we need to use a separate main file (I’ll name these mainDev.js and mainProd.js). We can tell Play to use the production file by adding the requireJs and requireJsShim build parameters.

val main = play.Project(appName, appVersion, appDependencies).settings( requireJs += "mainProd.js", requireJsShim += "mainProd.js" ) ▸ Read more...

Securing AngularJS Applications with Play


When you start migrating from classic page-reloading web applications, it can be quite confusing how to secure your JavaScript-driven app. Sure, you could keep using cookies, but cookies aren’t very secure, even more so if you allow them to be read from JavaScript.

James Ward from Typesafe wrote an excellent article about this topic, so I don’t want to repeat this here but instead encourage you to read his article first. In summary, the server generates an authentication token that our application uses to sign all requests by adding a custom HTTP header (X-AUTH-TOKEN for example).

He also shows how to implement this approach in “normal” JavaScript, jQuery and Play-Java. How is this done in AngularJS and Play-Scala? It’s actually pretty easy, let me show you how.

Signing Requests

In AngularJS we use the $http service to make AJAX-requests. $http’s provider (i.e. the module responsible for injecting the $http service), $httpProvider, offers us the possibility to define default headers. If you want to sign every request, you add them to the defaults.headers.common object. If you only want specific HTTP verbs, you can for example add the header to

$"/login", credentials).then(function(response) { $httpProvider.defaults.headers.common["X-AUTH-TOKEN"] = response.token; }); ▸

Using Play Routes with AngularJS and RequireJS

Using Play Routes with AngularJS and RequireJS


With the appearance of JavaScript frameworks like AngularJS, it has become a lot easier to write Single-Page-Applications on the web. Play, especially in it latest incarnation 2.1 and even more so in the upcoming releases, supports this style of development with its JavaScript router, RequireJS support and the WebJars project.

So instead of continuing the templates series, I want to show you how you use AngularJS, RequireJS and WebJars with Play. For this tutorial you should already be familiar with these technologies, although it shouldn’t be hard to follow if you know at least JavaScript.

The Problem

Play has a nice router which allows type-safe routes. There is also built-in functionality to make this router available as a JavaScript object (as described in this previous blog-post). It allows you to easily make AJAX calls on your routes, for example to log in, you could call

controllers.Application.login().ajax({ method:'POST', data:Json.stringify(credentials), success:function(data){} }) ▸

Migrating to Play 2.1

Play 2.1 Migration

I have just finished migrating one of my apps from Play 2.0.4 to 2.1 and while doing that I compiled a list of all the big & little things that I had to adapt. My app uses many parts of Play (except Anorm) so hopefully it will cover a lot of problems you will encounter. My app is written entirely in Scala, so changes in the Java API will (mostly) not be covered. First of all you should read the official migration guide.


Compilation times seem to have become even slower than before. Even on simple project with only a few files you can wait a good amount of time after changing a single file. I could actually trace this back to the fact that even when running play ~run (automatic compilation on file change, only useful when you’re not using an IDE) doesn’t prevent a re-compile when refreshing the browser.

What’s gone

Mixing Scala and Java API and using templates doesn’t seem to be possible anymore. As soon as you add javaCore to your dependencies, your templates will expect their types from either the Scala or Java API, whereas before it would choose the correct one for you.

Using Option in path parameters (they removed the PathBindable). You can implement your own PathBindable for this (as shown here), however they are right in that it doesn’t make much sense to have an optional value in your path.

What’s changed

Scala Futures

Play 2.0’s Promise has been replaced by Scala 2.10’s Future. This also means that instead of Akka.future {} you now wrap code that should be computed asynchronously with scala.concurrent.Future {}. And don’t forget to bring the right execution context in scope. The default execution context in Scala is, Play offers another one with play.api.libs.concurrent.Execution.Implicits._). If you have some blocking code, make sure to use a different context so the server thread won’t block.

More infos in the official documentation and in this excellent introduction.


The JSON parser has been rewritten. For one, the reads method no longer returns the value directly, but is wrapped in a JsResult. JsResult is a monadic structure which can be constructed using validate and allows for our well-known for comprehension:

implicit object UserReads extends Reads[User] { def reads(json: JsValue): JsResult[User] = for { name < - (json "name").validate[String] email <- (json "email").validate[String] password <- (json "password").validate[String] } yield User(name, email, password) } ▸ Read more...

Akka Essentials Review

Akka Essentials Review


I’m using Play 2.0 a lot these days, and to fully understand its asynchronous nature, you have to understand Akka. ▸ Read more...

Playframework Routes – Part 2, Advanced Use Cases

Play Routes – Part 2, Advanced Use Cases

Localized routes

There are different approaches to managing the user’s locale in a multi-language site. If most of the content is only available after log-in, a cookie backed by an entry in the User table should be enough. On your landing page you check for the Accept-Language header or check the IP address. Just make sure that Google Bot can index all publicly visible pages.

On content-heavy sites, one Google-compatible approach is to define the language in the URL. The first component of the URL should be the language (or, if really needed, both language and country). Using the first part of the URL not only to make it easier to differentiate for the user but also to makes it easier to manage the site in Webmaster Tools.

We have two options here. Either we define a regex, or we hard-code our supported languages. The second approach must be chosen when we optimize for Google (see section below).

# Map to language via RegEx /$language< [a-z]{2}>/videos/:id controllers.Video.showVideo(id: Long, language: String) # Hard-code supported languages /de/videos/:id controllers.Video.showVideo(id: Long, language = "de") /en/videos/:id controllers.Video.showVideo(id: Long, language = "en") ▸ Read more...

Tagged with: , ,

Playframework Routes – Part 1, Basics

Play Routes – Part 1, Basics

Routes? What’s to explain?

Routes in Play are not a difficult concept to grasp, but as always, the devil is in the details. Let me show you how to get the most out of routes and how to tackle some of the typical problems in designing the routing scheme of a Play web application.

Defining routes

Before we dive into the details, let’s recap the basics.

A route is a mapping from a URL to a controller action. Routes are defined in a Play project’s routes file in the conf folder. You can only use one routes file and routes in submodules are currently not supported (but will be in the upcoming 2.1 release).

A route is defined by specifying the HTTP method (Play supports GET, PUT, POST, DELETE), the path, and a fully-qualified controller method (usually called an action). These three elements are separated by as much whitespace as you like.

# Show the index page GET / controllers.Application.index() # Login POST /login controllers.Application.login() ▸ Read more...

Tagged with: , ,

Play Framework 2.0 Templates – Part 1, Parameters


Play Framework 2.0 includes a new and improved templating engine, based on Scala (also known as Twirl). When you don’t know Scala, this can be a bit of a hurdle to overcome. But instead of switching to a different engine, I invite you to learn the basics of Play Scala templating, as it is quite powerful and a joy to use.

What is a Template

A template is essentially a function, mapping its input values to either HTML, XML or any other text output. Everything is compiled and type-checked, that’s why you always have to declare all input parameters. Templates are files inside the views folder and use the naming convention <template-name>.scala.<format>. By default html, xml and txt are the supported formats.

The basic concept is based on ASP.NET Razor and uses the @-sign to mark occurrences of code that will be interpreted by the templating engine. To help the templating engine understand what is code and what is not, you can surround a line of code with @(). This is necessary when a white-space would indicate end of code. A full block of code can be defined with @{} – however this is something I try to avoid as much as possible because it indicates the view is doing the controller’s work.

Templates are rendered by the controller as a response to a request. For example, if you have a template app/views/users/profile.scala.html, you render it from your Java controller
like this:

return ok(views.html.users.profile.render());

Likewise, you can call it from other templates (never forget, it’s just a function):


For the rest of this article, I’m going to assume you have read (or at least skimmed) the templates articles from the Play wiki (Templates and Use Cases).


The first line of every template contains the parameter list(s). In Scala, you can define as many parameter lists as you like (we’ll see an application for that later on). Unlike Java, the type of a parameter comes after the name: <name>: <Type>. A simple template parameter list might look like this:

@(message: String)

Parameters can have default values and can be called by their name. Imagine you have a template that should either display a user’s data as text or as an edit form (depending on some logic elsewhere), you could include a boolean to indicate whether or not the object is editable for the current user. Since you don’t always want to explicitly pass the parameter, you can define a default:

@(user: User, isEditable: Boolean = false) ▸

Tagged with: , ,