Caffeine Lab Asynchronous HTTP Client in Play Framework Published June 29, 2010

I just finished to migrate Play’s http client to Ning’s own asynchronous library. What does it mean? A lot.

When you want to retrieve data from a different server, your web application behaves like a web client. Rather than serving a resource to a client, it requests one from a different server. For example, that’s what you would do if you want to interact with the Twitter API or if you want to build a web based feed reader.

HTTP Client Calls in Play 1.0

Play has a pretty cool http client library – pretty cool in the sense that it’s very simple to use compared to what you usually get in Java. I can get the content of a resource by calling:

[java]
String body = WS.url(“http://erwan.jp/”).get().getString();
[/java]

In the same fashion, I can do a post and retrieve the JSON result:

[java]
JsonElement response = WS.url(“http://api.server.tld/new”).body(“content”).post().getJson();
[/java]

As a comparison, see how it works with Apache HttpClient.

However there’s a big flaw in this API: it can only be used synchronously. That means that your Java thread will be blocked until the response from the server is received. Depending on the server it could take several seconds, so it is a real issue. If you need to do 5 calls then work on the result, you will have to wait for the previous call to be done before you can launch the second. In Play you can use jobs to have your calls executed in a separate thread, but it’s a burder to have to create jobs for that and kind of defeats the purpose of using play.libs.WS.

Play 1.1: Introducing Asynchronous Calls

Since a commit I did last week, additional methods are available on the request object. Now you can do:

[java]
Future<HttpResponse> response = WS.url(“http://erwan.jp/”).getAsync();
[/java]

Now your call is done in a thread – you can manipulate your Future object to test if the result is available, to cancel the call or to block the thread until the result is ready. Let’s say you need to do 3 API calls, and then use the results together. With the synchronous library you have to serialize the calls, but now you can do the calls in parallel:

[java]
// Launch all three calls in parallel
Future<HttpResponse> future1 = WS.url(“http://server/api/one”).getAsync();
Future<HttpResponse> future2 = WS.url(“http://server/api/two”).getAsync();
Future<HttpResponse> future3 = WS.url(“http://server/api/three”).getAsync();
// Now that the calls are launched in separate threads, wait for the results
Document xml1 = future1.get().getXml();
Document xml2 = future2.get().getXml();
Document xml3 = future3.get().getXml();
[/java]

Launch the calls in parallel means a much quicker response, so that’s an improvement in the case we have several calls to do. But we are still blocking one of Play’s threads until the three calls are done.

Avoid blocking Play’s threads

Before we go on, it’s important to understand Play’s threads pool. It’s configurable but usually there is one IO thread and 2 execution threads. When the IO thread gets a request it passes it to one of the execution thread, the execution thread calculates it and passes it back to the IO thread that will queue it to serve it to the client who originated the request.

That means that the execution of the action on the controller will block one thread. So if you do a synchronous web service call from your action, you’ll block a precious thread for all the time you wait for the remote server to respond to your server. When all threads are blocked waiting for a result, other requests get queued. Your site’s response is slow, and your users are unhappy.

So here is how you can free the thread while you wait for the remote server to respond. The following code is an action, within a controller:

[java]
private static Future response;
public static void mirrorFeed() throws Exception {
if (request.isNew) {
response = WS.url(“http://planet.playframework.org/feed”).getAsync();
waitFor(response);
} else {
renderXml(response.get().getXml());
}
}
[/java]

This can be tricky to understand at a first glance, so here is the process.

  • Your action gets called a first time: request.isNew is true. An asynchronous HTTP call is made to the playframework.org server.
  • The “waitFor(Future)” (static method on the Controller class) tells Play to wait until the response is received.
  • When the answer is ready, Play will call the action again. This time, request.isNew is false. We know that the Future is ready so we can do a get() to retrieve the HttpResponse instance. Here we’re just serving it to the user, but you see how we could parse the feed to use just some information in our response.

So here you go: the use of an asynchronous call prevents to block an execution thread, and the performance of your application will not be affected by the response time of the remote server.

When you should still use a job

While the waitFor trick prevents you from blocking a Play thread, your user still has to wait for the web service call to be back before he gets his response. In other words, your application may feel slow to the user.

When the information you need is general enough, for example when it comes from a public feed, it can still be a better approach to keep the information up-to-date using a job. At the time the user will fetch the information it will not be the most recent, but the page will be served to the user much quicker.

This is what I am doing for the Twitter box on Planet Play: I don’t pull it for each visitor at request time (that would be insane), but I have a Job refreshing the information every 5 minutes. Any page rendered will never get anything older than 5 minutes.

[java]
@Every(“5mn”)
public class TwitterJob extends Job {
public void doJob() {
try {
TwitterSearch.refresh(“playframework”);
} catch (UnsupportedEncodingException e) {
Logger.error(“Error refreshing Twitter search”);
}
}
}
[/java]

The information is then stored in cache and retrieved to render the front page.

Read the original...

Coffee Bean Authentication and security with Play framework Published June 26, 2010

Read this post in french

Today, let's see how to add authentication and security to a web application with Play, and what the framework offers with its Secure module.
We will study the following case: we have a public website, where you can browse without being authenticated. This site also has features of administration, displayed when someone identifies as an admin. To access these features, there is a URL that allows access to an authentication form.


Play allows to write user session information in a cookie. This cookie is signed, it is not editable on the client side, but is not encrypted, so you must not send sensitive information within it (no password for example). In our example, we want to use the session cookie to know if the user is identified as an admin or not.

One of the things we want to add to the web application, if the user is an administrator, is a "Delete" link in the html table that lists our business entities (e.g a list of music albums). We could therefore use the following code:


#{if session.get("username").equals("admin")} 
<a href="@{Application.form(album.id)}"</a>
#{/if}


But we quickly face a problem : this links leads to the following pattern of URL :
/admin/delete?id=11

Even if the link is hidden, anyone can enter this URL into his browser to delete the entity of his choice. We must also protect the delete method on the server side.
Play Secure module will allow us to do this elegantly. It also offers a ready to use login form that puts the information we need in the session cookie.

Let’s see how to configure the Secure module :

Begin by modifying the /conf/application.conf file :
  • Uncomment the following line  :
    module.secure=${play.path}/modules/secure
  • Add the following line to configure routes :
    # Import Secure routes
    *      /               module:secure
  • Add admin tokens :
    # Admin tokens
    application.admin=admin
    application.adminpwd=admin

Then, declare an admin controller for all activities that we want to restrict. Add @With annotation to this controller, to tell it that it must rely on the Secure module controller :


@With(Secure.class)
public class Admin extends Controller {
....
}


Add control on the delete action, using @Check annotation :

Check("admin")
public static void delete(Long id) {
...
}


Redefine the check method by creating a new class in the controller package, inheriting from Secure.Security class :


static boolean check(String profile) {
if(profile.equals("admin"))
return session.get("username").equals("admin");
return false;
}

This code will ask the Secure module to verify that the user in the session cookie is "admin" when the annotation @Check ("admin") will be found.

In the same class, redefine the authentify method. This method is used by the Secure module, to allow the user to see a page or not.

static boolean authentify(String username, String password) {
return Play.configuration.getProperty("application.admin").equals(username)&& Play.configuration.getProperty("application.adminpwd").equals(password);
}


With this configuration, if someone tries to enter /admin/delete?id=11 URL, he will arrive directly on the authentication form, to prove that he is an administrator. And of course if the password and the user entered are not good, an error is thrown.

Now, we would like to be able to go directly to this login form, to put information about user’s identity in the user session.

Just add the following code in the controller to expose the Admin login form to /admin/login URL :

public static void login() {
Application.list();
}

There will be a control for all methods in the Admin controller. So, using the login method, the user will be forwarded to the authentication form. Then if the credentials are OK, he will return to the main page of the application (albums list in this example).

Finally, we want to allow a user identified as admin to disconnect from the application. Nothing could be simpler, just add a link to main.html template :

<body>
#{if session.get("username").equals("admin")}
<div align="right">
<a href="@{Secure.logout()}">Logout</a>
</div>
#{/if}
#{doLayout /}
</body>


That's it, now you know how to add administration and security features to a public website with Play!
Read the original...

Lunatech Research How to demo the Play framework - live coding script Published June 14, 2010

If you want someone to know how fast and straightforward it is to build a Java web application with the Play framework, then show, don't tell. The most compelling way to do this is to download Play and start coding a web application from scratch, while they watch. This article is a script for a five-minute live-coding Play demo.

This script is based on how I have seen Play's creator, Guillaume Bort, demonstrate Play to introduce it to a small audience. More or less the same demo, but with Ajax, is the video on the front page of http://www.playframework.org/. This is an especially good way of showing Play to a small group of people, if you are fairly fluent with the framework, because you can answer questions about how you do something by just writing the code and showing it working far more quickly than you would be able to with other frameworks.

Summary

  1. Download the Play framework.
  2. Create and run the application.
  3. Inspect the set-up for the default welcome page.
  4. Replace the welcome page with a trivial dynamic template.
  5. Generate a Java compilation error.
  6. Retrieve HTTP request parameters.
  7. Show message file content in the template
  8. Add the project to Eclipse.
  9. Add a JPA Entity.
  10. Add an HTML form for creating entity instances.
  11. Add a link for deleting each instance.
  12. Use a Java extensions in the view template.
  13. Add form validation.

Create and run the application

Open http://www.playframework.org/ Download the binary

There is no need to install Play as such, although you might want to add the download's directory to your PATH, so you can execute the $PLAY_HOME/play commmand directly. On my machine, though, it's just as easy to just type ~/Downloads/play-1.0.2.1/play for this kind of demo.

Execute play new tasks
~ What is the application name? tasks

A task list application is an easy example for people to understand, but it is more fun to pick an example that is more familiar and relevant to your audience, such as 'customers' or 'cocktails'.

Execute find tasks (optional) - List the generated files

It is crucial to note that Play has not generated a lot of code here; the files are minimal stubs that you will only add to, rather than a lot of generated code that you will have to delete.

Execute play run tasks - Start the Play server runtime to run the application.

Depending on what you are used to, start-up time may seem extremely short.

Open http://localhost:9000/ - Show welcome page.

The welcome page describes how the stub application works, which the next few steps show.

Start a text editor.

You could use an IDE, such as Eclipse, already at this point. However, it is useful to start with a plain text editor to make it clear that you do not have to compile the Java code yourself.

Edit conf/routes - Show the route for the GET / HTTP request.

Since Play has an HTTP focus, in incoming HTTP request is a good starting point for explaining how it works. The routes file, is therefore crucial, because this defines the (two-way) mapping between HTTP requests and Java methods.

Edit app/controllers/Application.java - Show the index() method.

Edit app/views/main.html - Show the default template: HTML 5, CSS and jQuery.

Edit app/views/Application/index.html - Show the #{welcome /} tag and replace it with <h1>Tasks</h1>.

Open http://localhost:9000/ - Show the heading.

Show dynamic data in the template

Edit app/views/Application/index.html - Change the heading to <h1>${items}</h1>.

Edit app/controllers/Application.java - Change the index() method body to the following (omitting a semi-colon).

final String items = "Things"
render(items);

Open http://localhost:9000/ - Show the Java compilation error.

Edit app/controllers/Application.java - Add the missing semi-colon.

Open http://localhost:9000/ - Show the number, and Java changes without compilation or deployment.

Edit app/controllers/Application.java - Replace the items declaration line with a String items method parameter.

Open http://localhost:9000/?items=Things

Edit app/controllers/Application.java - Undo the last change - remove the parameter and put the declaration back.

Show message file content in the template

Edit app/views/Application/index.html - Change the heading to <h1>&{'model.shipments'}</h1>.

Open http://localhost:9000/ - Show the message key being displayed, because the message is not defined.

Edit conf/messages - Add the line model.shipments = Shipments

Open http://localhost:9000/ - Show the message being displayed.

Eclipse

Execute Control+C - Show how little logging there is by default.

Execute play eclipsify tasks - Generate Eclipse project and class path configuration.

Eclipse File » Import… » Existing projects into workspace - Show project structure.

Eclipse eclipse/tasks.launch » Run » tasks - Start the Play server runtime from within Eclipse.

Open http://localhost:9000/ - Show the application running.

JPA entity

Edit app/models - create class:

@Entity
public class Task extends Model {

   public String title;
}

At this point you may need to explain that Task is a Java Bean at run-time, because Play dynamically adds getter and setter methods for the public fields, turning them into normal Java Bean properties.

Edit app/controllers/Application.java - Change the index() method body to

List tasks = Task.findAll();
render(tasks);

Edit app/views/Application/index.html - After the heading, add:

<ul>
#{list tasks, as:'task'}
   <li>${task.title}</li>
#{/list}
</ul>

Open http://localhost:9000/ - Show the JPA error.

Edit conf/application.conf - Uncomment the line # db=mem

Open http://localhost:9000/ - Show the page - no tasks.

HTML form

Edit app/views/Application/index.html - After the list, add:

#{form @add()}
<p><input name="task.title"> <input type="submit" value="Add Task"></p>
#{/form}

Edit app/controllers/Application.java - Add the method:

public static void add(final Task task) {
   task.save();
   index();
}

Open http://localhost:9000/ - Add tasks.

Edit app/views/Application/index.html - Inside the <li> add a link:

<a href="@{delete(task.id)}">delete</a>

As for forms, there is also a tag for generating links; this way just generates the URL.

Edit conf/routes - Add GET /delete Application.delete

Edit app/controllers/Application.java - Add the method, noting the id parameter:

public static void delete(final Long id) {
   Task.findById(id).delete();
   index();
}

Open http://localhost:9000/ - Delete tasks - show the link URL and query string parameter.

Java extensions

Edit app/views/Application/index.html - Change the heading to:

<h1>${tasks.size()} Task${tasks.pluralize()}</h1>

Open http://localhost:9000/ - Add/delete tasks to show singular and plural forms.

If you are lucky, at this point someone in the audience will be smart enough to point out that some plurals are not just formed by adding an 's', at which point you can change the example, and show the pluralize method with one or more parameters, e.g. ${tasks.pluralize(messages.get('task'), messages.get('tasks'))}

Form validation

Edit app/controllers/Application.java - Add the @Valid annotation to the add method's Shipment parameter, replace the first line of the method body (Task.save();) with the following.

if (validation.hasErrors()) {
   validation.keep();
}
else {
   task.save();			
}

Edit app/views/Application/index.html - before the form, add:

#{errors}
    <p style="color:red">${error}</p>
#{/errors}

Open http://localhost:9000/ - Show the validation error when submitting an empty name.

The validation error is just 'Required', but we can change this.

Edit conf/messages - Add the line validation.required = %s is a required field

Open http://localhost:9000/ - Show the new validation error.

Now we get the field name, but not as a formatted label.

Edit conf/messages - Add the line shipment.name = Shipment name

Open http://localhost:9000/ - Show the new validation error.

This lists validation errors in one place. A better way is to list the errors next to each field.

Edit app/views/Application/index.html - Replace the errors tag with:

#{ifErrors}
    <p style="color:red">Validation failed</p>
#{/ifErrors}

… and after the text input, before the closing </p> tag, add:

<strong style="color:red">#{error 'task.name' /}</strong>

Open http://localhost:9000/ - Show the new validation error.

Peter Hilton is a senior software developer at Lunatech Research.

Read the original...

Lunatech Research Play framework cheat sheet Published June 8, 2010

Now that you are getting started with the Play framework, you need a handy quick reference. Here is a Play framework cheat sheet (A4 PDF, 53 KB), with the essential commands, tags and extensions.

Cheat sheet

If you want to know why we like Play, then read about Play framework usability.

Peter Hilton is a senior software developer at Lunatech Research.

Read the original...

Nicolas' Playframework Blog What's up? Published May 16, 2010

I realize that it was a pretty long time that I haven't blogged.

So, you tell me, what's up?

First of all, our Play! talk has been accepted to JavaOne. So Guillaume and I will be speaking in the biggest Java conference ever. We will try to do our best to convert fellow Java developers to try out Play!. Once you tried it, you are addicted so our job is actually easier than other framework ;)

Second, I have just released a new module that I think is really useful (actually I hesitated to provide the functionality per default in Play! so you don't have to enable the module):

http://www.playframework.org/modules/db

In short:

* play db:export will generate a sql script to create your database based on your actual object model

* play db:import will import your database table into your domain model (so it generates java files that extends JPASupport)

It is necessary to enable the module and to configure your database connection in the application.conf file. I think that is pretty simple and that is why it is Play! "compatible".

There are plenty of options for the db:output command, but you need the latest play! version (so play! > 1.0.2.1).

The next step for this module will be to generate diff between the database and the object model automatically.

The obvious next step will then be to merge this module and the DB migrate module. David feel free to fork my module or to contact me ;)

In term of POJO generation, it would also be nice if this module could generates the CRUD controller if asked for. Another feature would be to generate the object model as scala objects.

Under the hood the module uses a modified hibernate tools (so it works with Hibernate 3.5). Hibernate tools uses freemarker to generate files, so I had to modified those as well. I will publish all the sources shortly.

As usual, please report all the bugs on http://github.com/pepite/play--database . Contribution and help are more than welcome :)

And so you know, we are working hard to make play! 1.1 the framework that will allow java developers to be the best web developers. I am currently working on a new binding mechanism where JSON is a first class citizen. More about this subject later...
Read the original...

Coffee Bean How to write a REST/XML API with Play framework Published May 14, 2010

This is the english version of my post about REST/XML and Play! framework, for the planet <3 play! community.

Today we will see how to simply expose a REST/XML (or JSON, or another format) API with the Play! framework.
URL of Play! are RESTful in essence, so it becomes very easy to create a small REST API / XML beside the Web interface of Play! application.
Let's see how to do it.

Let's take the example of a music library. Our model includes albums, artists and genres.
The Album class looks like this:
@Entity
public class Album extends Model {
public String name;
@ManyToOne
public Artist artist;
public Date releaseDate;
@Enumerated(EnumType.STRING)
public Genre
}

Genre is a simple Enum defined as:
public enum Genre {
ROCK, METAL, JAZZ, BLUES, POP, WORLD, HIP_HOP, OTHER
}

We want to define an URL that returns a list of the albums in XML for a given genre, on a GET call.
To do this we must change the routes file:

GET /website/albums/{genre}       Application.list
GET /albums/{genre} Application.listXml(format:'xml')

The first line corresponds to the HTML page (not shown in this post) that displays a list of available albums: the format is not specified, so render will be made with an HTML page.
In the second line, the parameter (format: 'xml') indicates that the render() method of the controller will look for a file named listXml.xml. The{genre} parameter will be recovered in the URL and passed to the controller.

NB : You may use only one method in the controller class for HTML and XML if you need the same number of parameters and the same treatment for both of renderings.
In this case we may add parameters to the html version later, without wanting to impact the XML rendering,
i.e. GET /albums/{genre}/{first}/{count} Application.list
So i preferred a separation of the rendering in two distinct methods.

See the code of the Application.listXml() method :
public static void listXml(String genre) {
Genre genreEnum = Genre.valueOf(genre.toString().toUpperCase());
List<Album> albums= Album.find("byGenre",genreEnum).fetch();
render(albums);
}

We're just looking for the album corresponding to the genre parameter, and we request the rendering of the list. By the way we see how using JPA with Play! is simple. The report will be made in the file corresponding to the pattern {name of the controller method} + {.xml}.
In this case it will be listXml.xml.
This template, placed in app/views directory, is defined as follows:
   
#{list albums, as:'album'}
<album>
<artist>${album.artist.name}</artist>
<name>${album.name}</name>
<release-date>${album.releaseDate.format('yyyy')}</release-date>
<genre>${album.genre.toString()}</genre>
</album>
#{/list}
</albums>

That is enough to expose our albums in XML. By following the URL pattern defined in the routes file, for example by calling http://localhost:9000/albums/rock, we obtain the following result:

<albums>
<album>
<artist>Nirvana</artist>
<name>Nevermind</name>
<release-date>1991</release-date>
<genre>ROCK</genre>
</album>
<album>
<artist>Muse</artist>
<name>Origin of Symmetry</name>
<release-date>2001</release-date>
<genre>ROCK</genre>
</album>
<album>
<artist>Muse</artist>
<name>Black Holes and Revelations</name>
<release-date>2006</release-date>
<genre>ROCK</genre>
</album>
</albums>

Now let's see how to send XML content to add albums to our music library.

We want to send the following content, using POST with application/xml content type :
<album>
<artist>Metallica</artist>
<name>Death Magnetic</name>
<release-date>2008</release-date>
<genre>METAL</genre>
</album>

We add this line to the routes file to allow POST on /album URL :

POST /album  Application.saveXml

SaveXML method retrieves the content of the request in request.body variable.
Then it parses the content to create an album and save it in the database:

public static void saveXML(){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = null;
try{
//create XML document from the request
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(request.body);
}
catch(Exception e){
}
//XML content parsing
Element albumNode = document.getDocumentElement();
//get the artist
NodeList artistNode = albumNode.getElementsByTagName("artist");
//there is only one artist element, so we take index 0
String artistName = artistNode.item(0).getTextContent();
Artist artist = new Artist(artistName);

//get the name
NodeList nameNode = albumNode.getElementsByTagName("name");
String name = nameNode.item(0).getTextContent();
Album album = new Album(name);

//get the date
NodeList dateNode = albumNode.getElementsByTagName("release-date");
String date = dateNode.item(0).getTextContent();
DateFormat dateFormat = new SimpleDateFormat("yyyy");
try{
album.releaseDate=dateFormat.parse(date);
}
catch(ParseException e){
}

//retrieve genre
NodeList genreNode = albumNode.getElementsByTagName("genre");
String genre= genreNode.item(0).getTextContent();
Genre genreEnum = Genre.valueOf(genre.toString().toUpperCase());
album.genre=genreEnum;

//save in database
album.artist=artist;
album.save();
}

NB: Of course it is possible to obtain a less verbose code by de-serializing the request object using a tool like JAXB or XStream, but this is not the subject of this post.

When you write album.artist=artist, setArtist(Artist artist) method is automatically called by Play! (code is modified on runtime).
We can confirm that the artist exists or not in the database, and determine if we should create a new instance of the artist or retrieve the existing one. The save() method of Album class persists the album in the database, and the artist if it is unknown.

public void setArtist(Artist artist){
List<artist> existingArtists = Artist.find("byName", artist.name).fetch();
if(existingArtists.size()>0){
//Artist name is unique
this.artist=existingArtists.get(0);
}
else{
this.artist=artist;
}
}

@Override
public Album save(){
if(artist.id==null)
artist.save();
return super.save();
}

Our REST API / XML allows now to list and to add albums.
You can test sending XML content with Poster plugin for Firefox or with the rest-client application.
Read the original...

Biased Objectivity Can The Play Framework Play Nice With Others? Published May 7, 2010

So you still can’t get over how fast and simple it is to develop web apps with the Play framework and you want to use it for all your future web development. In fact, you like it so much that you even want to jam it into an existing servlet-based app with thousands of lines of code, Spring configuration files, etc. But wait, the Play framework doesn’t use the Servlet API! Can you still do it?

The short answer is YES, but first, let’s take a quick look at how Play works because there are some important limitations to this chimera, and understanding the constraints will help you decide when and where to do this kind of integration. In a future post I’ll show how to make this work in a couple of different ways.

Look Ma, No Servlets!

The Play framework has conceptual differences and similarities with other Java webapp frameworks but it differs greatly from all others in one thing: it doesn’t use the Java Servlet API and therefore doesn’t run in a Servlet container. Guillaume Bort (Play’s creator and lead developer) explains his reasons for dumping Servlets here. It basically boils down to Development Speed and Scalability.

On one hand, by dropping the whole Java Servlet apparatus he was able to create an environment that detects code changes, dynamically (re)compiles source files and hot-swaps the new bytecode into the running JVM, to the point where it feels like developing in a dynamic language like Ruby or Python, while maintaining all the goodness of a compiled, type-safe language like Java or Scala. You can literally edit your code, hit reload on your browser and see the change. Compare that to the typical edit-build-deploy-restart cycle with traditional Java-based frameworks. If you don’t think that makes a difference for development you haven’t really tried it yet. To deploy it in production Play pre-compiles all the files and runs the app in an optimized, non-reloadable mode.

On the other hand, the Play framework generates stateless applications that can be easily deployed in load-balanced clusters. You can start as many Play app instances as you need and just do simple load balancing between them; no need for layer 7 juggling, server affinity, session failover, or any of that fun stuff. Web app scalability is a complex subject and I’m not suggesting that Play addresses all its challenges, but it helps you design your web tier so that it doesn’t become the bottleneck. To accomplish this it requires a mental adjustment as some concepts clash with paradigms we take for granted in a Servlet environment (i.e. storing state in the session scope). But having developed and scaled massively large web apps for the past 10 years I believe Play discourages just the right anti-patterns and pushes the correct share-nothing constructs to the dev cycle.

There is a lot more that Play does for you behind the scenes but I won’t cover all its features here. You can watch the intro video on the Play site for a quick teaser. There is no such thing as a perfect development framework but if you create web applications you should take a serious look at Play.

Play-Servlet Chimera

The scenario I described at the beginning echoes one in which I recently found myself. We have a large web application built with some plain old Servlets, some Spring MVC, JSPs, Velocity templates, a service layer, data access code, caching, etc. all glued together with a Spring application context. When we recently needed to add a new feature I really wanted to do it in Play, but I wasn’t sure if I could integrate it in a seamless way or at all.

How can you reconcile these two different and seemingly incompatible runtime environments in a single web application? The answer is, you don’t! It’s not necessary because they can both live under the same webapp without overlapping and here’s why.

Play manages the complete HTTP request-response cycle through its default Mina-based implementation (Netty and Grizzly can be installed as modules). Not only is a container not required, it is not recommended.

However, Lee Breisacher wrote a Servlet wrapper that basically encapsulates a full Play application in a standard Servlet. To try it, you can export the Play application with a single command (play war <playapp_dir> -o <war_dir>). You lose all the dynamic recompilation features of the framework this way, but it is a viable alternative for people with limited deployment options. The resulting file layout conforms to the Servlet WAR standard. All the framework files end up inside the WEB-INF directory and a standard web.xml file is generated with the minimum necessary definitions to manage the full URL space (/*). With this in mind, it was relatively straightforward to take it to the next level: complete integration.

The result is more akin to Frankenstein’s monster than I would have liked, but it works and provides a migration path for new feature development on an old application. It requires splicing the exported Play app with the existing webapp by merging the contents of their respective WEB-INF directories. In a future post I will illustrate how to do this in an automated way.

Obstacles Ahead

Although getting both apps to run together in one Servlet context is relatively easy, getting them to behave like a single, seamless application is much more challenging. The Play app doesn’t naturally have access to any of the data structures of the webapp. You’ll find you need to create a communication channel between the two camps if you want the user to be able to navigate back and forth between different sections of the app without disruption.

For a completely stateless app this is no big deal. You may need to duplicate some HTML templates and maybe find a way to share some caches to avoid having redundant, possibly inconsistent data. For stateful apps it’s a different story. You may find that traditionally simple things like sharing the logged-in user state across requests can take some developer brain power. But these are not insurmountable and once you solve them once you won’t need to solve them again.

One obvious candidate for the traffic cop role is a shared Spring application context. There’s even a Spring module for Play, but I haven’t used it yet so I can’t recommend a solution at this point.

Promising Future

So far, I’m loving the productivity I get with Play. It is still a relatively new player in the space and I’m sure I’ll encounter some bumps along the way, but the community is wonderful and the developers are very responsive. Although I initially hoped it would be easier to plug it into old code I’ve come to embrace its approach and happily accept the limitations.

I used to think that Grails was the holy grail (pun intended) of JVM-based web frameworks. It has a large, active community, tons of modules and Springsource/VMWare behind it. But after using Play I can hardly justify writing all my code in Groovy. With Play’s bytecode gymnastics even Java code in Play looks more compact than Grails’ equivalent. And I haven’t even mentioned Play’s future with the Scala module…it’s just cool. But that’s a subject for another post.


Filed under: Software Development Tagged: framework, howto, java, play, scala, servlet, webapp
Read the original...

iam.guillaume.bort.fr Why there is no servlets in Play Published April 29, 2010

Creating a Java web framework without relying on the Servlet API can seem very strange. Most people ask why this uncommon choice? Some love it, others hate it. To be honest the very first versions of the play framework were using servlets and were running in a servlet container. But there are many good reasons why we decided to remove this requirement. I’ll try to explain.

There are two important points (among many others) in play framework: it is based on a completely stateless architecture model, and it auto-magically reloads your code changes. In fact these two points are intimately imbricated.

Making an application stateless is the only way to allow code hotswapping. Have you ever wondered why it just works with PHP while it’s not possible with JEE (I mean, not redeploying the war in the background, but really hotswapping the application code)? It’s just because PHP is totally stateless; between two successive requests, it will restart a fresh PHP process (OK there are some optimizations now using FastCGI but it doesn’t change the underlying model). If your application is not stateless, there is no way to rebuild the in-memory state after the code swap. It could work on some cases, but it will likely fail after any important change.

Allowing code hot swapping is not the only reason why we decided to make of play a stateless web framework. It’s not really the point of this post, but basically, it’s just because the WEB itself uses a stateless architecture. And there are very good reasons for that.

Now, you can always use the servlet API and build a stateless application with it. However you’ll have to refrain from using some features like the HttpSession or the servlet forward mechanism. That’s what we did on the first versions of play framework.

But sincerely, people don’t want access to the servlet API because they love it. Everyone agree on the fact that it is the worse HTTP API ever conceived. No, they want to access the servlet API to be able to reuse existing servlet based components like servlet filters, etc.

The problem with these components is that they are usually poorly designed. They store objects in the session, mess with your HTTP requests and responses objects in your back. So there is a great chance that installing a component like this will break the initial stateless contract of play and lead to a lot of class reloading and class cast problems. It is also because your application has to live in a play custom classloader in order to be reloaded. And to be used the servlet components need to live in the servlet container classloader. Do you need any cooperation between these components? Of course you do. And it will be a nightmare.

In fact there are two kinds of servlet based components. I was faced to this problem when I was searching for a captcha library for play. Some use two well separated layers, one with the captcha generation logic, and the other one for the servlet API integration. The other kind is a mess of imbricated code that you can’t use without using the servlet API yourself. For the first kind you can always use them with play by using only the interesting part. For the other kind, chances are high that it would have broken your application if you were able to install them in play.

Finally there is a last reason why we don’t use the servlet API anymore. A servlet container uses an old fashioned “one thread per request” model. It can be OK for some applications. But these days with all these Ajax and long polling calls, it is not enough.

I think that the fundamental problem is that using the servlet API is the only way you can plug with the HTTP layer of a JEE server. Perhaps the java ecosystem needs something like Rack. I mean, a real low level and portable API to deal with HTTP. Not an half assed HTTP API built on some flawed architectural principles.

Read the original...

Walk the walk Create Good Looking Charts With Play, Flot and JQuery Published April 26, 2010

Oftentimes, web sites need to display different kinds of data in web charts. As always, there are a bunch of different frameworks and libraries to choose from. After some investigation I decided to try out the Flot library together with Play. Flot is an easy to use Javascript plotting library for JQuery producing nice looking [...]
Read the original...

Rob at Rojotek Executing Play! from outside of Play! code Published April 26, 2010

As I’ve said earlier, I think that the Play! framework is lovely. It makes it easy to develop and write code quickly. One of the ways that it enables this is through performing runtime byte code enhancement of the code. This makes execution of your code somewhat non-trivial when coming from a non-Play! context. Play! aims to meet all your needs, but use cases exist where it is important non-Play! code with Play! code, and have your non-Play! code call into Play!

Having said that this is non-trivial, it is reassuring to know that the process to do this is very straight forward.

  1. Create a subclass of play.Invoker.Invocation.
  2. Override the public void execute() method.
  3. Call the run() method of the invocation.
1
2
3
4
5
6
    Invoker.Invocation invocation = new Invoker.Invocation() {
        public void execute() {
            //do stuff with play here
        }
    };
    invocation.run();

With this simple snippet of code, it is possible to have non-Play! code easily and cleanly call your Play! application code.

Read the original...

iam.guillaume.bort.fr My thoughts on Scala Published April 22, 2010

Well, I’m not a Scala master. For now I’ve mostly used it to create the play’s Scala module and tested it with small applications. I had the chance to meet some more experienced people and to discuss with them about the best way to use it.

However this first experience was pretty exiting and helped me to understand what could be the future of Scala. Is Scala a complicated language to learn? Yes I think so. But it is also a Scalable Language; it was the goal of the language design and I think it is really the case: it gives some incredible power to framework creators while letting the end-developer dealing with a very simple API (a very clean DSL in most cases).

Applied to play it is the ideal use case. Even if it requires some really tricky hacks in the core of the play’s Scala module it allows to write a web application in a very expressive way;

Most of the time you can just concentrate on your application without having to deal with technical boilerplate. I guess we have already done a pretty good job on the Java API but Scala gives us more power to do that.

There is some features that really saved our life while creating the Scala module. The native singleton objects definitively remove the nightmare of dealing with static members. The package objects allowed us to keep a coherent API between Java and Scala. And of course the implicits make pimping the existing Java API a breeze.

Traits really allow to reuse and mix several concerns in your controllers. And default arguments solve one of the most problematic issues of the play’s controller API;

Of course all these new concepts can scare a Java developer. But really as a play developer you just have to use them. And I think that it is really straightforward.

Finally a simple way to start with Scala and a play application, is perhaps to just use the new ScalaTest feature that allow to write your test case in a very expressive way;

Now there are still small problems with Scala. These are not related to the language itself but to the tooling that is still pretty immature. Even though the Scala compiler is awesome it’s really slow and has some difficulties to handle incremental compilation (even if the new, currently beta, 2.8 release has done huge progress in this area), and the error reporting can sometimes be a little cryptic. 

Anyway I’m sure these problems will be solved soon when the language will gain even more interest. And then using Scala for your projects, specifically with play as application framework will really change the way you will create your next web applications.

I’m pretty sure of that.

Read the original...

Lunatech Research How to localise a Play framework web application Published April 12, 2010

This article is about web application internationalisation (internationalization, I18N) and language localisation (localization, L10N). This article shows you how to localise a Play framework web application, with an example based on the 'Yet Another Blog Engine' example application, used in the Play tutorial.

Internationalisation and localisation

There are two separate steps to perform: internationalisation and localisation. Both are mostly about text.

Internationalisation, in programming terms, is a refactoring to remove locale-specific code from the application code. In a web application, this is almost entirely about replacing user-interface text in view templates with references to messages. It also includes formatting non-text data types: dates, currency and other numbers.

Localisation is making a locale-specific version of an application. If the application is internationlised, this means having one or more selectable locale-specific versions. In a web application, this localisation is mostly about translating the user-interface text into the chosen natural language. Language selection is typically a combination of language preferences set in the web browser, and a language selection user-interface in the application itself.

In practice, the two steps go together: you both internationalise and localise one part of the application at a time.

Play framework example

The rest of this article covers how to localise the 'Yet Another Blog Engine' example application, used in the Play tutorial. The starting point is the code in the Play distribution's samples-and-tests/yabe directory. The goal is to fully internationalise the application, and add several language localisations.

To get started, see the instructions in the Play manual's Setting up i18n cookbook, which covers the basic cases. First, edit conf/application.conf and uncomment (in the default configuration file) or add a line with three supported languages:

# Localisations for English, Dutch and French.
application.langs=en,nl,fr

If you load a page in the application now, the Play console will show three warnings because you do not have any locale-specific message files yet:

16:19:04,728 WARN  ~ Messages file missing for locale en
16:19:04,729 WARN  ~ Messages file missing for locale nl
16:19:04,729 WARN  ~ Messages file missing for locale fr

UTF-8 message files

The warnings above mean that you need to replace the existing conf/messages file with one message file for each language:

  • messages.en
  • messages.nl
  • messages.fr

At this point we encounter the first improvement over the normal Java way of doing things. These files use the same syntax as Java properties files, but they are not properties files because they must use UTF-8 encoding. Java Properties, on the other hand, specifies ISO-8859-1 'Latin-1' character encoding for streaming to and from text files.

Being able to use UTF-8 message files is a big deal for language localisation, because it means that you can write localised language messages in 'plain text'. For example, this means that for a Greek localisation, instead of:

hello.morning = \u0152\u222b\u0152\u00b1\u0152\u00aa\u0152\u2211\u0152\u00ba\u0152\u2260\u0153\u00c5\u0152\u00b1
hello.informal = \u0152\u2265\u0152\u00b5\u0152\u03c0\u0152\u00b1 \u0153\u00c9\u0152\u00f8\u0153\u00d6

you can use Greek letters instead of those Unicode character escapes:

hello.morning = καλημέρα
hello.informal = γεια σου

For the rest of this tutorial, code samples will either define messages in one of these files, or show internationalised mark-up in one of the HTML view templates.

Simple messages

The simple case is a text string that does not change, and that is not interrupted by other markup. For example, the first such text in the yabe/app/views/main.html template, in the tools list:

<ul id="tools">
    <li>
        <a href="@{Admin.index()}">Log in to write something</a>
    </li>
</ul>

To internationalise this, we replace the text with a message look-up, using the &{'key'} syntax:

<ul id="tools">
    <li>
        <a href="@{Admin.index()}">&{'views.main.tools.login'}</a>
    </li>
</ul>

To add the localisations, add the corresponding line in each of the three message files. In conf/messages.en

views.main.tools.login = Log in to write something

In conf/messages.nl

views.main.tools.login = Inloggen om iets te schrijven

In conf/messages.fr

views.main.tools.login = Connectez-vous pour écrire quelque chose

The message key can be anything you like; in this example I have used a key to indicate the location views/main.html#tools

Once you have saved these changes, you can see the different language versions in your web browser by changing the setting that results in a different Accept-Language HTTP request header. In Firefox, select Preferences » Content » Languages » Choose…, add French [fr] and Dutch [nl] if they are not already in the list, change which one is at the top of the list, close the dialogue box and reload the page.

Application model localisation

If you use that link to log in to the blog's 'admin' pages, you can access lists of posts, tags, comments and users. These pages are provided by the CRUD module. For each of these pages, the title (light pink) and the column headers are terms from the application's model, i.e. JavaBean class and property names.

The CRUD module internationalises these names using the JavaBean class or property name as the message key, which means you can localise them with messages such as the following.

In conf/messages.nl

post = artikel
Post = Artikel
posts = artikelen
Posts = Artikelen
comment = reactie
Comment = Reactie
comments = reacties
Comments = Reacties
user = gebruiker
User = Gebruiker
users = gebruikers
Users = Gebruikers

In conf/messages.fr

post = article
Post = Article
posts = articles
Posts = Articles
comment = commentaire
Comment = Commentaire
comments = commentaires
Comments = Commentaires
user = utilisateur
User = Utilisateur
users = utilisateur
Users = Utilisateurs

You will notice that this does not change the rounded purple navigation links:

Those are defined views/admin.html which you can internationalise to use the same localisations simply by surrounding the existing text with &{'…'} as follows:

<a href="@{Posts.list()}">&{'Posts'}</a>
…
<a href="@{Tags.list()}">&{'Tags'}</a>
…
<a href="@{Comments.list()}">&{'Comments'}</a>
…
<a href="@{Users.list()}">&{'Users'}</a>

Parameterised messages

As well as simple messages, our application includes messages that contain a variable, such as Posts tagged with Play

To localise a message that contains a single parameter, use a Java format string to insert the parameter value in the message:

views.Application.listTagged.title = Posts tagged with %s

and in the template, add the parameter like this:

{{&\{'views.Application.listTagged.title', tag}}}

When a message contains multiple parameters, add an index to the format string to allow for different word order in another language:

views.Admin.index.welcome = Welcome %1s, <span>you have written %2s posts so far</span>

… with a list in the template:

{{&\{'views.Admin.index.welcome', user, posts.size()}}}

In this example, we would also like to use the correct plural form for the word 'post', so make that word a parameter too:

views.Admin.index.welcome = Welcome %1s, <span>you have written %2s %3s so far</span>

… and use the pluralize extension in the template

{{&\{'views.Admin.index.welcome', user, posts.size(), posts.pluralize(messages.get('post'), messages.get('posts'))}}}

Note that we have to use messages.get to look up the localised singular and plural.

Play module localisation

Play module localisation works the same was as localisation within your application. This application uses the CRUD and Secure modules, which means that we must localise the messages in play/modules/crud/conf/messages and play/modules/secure/conf/messages that our application uses.

In conf/messages.nl

# play/modules/crud (administration)
crud.title = Beheer
crud.home = Home
crud.blank = Nieuw
crud.index.title = Kies het te bewerken object 
crud.index.objectType = Type object
crud.index.action = 
crud.index.add = Voeg toe
crud.add = &{%s} toevoegen
crud.list.title = &{%s}
crud.list.size = %d &{%s}
crud.list.totalSize = %d totaal
crud.pagination.previous = « Vorige
crud.pagination.next = Volgende »
crud.pagination.last = Laatste »»
crud.pagination.first = «« Eerste
crud.show.title = &{%s} bewerken
crud.save = Opslaan
crud.saveAndContinue = Opslaan en verder bewerken
crud.cancel = Annuleren
crud.hasErrors = Corrigeer fouten a.u.b.
crud.blank.title = &{%s} toevoegen
crud.saveAndAddAnother = Opslaan en nogmaals creëren
crud.delete = &{%s} verwijderen
crud.created = &{%s} is aangemaakt
crud.saved = &{%s} is opgeslagen
crud.deleted = &{%s} is verwijderd
crud.delete.error = Kan dit object niet verwijderen
crud.search = Zoeken
crud.none = (Geen)
crud.help.required = Verplicht.
crud.help.minlength = Min. lengte is %d.
crud.help.maxlength = Max. lengte is %d.
crud.help.email = Geldig e-mailadres
crud.help.dateformat = In de vorm YYYY-MM-DD.
crud.help.numeric = Numeriek.
crud.help.min = Moet groter daan %d zijn.
crud.help.future = In de toekomst.
crud.help.past = In het verleden.
crud.help.after = Na %s.
crud.help.before = Voor %s.
crud.help.range = Tussen %d en %d

# play/modules/secure
secure.username = Uw e-mailadres:
secure.password = Uw wachtwoord:
secure.signin = Nu inloggen

In conf/messages.fr

# play/modules/crud (administration)
crud.title = Administration
crud.home = Home
crud.blank = Nouveau
crud.index.title = Choisissez l'objet à modifier 
crud.index.objectType = Type objet
crud.index.action = XXX
crud.index.add = Ajouter
crud.add = Ajouter &{%s}
crud.list.title = &{%s}
crud.list.size = %d &{%s}
crud.list.totalSize = %d total
crud.pagination.previous = « Précédent
crud.pagination.next = Suivant »
crud.pagination.last = Dernier »»
crud.pagination.first = «« Premier
crud.show.title = Modifier &{%s}
crud.save = Enregistrer
crud.saveAndContinue = Enregistrer et continuez à modifier
crud.cancel = Annuler
crud.hasErrors = Corrigez les erreurs s.v.p.
crud.blank.title = Ajouter &{%s}
crud.saveAndAddAnother = Enregistrer et ajouter un autre
crud.delete = Supprimer &{%s}
crud.created = &{%s} a été crée
crud.saved = &{%s} est enregistré
crud.deleted = &{%s} est supprimé
crud.delete.error = Ne peut pas supprimer l’objet
crud.search = Chercher
crud.none = (aucun)
crud.help.required = Obligatoire.
crud.help.minlength = Longeur minimum est %d.
crud.help.maxlength = Longeur maximum est %d.
crud.help.email = Adresse e-mail valide
crud.help.dateformat = En format YYYY-MM-DD.
crud.help.numeric = Numerique.
crud.help.min = Doit être plus grand que %d.
crud.help.future = Dans le futur.
crud.help.past = Dans le passé.
crud.help.after = Après %s.
crud.help.before = Avant %s.
crud.help.range = Entre %d et %d

# play/modules/secure
secure.username = Votre adresse e-mail:
secure.password = Votre mot de passe:
secure.signin = Connectez-vous maintenant

Of course, once you have done this it is also a good idea to contribute the localisations back to the module.

Special cases compared to JavaServer Faces (JSF)

In 2008 I was localising an application that was built using Seam 2 and JavaServer Faces (JSF) 1.2. There turned out to have three special cases that were awkward to implement in JSF, which I reported as javaserverfaces-spec-public issue 517.

  1. Parameterised message used in an attribute value
  2. Formatted message parameter
  3. Link within message

All three cases turn out to be straightforward in Play.

The first case happens when you want to use a phrase with a parameter in an attribute value in the template, such as:

<a href="@\{Application.show(_post.id)}" title="By Bob">

This is a problem in JSF, because you would normally use an XML tag to perform the parameter replacement, which you cannot do in an attribute value. The Play syntax simply avoids this problem, and you can just do:

<a href="@\{Application.show(_post.id)}" title="&{'views.tags.display.author', _post.author.fullname}">

The second case is when you want to format a value, such as a date, for use as a message parameter in a phrase like By Bob on 2009-06-14. Again, the problem in JSF is caused by having to an XML tag to format the value, while needing to be able to use the result in an XML attribute value. In Play the formatting extensions do not get in the way of the message parameter syntax, so you can do:

<span>&{'views.tags.display.author', _post.author.fullname, comment.postedAt.format('yyyy-MM-dd')}"}</span>

You can, of course, localise the format pattern as well:

<span>&{'views.tags.display.author', _post.author.fullname, comment.postedAt.format(messages.get('views.dateFormat'))}"}</span>

The third case typically occurs when you want part of a localised message to be a hyperlink, as in the message Log in to write something. This is a problem in JSF because the hyperlink is a JSF component that is rendered in a way that means the link's mark-up cannot be in the message file. Play on the other hand, lets you use plain HTML in your templates, so you can just put the mark-up in your message with a parameter for the URL:

logIn = <a href="%s">Log in</a> to write something
&{'logIn', '/admin'}

Our application was using the <a href="@{Admin.index()}"> syntax in the hyperlink to get the framework to generate the URL based on the routes file. To do this in the message parameter, do:

&{'logIn', actionBridge.Admin.index()}

The localised 'Yet Another Blog Engine' example

The end result of applying the above steps is a localised version of the 'Yet Another Blog Engine' example that works in English, Dutch and French: yabe-l10n-1.0.2.zip

The 'Yet Another Blog Engine' admin interface in Dutch (above) and French (below).

Peter Hilton is a senior software developer at Lunatech Research.

Read the original...

Rob at Rojotek Eleven reasons to use the Play! Framework for Java Web Development Published April 10, 2010

The Play! Framework is a great tool for rapidly building Java web applications. Play! takes many of the ideas from the dynamic languages world (Rails and Django), and provides them to Java web development. Reasons to conside Play! for Java Development are:

  1. Rapid development via a local development server that automatically compiles your java code for you. It’s amazing how good it is to develop like this, and what a difference the rapid feedback loop makes.
  2. A good clean MVC famework.
  3. Nice testing support baked in.
  4. A useful routing table to make clean urls easy to work with.
  5. A focus around REST, but no slavish observence of it.
  6. built-in simple JSON support.
  7. A good module framework with useful modules including a “CRUD” module, and a Scala module currently under development
  8. An interesting mix of Java class enhancement that makes it easy to work with code, and then have the enhancer provide some of the hard work for ensuring that multiple threads are handled well.
  9. Deployment to a range of platforms, including JEE Servlets (Play! 1.0.2 has been tested on containers such as tomcat, jetty, JBoss and IBM WebSphere Portal 6.1), and the GAE.
  10. Enhancements to the JPA which make it really easy to work with.
  11. An active and supportive community. There is the right balance between having strong opinions about the “Play!” way of doing things, and helping people to get things done.

Play! makes Java web development fun and productive. The feedback loop is really quick, and much of the boilerplate code is removed. It’s well worth considering for any application you want to write in Java.

Take a look at the video, and work through the tutorial to get a feel for what development with Play! is like.

Read the original...

iam.guillaume.bort.fr A simple hit counter implemented with Software Transactional... Published April 9, 2010



A simple hit counter implemented with Software Transactional Memory (STM), using the akka module for The Play! framework.

Read the original...

iam.guillaume.bort.fr "There should be no business logic in a controller. Read that again. There should be no business..." Published April 6, 2010

“There should be no business logic in a controller. Read that again. There should be no business logic in a controller.”

- Josh Symands; Same apply for play 
Read the original...

iam.guillaume.bort.fr play 1.0.2 released — what's next? Published April 6, 2010

Since we released play 1.0 in october 2009, there was a lot of interest about it. It has been downloaded almost 70,000 times in only 5 months and the community has grown to several hundred of users. More importantly, the users feedback has been awesome; we almost have only positive reactions.

Today I’m pleased to announce the release of play 1.0.2 - This version is a maintenance release of the play 1.0 serie. It should be the latest important release of this serie. The now large community gave us a lot of feedback that allowed us to build this rock solid final version.

Now it’s time to concentrate our efforts working on play 1.1 that we hope to release this summer. So what’s new for this version? First, it’s really important for me that everyone understand that play framework is not only about technology but about simplicity and usability too. That’s why people love play framework: because it just works, it has a steep learning curve, and it doesn’t try to over abstract and complicate things.

So simplicity and usability are still the focus for play 1.1. I want to keep a light and rock solid core framework component and let the community build features around it: the main work for play 1.1 will be internal refactoring to allow even better modularity. Among these ones, play 1.1 will come with new languages support, new rendering types and better support for non-JPA based persistence engines.

But now it’s time to play with the 1.0.2 release; stay tuned!

Read the original...

Hugo Monteiro Deploying PlayFramework Apps in JBoss Published April 1, 2010

After you created your web application you need to create the WAR file that will insert the framework and other dependent libs inside the folder that you specify:

play war myapp -o myapp.war

Now to deploy on JBoss, you need to do some changes on your WAR file:

  • Create a file called jboss-web.xml in the myapp.war/WEB-INF/ directory container the following:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 2.4//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_4_0.dtd">



com.example:archive=myapp.war
java2ParentDelegation=false



  • Download hibernate-validator and hibernate annotation using the compatibility matrix (Hibernate Compatibility Matrix). Play is using hibernate core 3.3.2 GA. Once you are done, place the relevant jars in the myapp.war/WEB-INF/lib directory. You should end up with:
    • hibernate-annotations.jar
    • hibernate-entitymanager.jar
    • hibernate-validator.jar
    • hibernate-commons-annotations.jar
    • hibernate-search-3.1.1.GA.jar
    • hibernate3.jar (Do not overwrite this library, as Play! has a modified version of it)
  • Now that we’re prepared for WAR, you need to move your application to the deployment folder of JBoss. The default folder for it is: jboss_home/server/default/deploy (jboss_home == folder of jboss). There are some things you need to be aware of:

    1. Use a superior java version in JBoss to avoid class version errors
    2. Verify that the WAR folder has the necessary permissions. In my case I needed to make a “chown -R jboss myapp.war” where jboss is the user that controls the jboss application server
    3. Do a “tail -f jboss_home/server/default/log/server.log” to see if your application is being deployed. You’ve an Administration Console in http://yourserverip:8080
    4. Don’t change your routes file at runtime. Stop the war, change routes and then start the war (in the administration console I said before)
  • Now you should have your application working. You can access to your app at: http://yourserverip:8080/myapp.war
  • This tutorial was tested in JBoss 5.0.1

Thanks to Nicolas Leroux from lunatech.com for helping me to create this tutorial.

Read the original...

Lunatech Research Plan Cruncher - Play! in production Published March 29, 2010

At Lunatech, we recently decided to build a small web application to implement one of our ideas for generating business plan summaries. We needed to get this running on-line as quickly as possible, with minimal time spent coding, so we chose to build it using the Play! framework. The result was fast development, clean code, easy deployment and an instantly popular web application - http://plancruncher.com/.

Plan Cruncher is born

On 11 February, I presented an idea for ‘Business plan symbology’ at the Lean Start-up event organised by Lunatech Ventures. Basically, the idea is that if you choose a few standard icons that apply to your start-up idea, then you can put together a standard one-page summary of your business plan, with standard text, that avoids the length of normal business plans.

We had a great discussion about the idea, and got lots of positive feedback, including Invold.com and turtlethink.com blog posts, so we decided to do the lean and agile thing, and get the idea on-line. This meant that we needed to code a simple web application that would allow people to select some icons, and generate and e-mail a PDF of the business plan summary.

Play! framework

This is the kind of thing that PHP is ideal for - hacking-together a quick web application. PHP is not our thing though, because of the mess you inevitably end up with, which is one of the reasons why we prefer to use Java. However, while we normally work with the Java Enterprise Edition platform, that would be far too big a sledgehammer for this kind of small web application. We just want all of those Java libraries to be available in case we need them.

The new Java web application framework in the ‘best of both worlds’ category is the Play! framework, which massively simplifies much of the unnecessary complexity that has accumulated among Java EE development conventions. Like PHP, Play! is by and for web developers, bringing a different set of values to the kind of framework favoured by the heavy-weight Java EE community.

In particular, Play! was ideal for this project, because of the development speed you get from its edit-save-reload page development cycle (no build or deployment steps required), the cleanness and brevity of the code you end up writing (no code-generation), and the ease of integrating things like the Play! PDF module. We also wanted it to be easy to push new changes to the live application on a daily basis without interrupting users, because we were going to release-early, with a new idea that we were still thinking about.

plancruncher.com

Everything worked out beautifully: despite me being on holiday for a week, and Nicolas having other work to do, we had Plan Cruncher in production at http://plancruncher.com/ within a couple of weeks, after spending about two days each on design, coding and testing. It was fun as well.

plancruncher.com

After the first release, we released a new version every day for a week or so, to incorporate initial user feedback, as #plancruncher started to find its way around Twitter. Doing this with a stateful web application is a problem, especially if the application server takes a long time to redeploy the application.

We had no such problem with Play! because we set-up two instances of the application, and configured Apache load balancing to switch to the second instance if the first is not available. Since a Play! web application is stateless, you can use this to release a new version, without users noticing the switch from one instance to the next. What’s more, we can deploy a new version of Plan Cruncher (on both instances) in about ten seconds, because Play! application start-up is so fast. Upgrading your Play! applications without downtime explains how this works.

What’s next

Who knows where Plan Cruncher will go from here, but some further development is inevitable. Big projects often start out with a small application like this, which is another reason why we are glad we did not start with PHP.

We are certainly considering localisation, after attention from blogs in the US, Russia, Germany, Italy, Latvia and Japan.

We also have (a long list of) other ideas for lightweight web applications like Plan Cruncher, and it is good to know that we have a platform that offers us rapid development and results in a small amount of clean code. Of course, these are advantages that large applications can also benefit from.

Peter Hilton is a senior software developer at Lunatech Research.

Read the original...

Walk the walk Creating an Admin Application with Play Published March 23, 2010

I’ve been looking quite a lot at the Play framework recently and I really like everything about it. It is easy to use, the development cycle is awesome and the modules make it really easy to bring new new functionality into the application. But so far I’ve only used it for pet projects. So I [...]
Read the original...

Lunatech Research Upgrading Play! applications without downtime Published March 22, 2010

You have your Play! application deployed on production. It is a real success and you have loads of users. You are really happy, and because Play! is quite fast you do not have any performance issues yet :) However, you are receiving feature requests. Being agile developers, you implement them quickly, test them in acceptance and you are ready to let your users enjoy them. But, your web applications is so successful that you do not really want to plan any downtime…

Tough choice: new features to keep your users happy or 100 per cent uptime? Well it is quite simple to do both using Play! This is because Play! is fully stateless.

My Play! web applications always use a front end proxy. Apache being the most popular I will illustrate how to do it with this web server. The basic idea is to run two Play! instances of your web application and let the front-end proxy load-balance them. In case one is not available, it will forward all the requests to the available one.

Let's start our the same Play! application, deployed two times: one on port 9999 and one on port 9998.

What I actually did is to copy the my application two times and to edit the application.conf in the conf directory to change the port numbers.

For each web application directory:

play start mysuperwebapp

Now, let's configure our Apache web server to have a load balancer.

In Apache, I have the following configuration:

<VirtualHost mysuperwebapp.com:80>
  ServerName mysuperwebapp.com

  <Location /balancer-manager>
    SetHandler balancer-manager

    Order Deny,Allow
    Deny from all
    Allow from .mysuperwebapp.com
  </Location>

  <Proxy balancer://mycluster>
    BalancerMember http://localhost:9999
    BalancerMember http://localhost:9998 status=+H
  </Proxy>

  <Proxy *>
    Order Allow,Deny
    Allow From All
  </Proxy>

  ProxyPreserveHost On
  ProxyPass /balancer-manager !
  ProxyPass / balancer://mycluster/
  ProxyPassReverse / http://localhost:9999/
  ProxyPassReverse / http://localhost:9998/
</VirtualHost>

The important part is balancer://mycluster. This declares a load balancer. The +H option means that the second Play! application is on stand-by. It will take over if the first one fails. This is exactly what I want.

Every time I want to upgrade mysuperwebapp, here what I am doing:

play stop mysuperwebapp1

The load-balancer then forwards everything to mysuperwebapp2. In the meantime I update mysuperwebapp1. Once I am done:

play start mysuperwebapp1

And I can now safely update mysuperwebapp2 the same way.

Apache also provides a way to view the status of your cluster. Simply point your browser to /balancer-manager to view the current status of your clusters.

Because Play! is completely stateless you do not have to manage sessions between the two clusters. You can actually easily scale to more than two Play! instances. As we have seen, that is really easy to do.

Happy Play!

This article was originally published on playframework.blogspot.com.

Read the original...