my thoughts on programming and other nerdy stuff

April 1, 2014
by poornerd

How to implement a Session Timeout in Play Framework 2

If you fol­low the Play Frame­work 2 guide for imple­ment­ing authen­ti­ca­tion: http://​www​.playframe​work​.com/​d​o​c​u​m​e​n​t​a​t​i​o​n​/​2​.​2​.​2​/​J​a​v​a​G​u​i​de4 — you will notice that there is no ses­sion time­out in Play Frame­work 2. It was there in Play Frame­work 1, but Play Frame­work 2 fol­lows a dif­fer­ent approach.

I you want to imple­ment your own ses­sion time­out, then fol­low the guide for set­ting up authen­ti­ca­tion, by extend­ing the Security.Authenticator, and store a time­stamp in the ses­sion and keep extend­ing it every time a request is made.

Here is how I did it:

public class Secured extends Security.Authenticator {

    public static final String UNAUTHENTICATED = "unauthenticated";

    public static User getLoggedInUser() {
        if (session("userId") == null)
            return null;
        return User.findById(Long.parseLong(session("userId")));

    public static String getLoggedInUsername() {
        if (session("userId") == null)
            return null;
        return User.findById(Long.parseLong(session("userId"))).getUsername();

    public String getUsername(Http.Context ctx) {

        // see if user is logged in
        if (session("userId") == null)
            return null;

        // see if the session is expired
        String previousTick = session("userTime");
        if (previousTick != null && !previousTick.equals("")) {
            long previousT = Long.valueOf(previousTick);
            long currentT = new Date().getTime();
            long timeout = Long.valueOf(Play.application().configuration().getString("sessionTimeout")) * 1000 * 60;
            if ((currentT - previousT) > timeout) {
                // session expired
                return null;

        // update time in session
        String tickString = Long.toString(new Date().getTime());
        session("userTime", tickString);

        return User.findById(Long.parseLong(session("userId"))).getUsername();

Then just add a sessionTimeout=15 (in Min­utes) to your conf file.

If you have read this far, you may as well fol­low me on Twit­ter:

March 18, 2014
by poornerd

Examples for working with JSON in Play Framework 2 with Java

  • String to JSON
    JsonNode json = mapper.readTree(notification.getSharedData());
  • Json to Object: 
    Asset asset = mapper.readValue(a.toString(), Asset.class)
  • Json to extist­ing Object: 
    asset = mapper.readerForUpdating(asset).readValue(assetJson.toString())
  • Object to JsonString:
    mapper.writeValueAsString(new ResultDocument(document))
  • Con­vert Object ot JsonNode:
    JsonNode documentNode = mapper.convertValue(document, JsonNode.class);

    This causes an error — Caused by: com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle so do this workaround:

    String messageJson = null;
    String documentAsString = BaseApiController.mapper.writeValueAsString(document);
    JsonNode documentNode = BaseApiController.mapper.readTree(documentAsString);
If you have read this far, you may as well fol­low me on Twit­ter:

March 13, 2014
by poornerd

Configuring Play2War with Play 2.2 and build.sbt

Screen Shot 2014-03-13 at 21.07.45I had pre­vi­ously used Play2War with Play 2 projects that con­tained a Build.scala file fol­low­ing the con­fig­u­ra­tion direc­tions from Play2War. How­ever, when attempt­ing to con­fig­ure a newer project which now uses a build.sbt instead of the Build.scala, It wasn’t imme­di­ately appar­ent how to do it.

  1. Add this to your plugins.sbt: addSbtPlugin(“com.github.play2war” % “play2-war-plugin” % “1.2-beta4”)
  2. Add this to the top of your build.sbt:
     import com.github.play2war.plugin._
  3. Add this at the end of your build.sbt: (yes with the line between them, and the servlet Ver­sion you need). 
    Play2WarKeys.servletVersion := "2.5"
  4. Run “play war” and when it is done, look in the tar­get directory
If you have read this far, you may as well fol­low me on Twit­ter:

January 4, 2014
by poornerd

How to configure an SSL Certificate with Play Framework for https

sslI spent hours try­ing to get this to work, and in the end, then prob­lem was that I did not gen­er­ate the CSR (Cer­tifi­cate Request) myself with the keytool.

I kept get­ting this error when I tried access­ing Play with https:
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

The prob­lem ended up being that the key­store I cre­ated and imported the SSL cer­tifi­cate into did not have the pub­lic key that was used for the CSR (cer­tifi­cate request).

So here it the quick ver­sion of gen­er­at­ing an SSL Cer­tifi­cate with godaddy​.com and installing it with Play Frame­work 2.1+.

1. Fol­low these instruc­tions from godaddy​.com to gen­er­ate the CSR like this:
First gen­er­ate the key pair like this:

keytool -keysize 2048 -genkey -alias tomcat -keyalg RSA -keystore tomcat.keystore

Then gen­er­ate the CSR:

keytool -certreq -alias tomcat -file csr.txt -keystore tomcat.keystore

2. Use the CSR to apply for certificate

3. Add the Inter­me­di­ate Cer­tifi­cate Bun­dle and the Cer­tifi­cate that were gen­er­ated to your key­store.
NOTE: make sure this is the same key­store that you gen­er­ated the pri­vate key in, in step 1!

keytool -import -alias intermed -keystore tomcat.keystore -trustcacerts -file gd_bundle.crt
keytool -import -alias tomcat -keystore tomcat.keystore -trustcacerts -file mycert.crt

(Replace mycert.crt with the file name and loca­tion of the new GoDaddy certificate)

4. Finally, fol­low­ing the instruc­tions for con­fig­ur­ing https with Play 2.1+ ( http://​www​.playframe​work​.com/​d​o​c​u​m​e​n​t​a​t​i​o​n​/​2​.​2​.​1​/​C​o​n​f​i​g​u​r​i​n​g​H​t​tps ) which had already worked great with the self gen­er­ated key, I cre­ated a shell script for start­ing Play with the cor­rect parameters:

# script for starting play in production with SSL and the keystore
target/start -Dhttps.port=443 -Dhttps.keyStore=/Users/bp/mypath/tomcat.keystore -Dhttps.keyStorePassword=itl80809

Note: you need to do a “play dist” before­hand, so that the cur­rent Soft­ware is com­piled into a dis­tri­b­u­tion in the tar­get subdirectory.

If you have read this far, you may as well fol­low me on Twit­ter:

December 6, 2013
by poornerd
1 Comment

How to run a Play Framework Application in Tomcat or JBoss

So you have writ­ten an appli­ca­tion using Play! Frame­work 2.x and your Sys­tem Admin­is­tra­tor tells you that he won’t install Play! and that your appli­ca­tion needs to run in a sup­ported Java Servlet Con­tainer like JBoss, Tom­cat or Glassfish?

No wor­ries, you can use the play2-war-plugin to cre­ate a WAR file which can be deployed in a Java Servlet 2.5 or 2.3 spec Servlet Container!

Here is the Quick Guide for 2.1.x (mainly from stack­over­flow):

  1. Within plugins.sbt add:
    addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "1.1.1")

    Accord­ing to the project web page, you will need to pick the cor­rect Ver­sion for you Play! Frame­work version:

        Play 2.0 -> 2.0.4 : 0.8.1
        Play 2.0.5+       : 0.8.2
        Play 2.1 -> 2.1.3 : 1.0.1
        Play 2.1.4+       : 1.1.1
        Play 2.2.x        : 1.2-beta1 (unstable)
  2. Then within the Build.scala file add:
    import com.github.play2war.plugin._
    .settings(Play2WarPlugin.play2WarSettings: _*)
    .settings(Play2WarKeys.servletVersion := "X.X")

    The X.X needs to be changed to the required Java Servlet ver­sion (usu­ally 3.0 or 2.5 depend­ing on your con­tainer)

If you are using Play! Frame­work 2.2 then you can also try this method with­out the Plu­gin, just using sbt http://​play2war​.blogspot​.in.

If you have read this far, you may as well fol­low me on Twit­ter:

October 22, 2013
by poornerd

Crowd Dialog: Crowdfunding Conference 2013

Screen Shot 2013-10-22 at 15.10.12
Some of you have noticed that I have not pub­lished much recently.  In addi­tion to my day-job, I have been orga­niz­ing a Crowd Fund­ing con­fer­ence for Star­tups and Com­pa­nies that want to use Crowd­fund­ing to finance new prod­ucts.  The Crowd Dia­log Con­fer­ence is on Nov. 21 in Munich, Ger­many if you are inter­ested in coming.

If you have read this far, you may as well fol­low me on Twit­ter:

July 25, 2013
by poornerd

How to set the Java Version for Compiling a Play Framework Module

@jaliss and I were recently won­der­ing how to make sure that a mod­ule was com­piled with JSDK 1.6 after we had upgraded the Java Ver­sion on our Macbooks.

Stack­over­flow user mgre­gori just pro­vided this solu­tion (Thanks!):

In the file project/Build.scala, add the set­ting below if you want to com­pile with java 1.6 :

val main = play.Project(appName, appVersion, appDependencies).settings(
  // Force compilation in java 1.6
  javacOptions in Compile ++= Seq("-source", "1.6", "-target", "1.6")
If you have read this far, you may as well fol­low me on Twit­ter:

July 5, 2013
by poornerd

How to integrate Concordion in Play Framework and write acceptance tests in natural language

Screen Shot 2013-07-05 at 10.24.25After start­ing to read “Spec­i­fi­ca­tion by Exam­ple”, I wanted to have a go a writ­ing accep­tance tests for my Play Frame­work projects.  I stum­bled onto Con­cor­dion (http://​www​.con​cor​dion​.org/), because it is sim­i­lar to Cucum­ber but writ­ten in and for Java.

Con­cor­dion is sim­i­lar to Cucum­ber but focuses on readability.

Con­cor­dion inte­grates as Unit tests (which is the pri­mary focus of this post), and lets you write the Tests in Nat­ural Lan­guage in HTML Files so that it also becomes self documenting.

I got most of how to inte­grate Con­cor­dion from Craig Aspinall in Aus­tralia (@aspinall) who had writ­ten a Blog post about it, but which was no long “online”.   (he sent me a link to the mark­down so I could try it out — thank Craig!)

Inte­grat­ing Concordion

You first need to add the depen­dency to your Build.scala, and then add a line so that the SBT copies the Con­cor­dion HTML files:

import sbt._
import Keys._
import play.Project._

object ApplicationBuild extends Build {

    val appName         = "computer-database"
    val appVersion      = "1.0"

    val appDependencies = Seq(
       "org.concordion" % "concordion" % "1.4.2" % "test"  ,

    val main = play.Project(appName, appVersion, appDependencies).settings(
      // Next, you need to instruct SBT to copy the Concordion HTML files to the target folder
        unmanagedClasspath in Test <+= (baseDirectory) map { bd => Attributed.blank(bd / "test") }

Telling Play where to out­put the Test results to

This turned out to be a chal­lenge. If you do not set the concordion.output.dir sys­tem prop­erty, then they are out­puted to your Java temp direc­tory. Craig sug­gested set­ting it in the Build.scala, but as it turns out the most recent Ver­sion of Play forks the Tests into a sep­a­rate process and loses the set­ting. So I ended up adding this to my Global Set­tings class:

import play.Application;
import play.GlobalSettings;
public class Global extends GlobalSettings {

    public void onStart(play.Application arg0) {
        if (arg0.isTest())
            System.setProperty("concordion.output.dir", "target/test-reports/concordion");


Note: I think I dis­cov­ered another Bug in Play, because although this works, if I run “test-only” it doesn’t!!!

The Test

The key to get­ting Play to rec­og­nize and run Unit Tests is the @Test anno­ta­tion, so it seems that the eas­i­est way to get Play to run the Con­cor­dion tests is to add a method like this to your Con­cor­dion fix­ture class:

    public void runThisTest() {

I ended up imple­ment­ing one of the tuto­r­ial exam­ples from here: http://​www​.con​cor​dion​.org/​T​u​t​o​r​i​a​l​.​h​tml

You write the test case in HTML, and use <span> tags with Con­cor­dion ele­ments to spec­ify the paramters and assertions:

<html xmlns:concordion="http://www.concordion.org/2007/concordion">

        <link href="../concordion.css" rel="stylesheet" type="text/css" />


        <h1>Splitting Names</h1>

            To help personalise our mailshots we want to have the first name
            and last name of the customer. Unfortunately the customer data
            that we are supplied only contains full names.

            The system therefore attempts to break a supplied full name into
            its constituents by splitting around whitespace.

        <div class="example">


                The full name
                <span concordion:execute="#result = split(#TEXT)">John Smith</span>
                will be broken into first name
                <span concordion:assertEquals="#result.firstName">John</span>
                and last name
                <span concordion:assertEquals="#result.lastName">Smith</span>.


Then you write a fix­ture class with the Tests (and the @Test “hack” I mentioned).

import org.junit.Test;
import play.mvc.Result;

import java.util.HashMap;
import java.util.Map;

import static org.fest.assertions.Assertions.assertThat;
import static play.test.Helpers.*;

import org.concordion.integration.junit4.ConcordionRunner;
import org.junit.runner.RunWith;
import org.junit.Test;

public class ConcordianTestFixture {

    public Result split(String fullName) {
        Result result = new Result();
        String[] words = fullName.split(" ");
        result.firstName = words[0];
        result.lastName = words[1];
        return result;

    class Result {
        public String firstName;
        public String lastName;

    public void runThisTest() {

When you run the tests, then the result­ing HTML page it out­puted (as pre­vi­ously defined) to your target/test-reports directory. Here is an exam­ple of a failed test (for a suc­cess­ful one, see the image at the start of the post):

Screen Shot 2013-07-05 at 10.30.39

I hope you try this out!  Let me know if you have more ideas or tips…

If you have read this far, you may as well fol­low me on Twit­ter:

June 27, 2013
by poornerd

How to use Reflection to Document your Data Model based on JPA Annotations

annotation_reflectionSo using JPA, Hiber­nate or EBeans is cool when you can just anno­tate your Java classes, but haven’t you always wished you could “gen­er­ate” doc­u­men­ta­tion of your data model from the code? Pulling infor­ma­tion of the the JPA / Hiber­nate  and other val­i­da­tion annotations?

Assum­ing you have all those nice Anno­ta­tions in your beans:

@Table(name = "project_bills")
public class Bill extends Model {
	private static final long serialVersionUID = 1L;

	public Long id;
	public Double billAmount;
	public Date billDate;
	public String billNumber;
	public Boolean canBill;
	public String comment;
	public Date paidDate;


Here is an exam­ple of how to go about accom­plish­ing that task:

    public static String listEntities(String _package) {
        StringBuffer retval = new StringBuffer();
        Reflections reflections = new Reflections(_package, Play.application().classloader());
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);
        for (Class c : classes) {
            retval.append(c.getName() + "\n");
            retval.append(listAnnotations(c.getName()) + "\n\n");
            retval.append(listAttributes(c.getName()) + "\n\n");
        return retval.toString();

    public static String listAnnotations(String _class) {
        StringBuffer retval = new StringBuffer();
        try {
            Annotation[] annotations = Class.forName(_class).getAnnotations();
            if (annotations.length != 0) {
                for (int j = 0; j < annotations.length; j++) {
                    retval.append(annotations[j].toString() + ": " + annotations[j].annotationType() + "\n");
        } catch (ClassNotFoundException e) {
            return retval.toString();
        return retval.toString();

    public static String listAttributes(String _class) {
        StringBuffer retval2 = new StringBuffer();
        boolean perstistent = false;
        try {
            for (Field field : Class.forName(_class).getDeclaredFields()) {
                Class type = field.getType();
                String name = field.getName();
                perstistent = false;
                StringBuffer retval = new StringBuffer();
                retval.append("\t" + name + " (" + type + ")\n");
                Annotation[] annotations = field.getDeclaredAnnotations();

                if (annotations.length != 0) {
                    for (int j = 0; j < annotations.length; j++) {
                        retval.append(annotations[j].toString() + ": " + annotations[j].annotationType() + "\n");
                        if (annotations[j].toString().startsWith("@javax.persistence")) {
                            perstistent = true;
                if (perstistent) {
        } catch (ClassNotFoundException e) {
            return retval2.toString();
        return retval2.toString();

Which will gen­er­ate some­thing like this:

@javax.persistence.Table(schema=, uniqueConstraints=[], catalog=, name=project_bills): interface javax.persistence.Table
@javax.persistence.Entity(name=): interface javax.persistence.Entity

	id (class java.lang.Long)
@javax.persistence.Id(): interface javax.persistence.Id
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_ID, updatable=true, length=255, nullable=true, table=): interface javax.persistence.Column

	billAmount (class java.lang.Double)
@utils.data.formatters.Formats$DoubleFormat(): interface utils.data.formatters.Formats$DoubleFormat
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_BILL_AMOUNT, updatable=true, length=22, nullable=true, table=): interface javax.persistence.Column

	billDate (class java.util.Date)
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_BILL_DATE, updatable=true, length=255, nullable=true, table=): interface javax.persistence.Column
@play.data.format.Formats$DateTime(pattern=dd.MM.yyyy): interface play.data.format.Formats$DateTime

	billNumber (class java.lang.String)
@javax.persistence.Column(insertable=true, scale=0, unique=false, precision=0, columnDefinition=, name=PBI_BILL_NUMBER, updatable=true, length=10, nullable=true, table=): interface javax.persistence.Column

Of course this is only the tip of the ice­berg, but you get the idea.

Let me know if you have some good ideas of what other types of doc­u­men­ta­tion can be gen­er­ated from the source code.

If you have read this far, you may as well fol­low me on Twit­ter:

June 19, 2013
by poornerd
1 Comment

How to compile and use a Play Framework 2 module with the source from github

Screen Shot 2013-06-19 at 16.30.25Have you ever wanted to down­load the source of a Play Frame­work 2.0 mod­ule off of github and mod­ify the source and test it?  Or have you expected it to be in some repos­i­tory but for one rea­son or another it wasn’t there?

I have found myself in this sit­u­a­tion a few time recently and had to piece this together…

  1. Down­load the code from github (or where ever) — of course you can fork it, or check it out with git, but you can also just down­load the ZIP file
  2. Switch to the mod­ule direc­tory and run play clean , then play publish-local

Once you have done this, it is in you local repos­i­tory, so you can remove the repos­i­tory from your Build.scala if you added one.

Just remem­ber that it is in your local repos­i­tory so you will need to remove it if you want to revert back to a Ver­sion from the repos­i­tory in the internet!

If you have read this far, you may as well fol­low me on Twit­ter: