Author: marius

Understanding sbt and sbt-web settings

Inside sbt-web: Part II – Understanding sbt and sbt-web’s settings

Just enough sbt

If we want to talk about sbt-web, we must first discuess a few concepts related to sbt itself1. sbt is the Scala Build Tool, often critized for being overly complex. It however enables a lot of interesting use cases, so one might argue its not incidental but domain-related complexity2.

Let’s first look at the abstractions sbt provides and then go on to understand how sbt-web builds on them.

Builds

A build definition corresponds to the project you’re building. Each build can consist of multiple sub-builds, with one being the root project, or root build. Each project contains a top-level build file, build.sbt, that corresponds to the root build. .sbt files allow a subset of Scala syntax, and are compiled by sbt to Scala files. Alternatively you can write Scala build files directly (all build-related Scala files go into the project folder), but with the recent additions to sbt, this is rarely needed.

If you don’t provide a build file, sbt will infer a standard build for you.

A typical project might look like this:

my-project/
  build.sbt             < -- root build file
  project/                <-- definitions for all sub-projects
    build.properties      <-- define sbt version
    plugins.sbt           <-- sbt plugins
    Common.scala          <-- common build code
  my-domain-model      <-- sub-project
    build.sbt             <-- sub-project build file
    src/main/scala/...    <-- sources
  my-play-web-ui
    build.sbt
    app
    conf
  my-play-admin-web-ui
    build.sbt
    app
    conf

▸ Read more...

Posted in Scala & Playframwork

Intro to sbt-web

Inside sbt-web: Part I – Using sbt-web

Introduction

sbt-web is an sbt-based web infrastructure for handling client-side files. It serves as the new foundation for the Playframework and potentially any other sbt-based web project. sbt-web defines a basic directory structure (overriden in Play), and it offers an API for processing sources, static files, and reporting errors.

Motivation

Why do we need a new web infrastructure, why was the old one not good enough?

When Play 2.0 was conceived in 2011, the developers chose to integrate several client-side technologies: CoffeeScript, LESS, Google Closure, and later RequireJS. These were tightly integrated into Play, so everyone who wanted to use something different (e.g. SASS or Dust) had to first learn sbt, write a plugin, and somehow deal with integrating that framework into Play’s build mechanism. This obviously wasn’t a flexible enough solution.

Additionally, no-one could foresee the activity and speed of innovation in the JavaScript world1. Every week there’s a new framework coming out, and existing ones make steady progress. The Node.js community alone is around 10x bigger than the Play community, so keeping CoffeeScript and LESS inside Play up-to-date was a daunting task.

It became more and more difficult to catch up. At some point it wasn’t even possible to update Twitter Bootstrap because of newer LESS features that weren’t supported by Play. And the Play team simply didn’t have the resources to update client-side dependencies every couple of weeks.

So with Play 2.3 the decision was made to factor out any client-side concerns into a new independent project called sbt-web. sbt-web introduces the notion of assets to sbt. Taken from the Rails world, assets are simply files that are served to and displayed or otherwise processed by the web browser.

sbt-web is organized via sbt plugins that use sbt-web’s infrastructure to make integrating and updating the latest tools easier.

Project Layout

The basic project structure2 defined by sbt-web adapts to the standard sbt (or Maven) conventions and essentially adds the assets folder to the mix.

The input folder is src/main/assets for source files that are potentially converted (e.g. from CoffeeScript to JavaScript) or otherwise processed both while developing and in production. src/main/public is for static assets. When preparing for production-readiness (staging), the two will be merged and processed.

Please note that the subfolder organization below assets is only an example, sbt-web doesn’t require you to use a specific naming scheme (or any subfolder at all for that matter).

There is also a src/main/test/assets folder indicating that sbt-web also supports testing client-side code.

+ src
--+ main
----+ assets
------+ js
----+ public
------+ css
------+ images
------+ js
--+ test
----+ assets
------+ js
----+ public
------+ css
------+ images
------+ js

▸ Read more...

Posted in Scala & Playframwork

PlayBasics Updated for Play 2.3.2

Over the weekend I have updated most of the PlayBasics projects to the latest version of the Playframework, 2.3.2. This includes the move to sbt-web and its plugins.

▸ Read more...

Posted in Scala & Playframwork

RequireJS Optimization with Play 2.2, WebJars, and CDNs

The Story So Far

This post is just a short follow-up to my previous post about using RequireJS with Play 2.1 and WebJars. In that post I laid out a general approach on how to modularize your Play app using RequireJS, and how to make it production-ready by dividing your RequireJS configuration into several files (one for development, one for production, one for building). This is obviously flawed and can be an easy source of errors when the versions of your WebJars assets don’t match up with CDN versions. It also violates the DRY principle. At the time however it was the only way to use these technologies together.

Meanwhile, In Another Galaxy

Direct RequireJS support

In the meantime, James Ward has been actively developing WebJars and its accompanying Play plugin with two notable enhancements.

First off, WebJars now supports RequireJS directly (previously, it was only limited to the Play plugin). This means it is no longer required to write require(['webjars!angular.js'], function(angular) {...}). Instead require(['angular.js'], function(angular) {...}) is sufficient. To differentiate WebJars libraries from local JavaScript files, the local ones should be prefixed with ./.

For example:

require(['angular', './common'], function(angular) {
  angular.module('myModule', ['common']);
});

▸ Read more...

Posted in Scala & Playframwork

Ping Conference, Play Edition, Day 2

pingconf-scifi

“We want to go crazy about technology today”

Continuing with the second day of the awesome Ping Conference, with no further ado, I’ll shortly summarize the talks. Here we go!

▸ Read more...

Posted in Scala & Playframwork

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

Posted in Scala & Playframwork

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

Actions

Overview

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.

EssentialAction

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

Posted in Scala & Playframwork

RequireJS Optimization with Play 2.1 and WebJars

RequireJS Optimization with Playframework 2.1 and WebJars

Motivation

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

Posted in Scala & Playframwork

Securing AngularJS Applications with Play

Intro

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 defaults.headers.post.

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

▸ Read more...

Posted in Scala & Playframwork

Using Play Routes with AngularJS and RequireJS

Using Play Routes with AngularJS and RequireJS

Intro

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

▸ Read more...

Posted in Scala & Playframwork