It may sound like an obvious point, but until recently the major reason I had for setting my applications to use PROD mode when I move my applications to a production environment, was so that my source code would not be visible in the event of a server side error. However, whilst looking through the source code today, I found a major compelling reason to never use Dev mode in a production environment.

First of all though, here a few things that Play does when you move into production mode that makes it a good idea to use the setting.

  • Play precompiles your source code for you, and does not check for code changes on the fly, adding a slight performance benefit
  • Play starts the application immediately (including any bootstrap jobs), rather than waiting for the first request, again adding a small performance benefit for first use
  • The 500 (server error) and 404 (page not found) pages do not show source code or your routes configuration, but instead show a standard error page
  • Runs more HTTP threads to handle incoming requests (unless specifically set in the application.conf). The exact value set is number of processors + 1

So all sounds pretty sensible, but not entirely critical. So, here is why it is critical.

/@kill

Just like the @tests and @documentation URLs that can be used in Play, there is a largely unknown URL called @kill. As the name suggests, it simply performs a System.exit(0), which shuts down the Play server. The code first checks that the system is in Dev mode, and if it is, and the @kill request was received, the server is killed.

You will also get a nice output message printed to the logs @KILLED. Not exactly what you want your average user to be able to do on your shiny new application. Not that your average user will know that this feature exists, but it is better to be safe than sorry.

I assume that this facility has been made available, so that if you are running your application in a development set up, you can terminate the application remotely directly from the browser, without having to worry about accessing the server that it is running on. I can’t really think of any other good reasons why you would want to use this feature over simply terminating the command line or using the play stop command.

If you want to try it, just go to http://localhost:9000/@kill (assuming you have not changed your port, and you are running your play server locally in Dev mode).

So stick to PROD mode. Not only is it a better way to run your applications, it protects you from unwarranted server shut downs.

Play Modules

Posted: February 27, 2011 in Play Framework

Introduction
I have been asked a few times since writing the Play Framework book about how modules fit into the Play Framework. I didn’t think it made sense to add modules into the first edition, as it was intended as an introduction, so I thought I would add a blog here instead.

Before we being, let first understand what we mean by a play module.

What is a module
A module in play is actually little more than an organisation of your code base. The structure of a play module is very much the same as a standard play application. You will see an app directory (with the normal controllers, views and models), you will see also a conf directory (without an application.conf) and finally a src folder. There is no application.conf as a module will conform to the configuration set out by the application that includes this module.

Note that when your module is running inside an application it has access to all of the applications properties, as if your module was directly inside the application itself.

Why use modules
The idea behind using modules is re-usability and separation. Imagine a scenario where you are building a web application that consists of several discrete pieces of functionality, such as an online Office suite, you may create a set of modules as follows:

  • Core Application
  • Authentication
  • Word processing
  • Presentations
  • Spreadsheets
  • etc

The core application would be your main application that tied all the modules together, and the authentication, word processing, presentations and spreadsheets would each be an individual module.

You could even distribute these modules to different teams to work on.

But I am not going to write an Office clone!
Okay, but the theory transfer to much smaller modules. You modules really could be any discrete piece of functionality, such as admin functions, authentication, dashboards. Anything! Its all about clean separation of concerns and re-usability. Your authentication module could be lifted to your next application with no more effort than simply dropping the directory structure and adding a line in your application.conf.

Creating a Module
Lets take the idea of having a project that has some authentication requirements that we want to split into a new module.

First we will create our main application.

play new core-app

Next we will create our module

play new-module auth

To include our module into our core application, we simply update the application.conf and add a module in the same way we would add a community module.

module.auth=D:\playframework\my-apps\auth

So, the path is module.=

And that is it, your module will be available. But there is nothing in it yet.

What do I put in my Module
Well this is really up to you. For the purposes of our module, the most obvious things to add to our module would be a User model class, an Authenticate controller containing methods for registration, login, and checking authority, and finally views to go with the registration and login actions.

We won’t go into how to build these, because you can quite simply use the Secure module already available in Play for most of this stuff. It simply serves as a nice example of how to separate out some clearly de-marked functionality.

What can’t I do in a module?
Not a lot really. Remember, a module is very much a play application, but just does not have an application.conf, so can’t be run directly. As soon as it is attached to a play application, it can do anything a play application can do, without exception.

What about the PlayPlugin and src folders?
Right at the beginning we mentioned a src folder. In that folder there is also a play.plugins file.

Firstly, the /src directory is compiled when the module is built using the build-module command. The idea, of this directory is for utility classes that don’t have anything to do with Play. .

When the module is built, the contents of the src folder is compiled into a jar file ready for distribution.

Play Plugins are another entirely different topic, which are designed to modify how the Play Framework functions. A great example of this is the DocViewerPlugin which comes bundled into Play. The module simple adds a number of routes to your routes file (if in DEV mode), that allows you to see the core play framework documentation by using the URL /@documentation. The play.plugins file specifies the order of invocation of the play plugins.

My new module is amazing, how do I share it?
Use the build-module command to build a distribution of your module. Announce your module on Google Groups and Guillaume or one of the Play team will give you access to the module repository. You will need to provide an OpenID as well. Once you have access, you can specify the description of your module, and share your module via GitHub or another repository.

You should also add some documentation about your project to /documentation/manual/home.textile.


The eBook – “Introducing the Play Framework” will shortly be coming out of beta. The good news is that there have been no changes to the content as a result of the beta phase, so for all who bought the beta, your faith was well placed!

Also, I would like to thank everyone for the very encouraging feedback. If anyone would like to add a comment to be published in the final release, just drop me an email.

Once the book comes out of beta, it will probably go up by a few pounds, so if anyone wants to save a little, get in quick!

Enjoy.


A few days ago I released the Beta version of my new book “Introducing the Play Framework”.
To read more about the eBook, and to purchase, just visit the link

http://www.the-play-book.co.uk

Happy New Year and happy reading!

FastTags in Play

Posted: November 26, 2010 in Play Framework

Recently in the Play user groups, and on StackOverflow, there have been a number of questions regarding FastTags in Play. Having answered the question on StackOverflow, I thought I would add a post here, to show Fast Tags in action, because they are

  1. Very Simple to implement
  2. Very powerful tools

So what are FastTags

So let’s start with the basics. What exactly are FastTags?

If you read the online documentation, you will already have been introduced to the concept of creating your own tags. These tags are effectively Groovy/HTML code snippets that can pass named parameters  into the snippet to perform a re-usable piece of code. An example of a Groovy Tag (straight from the online docs):

To create a hello world tag, the tag code would be created in the app/views/tags directory, and named <tagname>.html. So a hello tag would be called hello.html. The tag code would look like this:

Hello ${_name} !

And we would use the tag in our views, like this:

#{hello name:'Bob' /}

Which when we run our view, we would see the output:

Hello Bob !

A very simply Hello World example. However, there is another way to create this tag, and that is where Fast Tags come in.

But Why Bother? What’s wrong with Groovy Tags?

Okay, so good question. And the answer is, it depends on the scenario. Groovy tags are great for taking repetitive or re-usable code out of a view, and making it a re-usable component. It allows great re-use at the view layer. But it is limited to HTML/Groovy code or the use of the script tag. Just like JavaExtensions give you the ability to take complex logic and abstract it out of the presentation layer, the FastTags give you the same power.

All of the tags that you are already using within Play are written using FastTags (see the source on github), so there is already a good set of examples for you to work with.

Well Show Me Then!
Okay, let’s once again see what we need to do to get a Hello World tag working.

A fast tag library needs to extend FastTags, and can have  a number of different tags contained in each class. The class can exist anywhere in the package structure, but I would suggest storing it app/tags as a neat place to keep them.

So, lets assume our tag library will be called MyFastTags

package tags;

import groovy.lang.Closure;
import play.templates.*;
import play.templates.GroovyTemplate.ExecutableTemplate;
import java.util.*;
import java.io.PrintWriter;

@FastTags.Namespace("mytags")
public class MyFastTag extends play.templates.FastTags {
   public static void _hello (Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
      out.println("Hello " + args.get("name").toString() + " !");
   }
}

So, there are a few things that are happening in this code. First of all we have set the package structure according to the directory we saved out tag to (app/tags).
We then import a list of packages needed for the FastTag to work.
Next, we have specified a namespace for the tag. This helps prevent conflicts, between different tag packages.
We then specify the class name, and extend FastTags (which is a must for the Play framework to pick this up as a tag).
The next 3 lines of code is the content of our tag. The method name _hello tells Play that our tag is name hello. The underscore is a required Play style that must be followed for your tag to work.
Our tag itself is very basic in this example. We are simply getting the variable name that is passed in, and output a String with the name inside the String.

To use our tag in the code, because we have used a namespace, we access the tag in a slightly different way. We use

#{mytags.hello name:'Bob' /}

The output is then identical to the hello world tag that we used previously.

You can imagine though that this approach could result in very powerful, re-usable tags that could significantly reduce presentation coding and rework. A good example that was released a few days ago was the JQValidate module. The module is a single FastTag with a few tags contained within it that allowed, form validation to be carried out client side, using the server side annotations of the Model. Doing this kind of tag in Groovy (without a lot of scripting, which is bad practice) would be impossible.

Try it out for yourself, and see what you can do! Whilst I don’t believe FastTags are the answer to all your tagging needs, because Groovy tags are perfect for purely presentation layer type tasks, FastTags open up another area of flexible development and will no-doubt make your development easier, especially as you (and the community) build up libraries of re-usable FastTags.

Web Services using Play!

Posted: August 15, 2010 in Play Framework

A reasonably undocumented feature of Play is the ease in which Web Services can be integrated into your application. This quick blog will show you how easy it is to create a Play Web Application to do a currency conversion calculation, using Live currency rates between some popular currencies.If you have not already done so, download the latest version of Play from http://www.playframework.org.

Open your command prompt at the directory where you have unzipped and type.

play new currency

Follow the on-screen prompts to set up your new application.
Next start the server by typing

play run currency

Now, open the file currency/app/views/Application/index.html.
In this page we want to have two drop down lists with common currencies to select, and a value field. Change the code so that it looks like the following.

#{extends 'main.html' /}
#{set title:'Home' /}

<h1>Play! Currency Converter</h1>
<form action="@{Application.convert()}" method="POST">
    Currency From:
	<select name="from">
		<option value="USD">USD - US Dollar</option>
		<option value="GBP">GBP - UK Pound Sterling</option>
		<option value="EUR">EUR - Euro</option>
	</select><br />
    Currency To:
	<select name="to">
		<option value="USD">USD - US Dollar</option>
		<option value="GBP">GBP - UK Pound Sterling</option>
		<option value="EUR">EUR - Euro</option>
	</select><br />
	Amount: <input type="text" name="amount" /> <br />

	<input type="submit" name="conv" value="Convert" />
</form>

This code is fairly straightforward HTML. The only Play feature in the code is the form action which points to a Play action (which we will create next), using the @{Application.convert()} code.

Next, we need to open the app/controllers/Application.java.
We need to add the convert action to send our form data to. The file should look like this.

package controllers;

import play.mvc.*;
import play.libs.*;
import org.w3c.dom.Document;

public class Application extends Controller {
	
    public static void convert(String from, String to, Float amount) {
		
        String wsReq = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
					  "<soap12:Body><ConversionRate xmlns=\"http://www.webserviceX.NET/\">" +
                      "<FromCurrency>"+from+"</FromCurrency>" +
                      "<ToCurrency>"+to+"</ToCurrency>"+
					  "</ConversionRate></soap12:Body></soap12:Envelope>";
					  
		Document doc = WS.url("http://www.webservicex.net/CurrencyConvertor.asmx").setHeader("Content-Type", "application/soap+xml").body(wsReq).post().getXml();
		String rate = doc.getElementsByTagName("ConversionRateResult").item(0).getTextContent();
		
		Float total = amount * Float.parseFloat(rate);
		render(from, to, amount, rate, total);
	}

    public static void index() {
        render();
    }
}

The main piece of code we are concerned about is the convert method. This method is called when the form is submitted (courtesy of the @{Application.convert()} code in the index.html page).
The method takes 3 parameters, which Play automatically maps from the HTTP parameters sent by the form, so we have the values present immediately when the method is created.

The first thing we do in the method (Play calls these methods actions, so we will do the same from now on), is to create the XML for the soap request. The XML is a reasonably simple SOAP request containing the envelope and body, and the currency symbols we want to convert from and to.

Next, is the WebService part of Play. To use web services in Play, we need to use the play.libs.WS class. Let’s take a closer look at the Web Service call.

Document doc = WS.url("http://www.webservicex.net/CurrencyConvertor.asmx").setHeader("Content-Type", "application/soap+xml").body(wsReq).post().getXml();

The first part of the request specifies the URL that we want to connect to. Here I am using a free sample webservice for live currencies. The second part adds a header to the request. For the request to work, the request needs to specify that the content is soap-xml, which is why the header needs to be added. The third part sets the body of the request to the SOAP xml we created at the start of the action, and the final part sends the SOAP request using the post method.
The final part (getXml()) returns the response as a Document object, ready for parsing.

The rest of the convert action simply gets the result from the returned XML, and calculates the total amount converted from the amount to convert multiplied by the exchange rate returned from the web service. All of the values (including the ones submitted by the form) are then passed through to the HTML page, so that they can be rendered, by calling the render method.

Finally, we need to output the results of the conversion. So let’s create a new file called app/views/Application/convert.html, and add the following code.

#{extends 'main.html' /}
#{set title:'Converted' /}

<h1>Total ${to} ${total}</h1>
Converted ${amount} ${from} to ${to} at an exchange rate of ${rate}

We can now try out our application. Go to http://localhost:9000 and you will see a page like this.

If we choose USD and GBP and set an amount, then click convert, we should see the results similar to the following.

To achieve this result, our code called an external web service to look up the Live exchange rate between these two currencies, and then used the results in our controller to perform the necessary calculations to display the results on the screen.

How cool is that! A currency conversion application, using real LIVE currency rates, written in less than 50 lines of code.