Play Framework 2.1 Architecture

Play 2 is completely different from the previous versions. When the team decided to change the framework I was frustrated just like the rest of the community.. “why would they change something so good” everyone was wondering! Anyway, I decided to follow the new version as I thought they would have a good reason for this radical change, and they did.

Asynchronous Web
Play 1.x  was following the steps of django and rails, too many request serving them as fast as possible. It was working on the assumption that all request will be short (just asking for some data, or sending a form) and for more time consuming requests a scheduled job could be used. The new architecture is based on the actor model, powered by akka. Actors are lightweight entities that processes messages asynchronously. In the new Play every request is considered to be a long lasting one and it seems that the best way to handle persistent connections is the event model.

Architecture Overview
Play 2.x still uses the MVC pattern. There is a Controller that handles the incoming request with the help of the Model and the View it will build and return the response. Model is of course the domain model with the data and logic and the View is the templating system that can be fed with model data to produce the response. What’s interesting about the Model is that it is completely agnostic of the view layer, well, after all that’s the point of mvc.

Just like the previous version Play 2.x comes with an embedded HTTP server which specifically is the jBoss Netty and it’s non-blocking IO server.  Netty is integrated into the framework and it’s completely transparent. The benefits of integrating a nonblocking IO server is that the framework provides an HTTP API that supports out of the box asynchronous web programming.  When an http request comes in Netty will handle it and forward the data to play framework, the framework will processes the data and generate some response which Netty will deliver back to the client.

Incoming Request
The following image illustrates how play handles the normal requests. A client makes a request for a resource in this example the request is the following After the domain name follows the route which is mapped to an Action in this case it is mapped to the remove action in a Controller class. The Controller has access to the model class and its methods and performs a delete on the data. The model synchronises with the database and returns back to the controller the status of the deletion (success or fail). The controller then renders the view and sends the Response to the client.


Incoming Request Asynchronous Action
The following image illustrates how play handles requests in an asynchronous way. A client makes a request for a resource in this example the request is the following After the domain name follows the route which is mapped to an Action in this case it is mapped to the remove action in a Controller class. So far nothing has changes from the previous method. The Controller has access to the model class and its methods and performs a delete on the data but in this case the operation last longer because a lot of business rules need to be checked before deletion. To avoid blocking the Controller sends back to the client a Future[Result] and it moves on with other possible requests. At this stage the client is waiting for the actual response. The model method completes and synchronises the state with the database and returns back to the controller the status of the deletion (success or fail). The controller then renders the view and sends the Response to the client fulfilling the future results.

You can learn a lot more about play framework at


Getting started with Scala

This is a list of Scala resources to get started and beyond.

1. Setting up the environment (installation guides):
* if you just want to experiment with scala there is no need to setup anything, you can use an online interactive interpreter like and

Mac OS X guide
Windows 7 guide
Ubuntu guide

2. Editors and IDEs
There are plugins for all major IDEs:

Scala IDE for eclipse
Scala plugin for NetBeans
Scala Plugin for InteliJ IDEA

Syntax highlighting plugins are available for jEdit, Notepad++, TextMate, TextWrangler etc.

3. Online Free Resources
Scala School @ twitter: this is a tutorial for beginners.
There is a free course at coursera: Functional Programming Principles in Scala don’t miss it but I suggest that you go through the basics first.

4. Scala and Functional Programming Books
– Scala
Programming in Scala 2nd Edition (I really liked this book, but one of my colleagues found it a little to academic and moved on to the next book)
Scala for the Impatient
Scala in Depth
Scala in Action
Testing in Scala (if you are serious about Scala this book is a must)

-Functional Programming
Functional Programming in Scala (I included this book here because it’s mainly about functional programming and less about Scala, it’s a five star recommendation though)
Purely Functional Data Structures (More theoretical and all examples are in ML and Haskel but it’s easy to translate them to Scala)
Functional Programming for the Object-Oriented Programmer (if you come from object oriented world this book will help you)

5. Scala for the Web
Play Framework 2.x (This is my favourite framework, all my web projects are based on play)
Lift (I have never used it in real project but it looks really good)
Scalatra (I don’t know much about it but I will give it a try soon)
Skinny (this is Scala on Rails and it’s in alpha version)

6. Scala Object Relational Mapping
Slick (I have been using slick with play and I’m quite happy but I’m sure all the others are equally good)
Lift ORM (included in the lift framework)

7. Scala for NoSQL
The list on nosqls is really big these are the ones that I have been using

8. Other
Akka (A toolkit – and runtime – for highly concurrent, distributed, and fault tolerant applications)
Scalaz (library for functional programming to complement those provided by Scala itself)

Final note: all software mentioned here is open source so you can get your hands dirty.. fork them and enjoy scala.

Play framework

Excellent! This is how java web frameworks should had been from 2005. Play is a full stack framework and has so many features that putting them all on this post it will end up being an index list. But it’s not only the long list of features it has, it’s that everything works out of the box, there is no need to figure out how to do something. As I said the list is big, so I will only list those that I found more exciting… (I am using this framework on one of my current projects and it works very well on production environment, it’s not just another experiment).

Here they are:

  • Active Record style model, based on JPA annotations and backed by hibernate. This is probably the most missing feature form java frameworks, for some strange reason no other Java web framework (at least non that I am aware off) tackle this one and developers are stack with an anemic model – well this is probably a very controversial issue with pros and cons from both sides, anyway, this works fine for me and the fact that it removes the need for DAOs is a big win. Furthermore, just like POJOs you can transfer the model objects them from the service layer to the front-end and back again.
  • No need to compile the sources, just make a change and reload your browser.
  • Template engine, it uses Groovy as an expression language, I am not familiar with Groovy at all but I love this feature, it works just like the django templates, there is no need to know Groovy to use it.
  • Play is modular, there are already plenty of modules to use and it’s really easy to write yours. Standard distribution of Play comes with two optional modules, CRUD and Secure. I think all projects have a need for both modules. With CRUD you have a full web administration interface for all your model objects and it’s fully customizable. Secure is a simple module that helps you setup a basic authentication and authorization management, it’s also highly customizable.
  • Play also ships with an embedded application server, just type ”play run” and the world is ready for your next cool app, of course you can deploy your application on any application server. It’s really nice that the embedded application server is ready for production, it’s not just a subset to help you during development.
  • Testing the app is easier than ever.  It uses the JUnit for unit and functional testing, in your functional testing you can access directly your web controller objects. And there is a third kind of testing, Selenium for your views. But it does not stop there you can run your tests from your web page. In fact the tests are loaded only when you run Play in test mode “play test CoolApp”. Even more, with the Fixtures help class you can load your test data from a yaml file in no time. Do you want more! Continuous Integration to run your test auto-magically, just run Play with the auto-test command. I know what you think, you can do all these with any framework since they are not framework specific, but just imagine the time you need to set everything up, in Play they just work.
  • Ready for REST, it is easily scaled by running multiple instances of the same application on several servers.
  • IDE agnostic :) it comes with a command line tool that converts your project so it can be used in your favorite IDE.
  • And it’s really fast

There are a lot more cool things about this framework. It’s very different from the rest of the frameworks in a good way, just as Spring broke the rules of enterprise development years ago, Play does the same, it breaks the rules and takes an unconventional away of doing thing which is closer to the developer, with the usability and productivity in mind.

Give it a try

Clean and usable URLs in Stripes

Cool URIs don’t change wrote Tim Berners-Lee more than a decade ago, URLs should be clean, usable and persistent. However, the biggest percentage of URLs around the web still are not clean and usable and even less persistent. There are lots of reasons that URLs are not persistent and most of the times it is not in the hands of the developer or webmasters, under certain circumstances some domains may not continue to be alive or they may change hands, anyway there isn’t much a framework can do about that. But for the URLs to be clean and usable is totally in the hands of the developers and webmasters. Unfortunately most web frameworks makes things even worse by not providing the mechanism to handle URLs or by making it really difficult to change the default behavior.

Stripes is not one of those frameworks and it really makes it easy to create clean URLs and provides a very flexible mechanism for handling them.

The simplest way to do it is using the @UrlBinding annotation. Let’s assume we have the following action bean:

package com.project.action;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

 * @author omer haderi
 * @version 1.0
public class SimpleMathActionBean implements ActionBean {
	private static final String view = "/WEB-INF/jsp/index.jsp";

	private ActionBeanContext ctx;

	private double number;

	public ActionBeanContext getContext() {
		return ctx;

	public void setContext(ActionBeanContext ctx) {
		this.ctx = ctx;

	public Resolution view() {
		return new ForwardResolution(view);

	public Resolution sqrt() {
		number = Math.sqrt(getNumber());
		return new ForwardResolution(view);

	public double getNumber() {
		return number;

	public void setNumber(double number) {
		this.number = number;

The URL for this action bean to calculate the square root (assuming the default behavior) will be:

To simplify this we just need to mark the bean with the following annotation:
after this the URL will be:

Of course the point is to remove the question mark, the ampersand and the equals sign. In the previews URL the [sqrt] is an event of the action bean as you can see from the action bean class. There is a special notation to identify the event in the UrlBinding which is {$event}, so we need to modify the annotation as follows:
after this the URL will be:

Let’s move on and remove the rest of symbols. In our URL the [number] is a parameter and just like the events it can be embedded in the UrlBinding as follows:
@UrlBinding(“/public/simple_math/{$event}/{number}”) and it can even have a default value
after this the URL will be:

That’s it just one annotation and the URL is simple, more readable and makes more sense.

This is how will the action bean class look like after marking it with the annotation that we just constructed:

 * @author omer haderi
 * @version 1.0
public class SimpleMathActionBean implements ActionBean {

Here are the two URLs:
after   :
as you can see the later is much better.

You may be wondering what’s that /public over there!?
That’s the url-mapping in the servlet-mapping of the DispatcherServlet in the web.xml which can be anything that makes sence for your project:


When using UrlBinding annotation only the URL of those action beans that are marked by the annotation will change, the rest of the actions will still have the default URL binding as explained in the “URL Binding in Stripes“.

To change the default behavior to all Action Beans we would need to create a subclass of NameBaseActionResolver and override its methods:

package com.project.extensions;
 * @author omer haderi
 * @version 1.0
public class CustomActionResolver extends NameBasedActionResolver {
        // this is the url-pattern from the DispatcherServlet servlet-mapping in the web.xml
	private static final String URL_PATTERN = "/public";

	protected String getBindingSuffix() {
		return "";

	protected String getUrlBinding(String actionBeanName) {
		String result = super.getUrlBinding(actionBeanName);
		result = separeteCamelCaseWithUnderscore(result).toLowerCase();

		return URL_PATTERN + result;

	private static String separeteCamelCaseWithUnderscore(String s) {
		String pattern = "(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])";
		return s.replaceAll(pattern, "_");

You need to add the extension package in the filter parameters in the web.xml see “URL Binding in Stripes” for more information.

From now on all the action beans will have this as default URL binding.

Type safe JPA queries

Quite often I find myself refactoring parts of my applications for different reasons and I am sure most developers do the same thing. Refactoring a java application is relatively easy since java is statically typed language and compiler will catch all type mismatches, moreover, modern IDEs like eclipse, intelij and netBeans provide all the necessary tools to accomplish this task as easily as possible. However, there is one part of the application that java compiler and IDE tools cannot do much. This part is the JPA queries which are String literals and there is no way for the compiler to catch any changes from the model. It seems that things will change with JPA 2.

JPA 2 introduces the Metamodel API (proposed by Gavin King) which is useful regardless of type safe queries. The metamodel exposes a set of interfaces which can be used to write  type safe queries with the new API. Other advantages of metamodel API besides the type safe queries are that it protects from SQL injection, auto-complete support through IDE, refactoring support.

Here is an example of how cool feature this is. Consider the following entities:

package org.chemistry.domain;

import javax.persistence.Entity;
import javax.persistence.Id;

public class Substance {
	private Long id;

	private String name;
	private String symbol;
	private double atomicWeight;
	private double grams;

	// getters and setters
	// ...

package org.chemistry.domain; import java.util.Set; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Mixture { @Id private Long id; @Basic private String name; @OneToMany private Set<Substance> substances; // getters & setters // ... }

The metamodel classes for the entities will look like the following:

package org.chemistry.domain;

import javax.persistence.metamodel.*;

public class Substance_ {
	public static volatile Attribute<Substance, Long> id;
	public static volatile Attribute<Substance, String> name;
	public static volatile Attribute<Substance, String> symbol;
	public static volatile Attribute<Substance, Double> atomicWeight;
	public static volatile Attribute<Substance, Double> grams;

package org.chemistry.domain; import javax.persistence.metamodel.*; @TypesafeMetamodel public class Mixture_ { public static volatile Attribute<Mixture, Long> id; public static volatile Attribute<Mixture, String> name; public static volatile Set<Mixture, Substance> substances; }

Nothing impressive until now… the impressive part is how we can write the queries in a type safe way using the new criteria API. We can use the CriteriaQuery and the QueryBuilder to create the queries in the following way.

// get the entity manager
EntityManager em = ... ;

String query = "SELECT FROM Mixture m JOIN m.substances s WHERE = :name"
Query q = em.createQuery(query);
q.setParameter("name", "Beryllium");

// new query API
QueryBuilder qb = em.getQueryBuilder();
CriteriaQuery q = qb.create();
Root mixture = q.from(Mixture.class);
Join<Mixture, Substance> sub = mixture.join(Mixture_.substances);
q.where(qb.equals(sub.get(, "Beryllium")).select(mixture.get(;

Now any refactoring in the Mixture or the Substance classes will immediately reflect the changes to the query. The metamodel classes are (or will be) auto generated by the time the entity class is compiled. So hopefully no more runtime exceptions because of domain model refactoring :)

This is JSR 317, here you can find all the necessary details about this cool API.

URL Binding in Stripes

The best thing about Stripes is that it follows the convention over configuration practice. One of the most convenient conventions is the automatic generation and binding of URLs to the action bean class names. During development this is very helpful since you don’t need to keep in sync a configuration file as you add or delete action beans. To generate the URLs Stripes follows certain rules, of course as with everything else in Stripes you can change the default rules if they don’t meet your needs.

First lets see the default rules and then I’ll discus  how to change them if needed.

Stripes will automatically load all your action beans at start up, but we need to tell Stripes where to start looking for action beans, we need to declare at least one root package. We can do this by specifying the ActionResolver.Packages init-param in the declaration of the StripesFilter in web.xml which is the only mandatory configuration parameter. If you keep your action beans in different packages you can add all of them separated by comma as shown in the following spinet.


Now that Stripes knows how to load the action beans lets see how the URLs are generated and bound to the action bean class names. Lets suppose we have the following action bean:

package com.action.test;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

public class HelloActionBean implements ActionBean {
	private ActionBeanContext context;

    public ActionBeanContext getContext() {
        return context;
    public void setContext(ActionBeanContext context) {
        this.context = context;

    public Resolution view () {
	return new ForwardResolution("/WEB-INF/jsp/home.jsp");

Our action bean class name is HelloActionBean and it’s located under the package com.action.test; to refere to this action in a jps we can use the following name /test/Hello.action.

As mentioned previously to generate the URLs Stripes follows certain rules.
1. It will remove the package name up to and including the the following names if present in the package [action, stripes, web, www]. That’s why we refer to the /test/Hello.action without the full package name since the package name of this bean includes the token action and is removed up to that token.
2. It will remove from the class name the following suffixes [ActionBean, Action or Bean]. That’s why we have the /test/Hello.action instead of /test/HelloActionBean.action.
3. It will convert package name and class names to paths and change all periods to forward slashes. Instead of [test.Hello.action] we have /test/Hello.action
4. It will append the .action to the end of the striped bean name.

Fast forward:
rule 1: from com.action.test.HelloActionBean we get test.HelloActionBean
rule 2: from test.HelloActionBean we get test.Hello
rule 3: from test.Hello we get /test/Hello
rule 4: from /test/Hello we get /test/Hello.action

Lets see some examples of how this works:
com.pk1.action.HelloActionBean –> /Hello.action
com.pk1.web.HelloAction –> /Hello.action
com.pk1.www.HelloBean –> /Hello.action
com.pk1.stripes.HelloActionBean –> Hello.action
com.pk2.module.HelloActionBean –> /com/pk2/module/Hello.action

Some controversial examples:
com.pk1.web.MyActionBeanX  –> /MyActionBeanX.action (the ActionBean is not removed since it is not at the end)
com.pk1.www.ActionBean –> /.action (the ActionBean is removed based on the rule number 2)
http://www.web.action.stripes.HelloBean –> /Hello.action (all package tokens are removed since they are in the list of rule number 1)

Now that we know the rules for generating the URLs, lets see how we can change them to meet our needs. This process is quite easy.
The class that implements the rules for URL binding is the NameBasedActionResolver. To change the rules for URL binding you just need to extend this class and override the getBasePackages() and/or getBindingSuffix(), (if you change the suffix do not forget to change url-pattern of the servlet mapping in the web.xml). You can change completely the behavior of URL binding by overriding the getUrlBinding(String). Your custom class for the URL bind rules should be registered as a Stripes extension.

Here is an example of how to change the suffix from [action] to [go]. As I said this is quite easy, it requires two steps:

1. Change the servlet mapping in web.xml


2. Extend the NameBasedActionResolver and override the getBindingSuffix()

package com.ext;

import net.sourceforge.stripes.controller.NameBasedActionResolver;

public class CustomActionResolver extends NameBasedActionResolver {
	protected String getBindingSuffix() {
		return ".go";

Note that this is an extension and extensions are loaded automatically by Stripes but as with action beans we need to tell Stripes where to look for. To configure extensions we need to add another init-param to the StripesFilter as we did for the action beans. The parameter name for the extensions is [Extension.Packages].
Here is an example:


Extending the NameBasedActionResolver we can tweak the URLs in any way we want and as you can see it is quite easy, an interesting tweak would be to implement clean URLs but that will be another post.

The Stripes framework

Choosing a java web framework is somehow a complex process, not because they are difficult to evaluate but because there are so many of them (in fact it seems that there are more java frameworks than java developers :) but having many frameworks is a good thing. It means that there is a lot of competition and the competition seems to be healthy since most of the frameworks are open source, so competition is based on quality and features instead of marketing and lobbing.

Different people have different criteria on selecting a framework and probably different needs, so I will list my criteria an the reasoning behind them for choosing Stripes.
(Disclaimer: this expresses only my views on what I expect from a framework, I don’t think there are good or bad frameworks, from my point of view there are only convenient frameworks – just trying to avoid flame war here, although flame wars entertains me a lot!).

I would like to start with what I consider the most annoying thing when working with a Java framework which is not other than XML configuration files. Having worked with JSF and Struts where you need to configure all your managed-beans/action-beans and pretty much everything else into an xml configuration file, which during development becomes a mess to keep it in sync, I enjoy that Stripes removes all this configuration hassle with autoloading feature. The only xml configuration file that you need is the web.xml but that is required by the Servlet specification. Configuration by exception (a.k.a convention over configuration) is the way to go, developers should focus on business solutions and not in framework configuration details that will just disturb the flow of thinking. Hopefully other framework will follow – or maybe some already does.

Testing is the most important part of development and therefore frameworks should come with a build-in support for testing to make this process easy. So Stripes comes with a set of mock objects that help developers to easily write unit tests.

Easy extension and customization. Stripes is designed in modular form it is quite easy to add a customization plugin to change the behavior of any part of the framework, because of this modular design the extensibility of Stripes is trivial. Actually This is one of the areas that the framework really make the difference.

I don’t think that there’s a need to explain why internationalization of web application is important, all frameworks need to have a built-in support for i18n. Stripes tags comes with a default bundle lookup strategy so that i18n is just a mutter of adding key/value pairs in the resource bundle.

Never trust the user input, therefore a strong and flexible validation mechanism is needed. Stripes provides a powerful validation mechanism which is based on annotations (remember there is no XML configuration).

When working with request parameters the most annoying process is converting Strings to objects and vise versa, the Stripes support for this process is just amazing. But it is not just conversion there is also support for formating an object to string and that’s as easy as the conversion process.

Stripes comes with a built in support for layouts, with three tags you can achieve pretty much everything. If the built in support for templating is not enough you can use freemarker.

Since we are talking about web framework and web applications it would be a pity to not take advantage of Ajax. Any Ajax framework can be used due to Stripes simple and transparent request/response nature.

These are some of the features that I like to see in a framework and surely you can find this features in most frameworks and probably more but the difference is that with Stripes is easy and development is fun again as the book of Frederic Daoud suggests and proves it.

If you want to learn Stripes I suggest the “Stripes … and Java web development is fun again” from The Pragmatic Programmers, in fact this is the only book about Stripes but even if there were more books I am totally sure that I would suggest this book again, it is very well written and it covers everything about Stripes.

The following is a quick list of Stripes features, which I will try to explain and give an example in future post for each one of them and link them back to this page:

URL Binding
Built in Validation
Custom Validation
Type Conversion
Using Freemarker
Exception Handling
URL Customization
Ajax Integration
Framework Extension
Framework Customization
Dependency Injection (Giuce/Spring)
JPA Integration
Security and Encryption

The examples will be deployed on google app engine.

P.S: Now that the jsr 330 is approved maybe the next version of Stripes will come with build in Dependency Injection.

If you would like to start playing with Stripes and google app engine have a look at the following links:

Stripes resources:
Stripes Home Page
Stripes … and Java development is fun again

Redoing Guestbook example with Stripes

Google has created an example on how to use google app engine with java. In this example they demonstrate the basic usage of Servlet API and JDO, it’s a simple example that stores, retrieves and renders entities in google app engine.
After the first tutorial on how to deploy Stripes in google app engine I decided to re-write this example using the Stripes framework of course.

Download the source code!


1. Create a project and name it Guestbook

2. Follow the Getting started with Stripes and google app engine to configure Stripes

3. Add the JSTL jars (standard.jar and jstl.jar) in the lib directory

4. Create an ActionBean that will handle the greeting requests

package com.guestbook.action;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

import com.guestbook.manager.PMF;
import com.guestbook.model.Greeting;

 * @author 110j
public class GreetingActionBean implements ActionBean {
	private static final String VIEW = "/guestbook.jsp";
	private ActionBeanContext ctx;
	private UserService userService = UserServiceFactory.getUserService();
	private Greeting greeting;

	public Resolution welcome() {
		return new ForwardResolution(VIEW);

	public Resolution addGreeting() {
		if (greeting != null) {
			greeting.setDate(new Date());

			PersistenceManager pm = PMF.get().getPersistenceManager();
	        try {
	        } finally {
		return new ForwardResolution(VIEW);

	public Resolution signin() {
		ForwardResolution fd = new ForwardResolution(VIEW);
		if (!userService.isUserLoggedIn())
			fd = new ForwardResolution(userService.createLoginURL("/Greeting.action"));
		return fd;

	public Resolution signout() {
		ForwardResolution ForwardResolution ">fd = new ForwardResolution(VIEW);
		if (userService.isUserLoggedIn())
			fd = new ForwardResolution(userService.createLogoutURL("/Greeting.action"));
		return fd;

	public List getGreetings() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Greeting.class.getName() + " order by date desc range 0,5";
	    return (List) pm.newQuery(query).execute();

	public Greeting getGreeting() {
		return greeting;

	public void setGreeting(Greeting greeting) {
		this.greeting = greeting;

	public User getUser() {
		return userService.getCurrentUser();

	public ActionBeanContext getContext() {
		return this.ctx;

	public void setContext(ActionBeanContext ctx) {
		this.ctx = ctx;

5. Create the model class called Greeting (as described in the google example, no changes here!)

package com.guestbook.model;

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Greeting {
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    private User author;

    private String content;

    private Date date;

    public Greeting() {}

    public Greeting(User author, String content, Date date) { = author;
        this.content = content; = date;

    public Long getId() {
        return id;

    public User getAuthor() {
        return author;

    public String getContent() {
        return content;

    public Date getDate() {
        return date;

    public void setAuthor(User author) { = author;

    public void setContent(String content) {
        this.content = content;

    public void setDate(Date date) { = date;

6. Create the utility class that will instantiate the EntityManager (no changes here also!)

package com.guestbook.manager;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

public final class PMF {
    private static final PersistenceManagerFactory pmfInstance =

    private PMF() {}

    public static PersistenceManagerFactory get() {
        return pmfInstance;

7. Modify the guestbook.jsp, there are a lot of changes here since in their example google uses scriptlets, I have replaced the scriptlets with jstl tags and Stripes tags, all the logic has moved to the ActionBean.

8. Modify the welcome file list in the web.xml and set as welcome file the Greeting.action

Download the source code!

Getting started with Stripes & Google App Engine

This is a basic example of using Stripes Framework with the cloud infrastructure of Google. I am using Stripes in one of my projects that I am thinking to move it to google app engine so I decided to experiment before the migration. More posts will follow in this topic as I progress with it. The first objective is to create the basic project structure, configure and deploy, well… a hello world web application. This is a trivial application but there are some limitations using google app engine so trying to use the framework as is will fail with some non-sense stack traces.

The following is a list of things that we will be need to complete this application:
1. Stripes Framework (home page: )
2. Google app engine sdk – if you use eclipse and google plugin the sdk is included in the plugin.
3. Eclipse (you can use whatever IDE or environment you like, it’s not mandatory to use eclipse, it’s just easier).

Note: For information on how to install the google plugin visit

I assume you are familiar with java web frameworks and that you will use eclipse with the google plugin.

The first step is to create a project in the eclipse IDE:

Give a name to the project and an initial package name. For the moment we do not need GWT so just deselect it.

After pressing finish we have the following project structure.

Before continuing copy the Stripes jars in the the lib directory under hello_project/web/WEB_INF/lib and add them to the project’s build path by selecting them, right click-> Build Path -> Add to Build Path. Also copy and paste the in the directory “src” (not in a package).

By default the google plugin will generate a servlet for us, under the package name that we entered in the previews step. It will also generate the following configuration files:
Servlet spec requirement:
1. web.xml (this is the well known deployment descriptor required by the servlet specification)

Google App engine specific (we will not use them for this application):
1. appengine-web.xml
2. jdoconfig.xml

Logging property files:

For the purpose of this trivial application we will only need to edit the web.xml (a.k.a Deployment Descriptor so from know on I will call it DD).
By default the plugin registers the generated servlet in the DD, so open the DD and delete the servlet and servlet-mapping it’s not needed.

The following is the generated DD that need to be edited:

The following is the new and final DD containing the Stripes filter and dispatcher servlet:

Note that the web-app tag version has changed from 2.5 to 2.4 there are some jsp exceptions with the 2.5.

The Stripes filter includes two initial parameters the ActionResolver.Packages which tells Stripes where to find the ActionBeans (more on this in next post or in Stripes documentation) and the MultipartWrapperFactory.Class, a factory class used to upload files, but uploading files is not supported by google app engine and the Stripes filter will fail to initialize. Therefore we need to disable this by providing an empty configuration.

The first step to disable file uploading is to add MultipartWrapperFactory.Class initial parameter to the Stripes filter as shown in the DD and the second step is to create the appropriate class. So create a package in the project (I created the com.helloworld.exclude but you can create anything that make sense for your project) and add the following class:


import javax.servlet.http.HttpServletRequest;

import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.FileUploadLimitExceededException;
import net.sourceforge.stripes.controller.multipart.MultipartWrapper;
import net.sourceforge.stripes.config.ConfigurableComponent;
import net.sourceforge.stripes.controller.multipart.MultipartWrapperFactory;

 * GAE does not support file uploading so we need to disable this feature from Stripes.
 * @author 110j
public class EmptyMultipartWapper implements ConfigurableComponent, MultipartWrapperFactory {

	 * @see net.sourceforge.stripes.config.ConfigurableComponent#init(net.sourceforge.stripes.config.Configuration)
	public void init(Configuration conf) throws Exception {

	 * @see net.sourceforge.stripes.controller.multipart.MultipartWrapperFactory#wrap(javax.servlet.http.HttpServletRequest)
	public MultipartWrapper wrap(HttpServletRequest request) throws IOException, FileUploadLimitExceededException {
		return null;

Now that we disabled the file uploading lets create an ActionBean that will handle our request. Create a package in the project called com.helloworld.action and add the following class:

package com.helloworld.action;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

 * The action bean that will handle the our simple request.
 * @author 110j
public class EasyActionBean implements ActionBean {
	private static final String VIEW = "/WEB-INF/jsp/hello_world.jsp";
	private static final String MY_MESSAGE = "hello world";
	private ActionBeanContext ctx;

	private String message;

	public Resolution showMe() {
		return new ForwardResolution(VIEW);

	 * @see net.sourceforge.stripes.action.ActionBean#getContext()
	public ActionBeanContext getContext() {
		return this.ctx;

	 * @see net.sourceforge.stripes.action.ActionBean#setContext(ActionBeanContext)
	public void setContext(ActionBeanContext ctx) {
		this.ctx = ctx;

	 * @return the message
	public String getMessage() {
		return message;

	 * @param message the message to set
	public void setMessage(String message) {
		this.message = message;

Next lets create a jsp file that will render the response, create the hello_world.jsp under WEB_INF/jsp/ and add the following content:

Finally create a welcome file called index.jsp if it does not exist or rename the index.html to index.jsp and add just a forward to the action:

You can delete the servlet generated by the google plugin there is no need for it.

In order to test it you just need to run the hello_world in the Run history of eclipse as the google plugin will create one for us, or under the run button in the toolbar, and then visit the address localhost:8080

NOTE: if your application require session you need to enable it in the appengine-web.xml since it is disabled by default (but keep in mind the implication it may have in a distributed environment such as google app engine, maybe your attributes will need to implement the HttpSessionActivationListener if you plan to add them in the session).

You can upload your application by using eclipse or the command line tool, for more information visit

To be continued!

tail the log file inside eclipse

Most common tool to follow the logs of the application is tail at least under unix, linux and probably mac osx operating systems. So we just need to open a console and type tail -f path/app.log. Fairly simple but it would be nice to have it inside eclipse, which turns out to be also very simple to configure it with the external tools of eclipse.

Open External Tools Configurations:

External tool configuration

External tool configuration

Hit Run and that’s it. Windows users should install a tail for windows first!