Use Twirl in your next project

The Twirl project is the engine used by Play to support the creation of views in our projects. A some time ago, this project was separated from the core of the framework and, nowadays, is possible to use this fantastic template engine in any Scala/Java project.

The only problem is that you have to use SBT in order to have your views being compiled all the time. Thinking about that, @csokol and I have created a new project that allows you to use Twirl in every app, using SBT or not. Basically we created a class which compiles your views and other class that watches every change in the views directory.

If you are using maven, you can use whatever you want, you just need to follow a simple steps. First you have to download our project, for while you need to clone the repo and install locally. After that, you just need to run our class :).

 mvn exec:java -Dexec.mainClass="" -  Dexec.cleanupDaemonThreads=false

Put some views in the source folder src/main/twirl/simple.scala.html, for example:

  @(customer: String)

   <h1>Welcome @customer</h1>

Let’s say you are writing a servlet and want to return some html for the browser. We just need to use the generated class!

   public class TwirlServlet extends HttpServlet {
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Html clientPage = html.simple.apply("client");


Twirl is a powerful template engine and deserves some attention. The Java world needs a new approach to write views, JSP is too old and does not have a good support to a lot of things needed by our views. You already have Freemarker but, at least in my opinion, Twirl and its compiled views is the next step. For example, you can test your view in a simple way, just invoke a method :).

   public void shouldContainsCustomerName(){
      Html clientPage = html.simple.apply("client");

That is it! This was a different post, not completely related with Play, I hope you had enjoyed.

Reminders about deploying Play apps in Heroku

Put your application in production, also known as deploy, is one of the most important aspects of our lives as developers. This is one more thing that is too much easy with Play. Let’s walk through for some important details about deploying apps in Heroku.

There is step by step guide here. The main problem that I usually see with people that are trying to use heroku is about the details in the procfile and the database configuration. The procfile is used to configure heroku in order to start your application. This file is needed by Foreman, a ruby gem used to manage all processes necessary to run your application. Here an example:

  web: target/universal/stage/bin/acasaesuadecor-landing 

Heroku uses the stage command to generate the deploy structure for the Play app, that is why you used this path. You need to have this file in order to run your app. It also needs to be placed in the root of your project. All information between curly braces will be provided by Heroku, in their environment.

If you take a closer look, you will see the parameter named Ddb.default.url and this is a point of confusion between a lot of people. All the information needed to connect to the database is provided in the url. You only need to configure, in your production.conf, the driver information.


If you configure, for example, the password. This information will be used and you will get an exception in Heroku, explaining that the password is wrong.

That is it :). I am gonna try to write about the webjars in the next post!

Customizing the loading of provider’s configuration in Secure Social

In my last project, which I had to use a lot of features of Secure Social, I had to customize the way this plugin loads social credentials from the securesocial.conf file. Let me explain a little bit my problem. It is a multi tenant app and the tenant is defined by a subdomain. For example, and should load different configurations of facebook.

The problem is that Secure Social loads the social credentials from a configuration file. By default it is not possible to load multiple configurations, at least as far as I know :). So, in order to allow this kind of behavior, I had to specialize the provider and change this part of the plugin. Let’s see the code and the problems.

The first thing we need to is to inherit from the FacebookProvider class(italico) and override a method which name is settings(negrito)

    public class CustomFacebookProvider extends FacebookProvider{
    	public CustomFacebookProvider(Application application) {
    	public OAuth2Settings settings() {

This method is invoked to load the configuration. The default behavior is to load all information in the application startup, take a look in github(link para o github). Now we need to access the database and load the specific credentials of a tenant

	public OAuth2Settings settings() {		;
		User client = Users.findByDomain(Context.current()._requestHeader().domain())
		return new OAuth2Settings(

There is just one problem, and it is a big one. I am using the Java version of Play and, at this point, the request was not set in the ThreadLocal(italico) used by Play to handle the execution of a client. In order to solve this problem, I had to use a little bit of bad practice of code, which is called POG here in Brazil(Programação orientada a gambiarra) . There is a method called doAuth(italico) which is responsible for authenticate a user in Secure Social and this same method receives a request as a parameter. So take a look in my solution:

        private static ThreadLocal<String> domainContext = new ThreadLocal<>();

	public OAuth2Settings settings() {		;
		User client = Users.findByDomain(domainContext.get())
		return new OAuth2Settings(

	public <A> Either<Result, SocialUser> doAuth(final Request<A> request) {
		Either<Result, SocialUser> doAuth = super.doAuth(request);
		return doAuth;

I used a ThreadLocal to store the current request and use it in the method settings(italico). I know it is not the best, but I could not store this request in a instance variable because the provider is loaded as a plugin, and plugins are singletons. Using this technique I can retrieve the domain and pass it to the method responsible for loading the tenant information.

The last part is that you have to change the configuration in your play.plugins(negrito) file.


That is it folks! Every week I try to write something that was useful for me in one my projects. If you have any topic that is interesting for you, comment here and I will be glad in writing about!


Plugins as extension points for your apps!

Normally, we use plugins to help us in a daily tasks, for example: send emails, secure our actions, upload files to amazon etc.  Play itself has a lot of parts built on top of plugins, more examples: evolutions, ebean and web service client. Another usage of plugins is as extension points of our apps.

In one of my current projects, the application needs to process a lot of data and provide a visualization for the client. This is a multi tenant app. So there is a core which is responsible for processing the information and there are specialized apps which are responsible for build its own visualization. Let’s take a look in the piece of code in the core:

    public class AllocationResult {

    	public String getBrokenConstraintsAsString(){
           //need the Html object with the visualization
           return html;


As you can see, after processing we need to generate the visualization part. Here is where the plugin can be used.

        public abstract class BrokenConstraintsViewPlugin implements Plugin{

        	private Application application;

        	public BrokenConstraintsViewPlugin(Application application) {
        		this.application = application;

        	public abstract Html getView(Collection<ConstraintMatchTotal> constraints);

        	public boolean enabled() {
        		return true;

        	public void onStart() {
        		// TODO Auto-generated method stub


        	public void onStop() {
        		// TODO Auto-generated method stub

        }    }

We created the plugin as an abstract class, in order to force the client apps to inherit this class and build the visualization. Now we can use Play to load the specialized plugin!

    public class AllocationResult {

    	private static BrokenConstraintsViewPlugin constraintsPlugin = Play

    	public String getBrokenConstraintsAsString(){
    		Html html = constraintsPlugin.getView(constraints);
    		return html.body();


We can pass the abstract class as argument and the Application(negrito) class will load the specialization. Of course, you need to register your plugin in the play.plugins file.

This feature is very important in order to provide extension points in your apps.  If you are building an API using Play, maybe this feature will be helpful for you :). Thanks for reading!

Secure social login and Play authenticator together

It is quite common use facebook, twitter and other social networks as a login provider for application. In Play world, Secure Social is one of the most used! Here in the blog there is a tutorial that guides you to configure this extension in your project. But, it is also important that your web app provides a formal way to register new users, using a common registration form.

For this last case, the normal way to control user access is using the Play plugin, provided by the framework “out of the box”. The problem here is the integration between these two plugins. When your user authenticates through a social network, Secure Social is the one responsible for checking the access control, it already has annotations for this case. While that when the user authenticates, for instance, through your database, you will probably want to use the plugin annotation provided by Play to control the user access.

In order to use both together, you have to change the Play’s session with information that came from the social login. The good news is that Secure Social has this exactly feature! You can create a listener that can be notified when new social login is done :). Let’s see the code.

    class SocialLoginEventListener(app: play.Application) extends EventListener {
      override def id: String = "my_event_listener"

      def onEvent(event: Event, request: RequestHeader, session: Session): Option[Session] = {
        event match {
          case e: LoginEvent => {
            val loggedUser = event.user.asInstanceOf[WrapIdentity].getUser()

          case e:LogoutEvent => Option(Session.deserialize(Map[String,String]()))
          case _ => None

You just have to change the session. I put the email information here because this is the key being used for my Play Authenticator, fell free to change and use what is better for you. Another point is that Secure Social provides only a Scala version of this feature. Remember, it is not a problem, your Play project is Java and Scala! You can combine both languages to take advantage of both worlds.

Now you have to configure Secure Social to use your listener. You have to add an entry in your play.plugins file.

  #my implementation of a service

That is it, now you are able to use both login ways together without a problem! As last week I did not write,  I am gonna write twice in this one.

Using Play-S3 plugin to upload files to Amazon.

One of the most common task in applications around the world is the file upload. And, nowadays, instead of store these files in our server, is quite normal send them to Amazon S3. In this post let’s see how to use the Play-S3 plugin for a Play application using Java.

The first problem is that this plugin only has a Scala version. What are you gonna do? Are you going to implement everything again? It seems a little bit over… As we has already discussed in another post, your Play project is Java and Scala, together! Let’s mix both languages and take advantage of this plugin.

The first thing you have to do is to add the Play-s3 as a dependency in your build.sbt file.

    libraryDependencies ++= Seq(
      "org.hibernate" % "hibernate-entitymanager" % "3.6.9.Final",
       "mysql" % "mysql-connector-java" % "5.1.20",
       "org.mindrot" % "jbcrypt" % "0.3m",
       "ws.securesocial" %% "securesocial" % "2.1.3",
       "nl.rhinofly" %% "play-s3" % "3.3.5"

Now you have to configure your access and secret key in order to enable the upload of files to S3. This configuration, as usual, is placed in the *.conf file of your application.


Previously, you could get these keys from your root account in Amazon but, for security reasons, a few weeks ago they started to force you to follow a new process to configure your keys. You have to use the Identity and Access Management (IAM) and create your keys. They suggest that you create a pair of keys for each kind of user that your application has. The choice is yours 🙂

Now let’s take a look in the code necessary to upload a file.

    val result:Future[Unit] = bucket + BucketFile("pdfs/yourfile.pdf",
      "application/pdf",IOUtils.toByteArray(new FileInputStream(pdfFile)),Some(PUBLIC_READ))

There are a two important objects here. Bucket and the BucketFile. The first is needed to identify which folder(bucket) contains all your uploaded files from your current application. It is easy to create this object.

    private val bucket = S3("youpet")

Probably you will create one bucket per application.

The BucketFile is just a wrapper with all information needed about your file being uploaded. The last parameter is a little bit important. It is recommended to pass which roles this file has. Here we are saying that everyone can read(download). All this code can be encapsulated in a Scala class that can be used from your Java code :).

    object AmazonS3 {
      private val bucket = S3("youpet")

      def upload(folder: String, file: File,fileName:String): WaitingForS3 = {
        val timestampedName = FilenameUtils.getBaseName(fileName)+"_"+System.currentTimeMillis()+"."+FilenameUtils.getExtension(fileName)
        val s3Url = bucket.url(s"${folder}/${timestampedName}")

        val result:Future[Unit] = bucket + BucketFile(s"${folder}/${timestampedName}",
          IOUtils.toByteArray(new FileInputStream(file)),Some(PUBLIC_READ)) { unit =>
          Logger.debug(s"Enviou o arquivo $s3Url")
        }.recover {
          case S3Exception(status, code, message, originalXml) =>"Error: " + message)

        new WaitingForS3(s3Url,result)

This same code is available here. Feel free to copy and use in your projects :). Of course you could use all these Scala classes from your Java code directly but, in this case there are “functions as parameters” and “case classes” that are hard to translate to Java code. It is better isolate this code in a Adapter class and only expose a simple method to your Java side.

That is it! Upload your files to S3 and just have to deal with the links of your uploaded files :). It is easy to maintain and you gain, as a bonus, things like cache out of the box :).

Composable pages and the Cache feature

The Cache feature provided by Play, in both versions, is very well known. It is so important, that has its own page in the documentation. Just to give a quick description. Once you have put the @Cache annotation in your action, after the first request, the html generated will be stored and reused for the consecutive requests. The same thing applies to the Scala version.

The downside of this approach is that, almost every page in our application, has a relation with the current logged user. So, if you put the name of the user in the home page, like in GUJ(brazilian java forum), you just lost the opportunity to use the cache feature. You always have to remember, this cache is global. One approach could be create cache entries related with the current user, but this will imply an explosion of entries in the cache implementation.

In one of my posts, that was related with the Big Pipe idea presented in the talk given by Linkedin, it was demonstrated how you can compose your pages, loading each piece from a different request. Something like Page as a Service :). If you follow this approach you can gain another thing, the ability to cache just certain pagelets from your page!

Let’s see how we could compose the home page of GUJ using the “big pipe” approach implemented by Linkedin.

    public static Result index() {
      F.Promise news = ServiceClientJ.makeServiceCall("recent/news");
      F.Promise recentTags = ServiceClientJ.makeServiceCall("recent/tags");
      F.Promise availableJobs = ServiceClientJ.makeServiceCall("jobs");
      F.Promise infoqNews = ServiceClientJ.makeServiceCall("infoqnews");

      F.Promise newsHtmlPromise = render(news,;
      F.Promise recentTagsHtmlPromise = render(recentTags, views.html.guj.recent_tags.f());
      F.Promise availableJobsHtmlPromise = render(availableJobs,;
      F.Promise infoqNewsHtmlPromise = render(infoqNews, views.html.guj.infoq_news.f());

      HtmlStream newsStream = Pagelet.renderStream(newsHtmlPromise, "news");
      HtmlStream recentTagsStream = Pagelet.renderStream(recentTagsHtmlPromise, "recentTags");
      HtmlStream availableJobsStream = Pagelet.renderStream(availableJobsHtmlPromise, "availableJobs");
      HtmlStream infoqNewsStream = Pagelet.renderStream(infoqNewsHtmlPromise, "infoqNews");

      HtmlStream body = HtmlStream.interleave(Arrays.asList(newsStream, recentTagsStream,availableJobsStream,infoqNewsStream));

      return ok(HtmlStream.toChunks(;

As you can see, the page is built based on several requests! If you, for example, want to cache the “recent tags” pagelet, just put the @Cache annotation in this controller’s action.

    public class RecentTags extends Controller{

    	@Cached(key = "recent_tags", duration = 3600)
    	public static Result index(){
    		return ok(views.html.tags.index.render(;

Now you are taking advantage of the cache feature! I really like this approach and I will try to use it in my next projects :).

Organizing composable Play apps with Flexbox

Yevgeniy Brikman made a awesome presentation about how Linkedin solved its problems to build complex web pages. The basic problem is that, for instance, your profile’s page is too complex and keep one single file like a jsp, to build all this html, is not maintainable. Obviously, we are thinking in a long running app.
There are a lot of objects that have to be loaded to create that page. For example:

  • Basic information like: name, current company, etc.
  • Background information
  • Skills and Endorsements
  • Education
  • People also viewed

This is a major problem for all big web sites and each one has its own version of solution. A lot of them, load the snippets of page from iframes and with this, they can load these pieces from everywhere they want… Another approach is when the server sends a almost blank page and every snippet is loaded from ajax calls. Both approaches solve the problem but it delegates a lot of responsibility to the browser.

The third possibility, which is more difficult, would be load all snippets in your server side and glue them to build the requested page. Using this approach, even in a synchronous way, you would have just small pages that are more testable, easier to maintain and would send to browser just a simple html. Facebook engineers wrote about that in this amazing post.

Linkedin guys used this same approach to change the way them build web pages. They used Play’s API to fetch small pieces of html and aggregate these snippets to compose the page. But if you remember, Play is all about async and streaming data. So Linkedin went ahead and used this power to fetch all pagelets in async way, using the Promise’s API provided by Play. Now, and if the last Promise completes its job before the first one, what your controller would have to do? Wait for the first? The answer is no! If you have a partial of your html, just send to the browser :). To accomplish this task, they used the Iteratee and Enumerator API to stream each html partial as soon as it is available. This project is hosted on github(link aqui) and I advise you to take a serious look!.

Everything is really cool until now, but how they organize all pagelets to build the page? I mean, there is a order between Background information’s block and Education’s block . They solved this using a simple Javascript snippet inside pagelet’s template. Take a look:

    @(contents: Html, id: String)

    <script type="text/html-stream" id="@id-contents">

    <script type="text/javascript">
      document.getElementById("@id").innerHTML = document.getElementById("@id-contents").innerHTML;

Each pagelet knows what is its id in the main template. So, it is used javascript to put the returned html in the correct place, smart :). Talking with @sergio_caelum and @srsaude, masters in frontend topic, they warned me about the high cost that is to use innerHtml in your browser. Especially if you have to use it a lot of times! So they proposed to me that would be interesting if the Linkedin had used the Flexbox property in CSS3. This property, allows you rearrange every element in your page with CSS, no Javascript is needed. I liked the idea so I forked the code and I made this little change.

Now, each snippet has its own div and I just have to define the appearance order in the CSS file :).

    @(wvypCount: Int, searchCount: Int)

    <div class="wvyp">
      <h2>Who's Viewed Your Profile</h2>


And now the css code:

    .wvyp {
    	display: -webkit-flex;
    	display: flex;
    	-webkit-flex-flow: column;
    	 flex-flow: column;

    .wvyp .wvyp-count {
    	color: #0077b5;
    	-webkit-order: 1;
    	 order: 1;

    .wvyp .search-count {
    	color: #333;
    	-webkit-order: 2;
    	order: 2;

Now, I can even delete the pagelet template file :). This changed version is in my repository, go there and take a look!.

I really like this idea and I wish to have a chance to apply this solution in one of the systems that I am helping to build. What did you think? I had to write this post because this presentation is one of the best that I ever saw :). I don’t remember when I spent 50 minutes watching a video!




Play 2.3, Java 8 and async results

For the Java developers, Play 2.3 greatest feature is the native support for Java 8 and all things that are possible with lamba support.  Almost all pieces of code that were built with anonymous classes now can be replaced with lambdas.

Let’s see the case when we want to return a async result. The older version is like this:

    Promise<List<Photo>> promise = Promise.promise(new Function0<List<Photo>>() {

    	public List<Photo> apply() throws Throwable {
  		  return JPA.em().createQuery("select p from Photo p",Photo.class)

    return Function<List<Photo>, Result>() {

    	public Result apply(List<Photo> photos) throws Throwable {
    		Html render =;
    		return ok(render);

The new version with lambdas is way more cleaner.

    Promise<List<Photo>> listingPhotos = Promise.promise( () -> {
    	return JPA.em().createQuery("select p from Photo",Photo.class).getResultList();

Remember, all methods that receive functional interfaces(interfaces with just one method) can be used passing lambda as arguments!

And here, we didn’t separate our code like we should. Database access is being done in our controller. If we put this code in a different class, we can improve the usage of promise.

  Promise<List<Photo>> listingPhotos = Promise.promise(Photos::all);

Method Reference is a great feature to use with lambdas, the code is much more cleaner. Now you have to use map method to transform the Promise<List<Photo>>  to Promise<Result>.  This will be a common situation around your application.

    return -> {
    	Html render =;
    	return ok(render);

Here we can try to be more creative. I would like to use Method Reference to create Promise<Result> rather than use the map method. It would be nice if we had used a pimped version of Promise class with statuses map method. Here a example:

    return new PimpedPromise<List<Photo>>(listingPhotos).

There is nothing out of the box in Play so, to accomplish this, we can create our pimped version! Take a look:

    public class PimpedPromise<T> {

    	private Promise<T> promise;

    	public PimpedPromise(Promise<T> promise) {
    		this.promise = promise;

    	public <B extends Content> Promise<Result> map(play.libs.F.Function<Content, play.mvc.Results.Status> statusFunction,Function<? super T, B> callback) {
    		Promise<B> contentPromise =;
    		return -> {
    			return statusFunction.apply(content);


We just changed a little bit the signature of map method :). We forced the developer to pass a function(second argument) that returns a Content object. Then we get the result of and we have to map again using the status function(first argument). Maybe it is a little bit complicated inside our pimped promise but is, at least for me, better to be used in controllers.

What do you think? Have you tried to create something new with the lambda support?

Multi tenant approach with Java 8 in a Play project.

In my current project, I had to implement a multi tenant approach. There is nothing new about this, I have to check if current user is the owner of some resource. And I have to do the same thing across other several actions. The best way to do this, is to build an Action composition and compose all actions with it. So, let’s say we have this route:


Now, when we try to access this resource, our interceptor will be invoked:

    public Promise<SimpleResult> call(Context context) throws Throwable {
    	RoleType currentRole = CurrentUser.role();

    	Long currentLoggedUserId =;
    	Long clientParamId = //get parameter here;
    	for (RoleType roleType : rolesAllowed) {
    		&& roleType.acceptsTenant(currentLoggedUserId,clientParamId)){
    			try {
    			} catch (Throwable e) {
    				throw new RuntimeException(e);
    	return Promise.<SimpleResult>pure(
    	  Controller.unauthorized("You are not allowed to see this page"));

And now we have a problem. How do we extract the client id from the url? The first thing that I thought was: All parameters are in request data…

  Long clientParamId = Long.parseLong(context.request()

Unfortunately, Play does not provide this information anywhere :(, if you try to run this code, you will get a NPE. This probably happens because in Scala version you would not have this problem, in there you compose actions in a different way. Basically you can invoke the “call” method from your controller’s action, using the functional support provided by the language instead of using annotation. You can see more here(link). To solve my problem, I used the same approach. Let’s see:

    public static Result updateForm(final Long id) {
    	return new RoleAction(User.class, id, RoleType.ADMIN,RoleType.TENANT)
    			.call(new Function0<Result>() {
    				public Result apply() throws Throwable {
    					User user = JPA.em().find(User.class, id);
    					Form<User> filledForm = userForm.fill(user);
    					return ok(views.html.admin.users.update_form.render(filledForm));

It is a little bit verbose, no doubts, but I needed to delivery this feature :). And now I can access all parameters that I need. Just to make the job less annoying, I’ve created a Eclipse template that allows me just write “roleAction” and the code template is generated automatically :).

The good thing about this approach is that, now with Java 8, we can change this implementation in order to use the new lambda support :). Play with Java8 is a lovely thing!

    return new RoleAction(User.class,id,RoleType.ADMIN,RoleType.TENANT)
   .call( () -> {
    	User user = JPA.em().find(User.class, id);
    	Form<User> filledForm = userForm.fill(user);
    	return ok(views.html.admin.users.update_form

What do you think? One nice thing here is that I didn’t need to change the original call method. When you have just one method in your interface, the new compiler understands this interface as a Functional Interface and allows you to pass lambda as a parameter. Java 8 support is enabled in Play 2.2.2 and Play 2.3.x!