I recently moved one of my applications to Google AppEngine. What I found missing was an explanatory tutorial to get started. As I mostly work with C#, I kept running into issues simply because I wasn’t too familiar with the technologies used.

Thus I’m writing this easy to follow all-steps-included tutorial, to help people whom are in a similar position to quickly get started developing with Grails for Google AppEngine.

This tutorial will take you through setting up a simple Grails application running on Google AppEngine; using the app-engine and GORM-JPA plugins to Grails. If you run into trouble, I’ve added a trouble shooting section at the end.

First of make sure you have the latest version of the Google AppEngine SDK, and Grails 1.1.1 or better. If you want to deploy your application to Google AppEngine, make sure you have an active account.

I also added a Known Issues section at the end, it’s there to assist you if you run into trouble.

Lets get started.

Create a Grails Application

First create a Grails Application using the create-app command. For this tutorial we’re creating an application called AppEngineDemo; but the name is not important.

C:\Users\Morten\IdeaProjects>grails create-app
Welcome to Grails 1.1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: c:\dev\grails-1.1.1

Base Directory: C:\Users\Morten\IdeaProjects
Running script c:\dev\grails-1.1.1\scripts\CreateApp_.groovy
Environment set to development
Application name not specified. Please enter:
AppEngineDemo

Install the App-Engine plugin

The app-engine plugin requires a environment variable to be set to the location in which the Google SDK is installed. I recommend you take a minute or two to read through the plugin information page. I’ll add some examples form running the installation on the command line.

Move to the newly created application and install the app-engine plugin to the application.

C:\Users\Morten\IdeaProjects>cd AppEngineDemo

C:\Users\Morten\IdeaProjects\AppEngineDemo>grails install-plugin app-engine
Welcome to Grails 1.1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: c:\dev\grails-1.1.1

Base Directory: C:\Users\Morten\IdeaProjects\AppEngineDemo
Running script c:\dev\grails-1.1.1\scripts\InstallPlugin.groovy
Environment set to development
Reading remote plugin list ...
Reading remote plugin list ...
Plugin list out-of-date, retrieving..

During the installation the plugin will ask you which persistence provider you want to use. We want to use the GORM-JPA plugin so select JPA for persistence.

Do you want to use JPA or JDO for persistence? (jpa, jdo)
jpa

This will create a file called persistance.xml in your Grails conf directory. In this file we will specify which domain objects we can persist to the Google AppEngine data storage.

Install GORM-JPA plugin

The GORM-JPA plugin will allow us to use the convenient dynamic methods for persistence; for example save() or findby…()

It is a straight forward to install the plugin

C:\Users\Morten\IdeaProjects\AppEngineDemo>grails install-plugin gorm-jpa
Welcome to Grails 1.1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: c:\dev\grails-1.1.1

Base Directory: C:\Users\Morten\IdeaProjects\AppEngineDemo
Running script c:\dev\grails-1.1.1\scripts\InstallPlugin.groovy
Environment set to development
Reading remote plugin list ...

Create a domain class

We want to create a domain class for the application, in this tutorial we will create a domain class called Note.

C:\Users\Morten\IdeaProjects\AppEngineDemo>grails create-domain-class
Welcome to Grails 1.1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: c:\dev\grails-1.1.1

Base Directory: C:\Users\Morten\IdeaProjects\AppEngineDemo
Running script c:\dev\grails-1.1.1\scripts\CreateDomainClass.groovy
Environment set to development
Domain class name not specified. Please enter:
Note
Created DomainClass for Note
Created Tests for Note

Next we generate the necessary controllers and views for the Note domain class.

C:\Users\Morten\IdeaProjects\AppEngineDemo>grails generate-all Note
Welcome to Grails 1.1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: c:\dev\grails-1.1.1

Base Directory: C:\Users\Morten\IdeaProjects\AppEngineDemo
Running script c:\dev\grails-1.1.1\scripts\GenerateAll.groovy
---
Generating views for domain class Note ...
Generating controller for domain class Note ...
Finished generation for domain class Note

Move the domain classes into a package

The storage platform used by Google AppEngine doesn’t allow you to have your persisted domain classes in the default package. Not to worry, this is also good practice. We move our Note domain class into the package called persisted.

package persisted;

import javax.persistence.*;
// import com.google.appengine.api.datastore.Key;

class Note implements Serializable {

 Long id

}

Note the green code line in the above code.

Might as well add some code while were at it. The complete code for the Note domain class should be the following:

package persisted;

import javax.persistence.*;
// import com.google.appengine.api.datastore.Key;

class Note implements Serializable {

 Long id

 String message
}

Update the domain class with annotations

Now we must specify that the Note class can be persisted, and how it will be persisted. This is done using JPA annotations.

You might have noticed the @Entity, @Id,  @GeneratedValue… lines in the above code. These are JPA annotations added by Grails when you created the domain class. Now we must specify one for our added Message property.

We just want to say that it should be persisted along with the class. For this we add the @Basic annotation above the line declaring the message property. This will tell the persistence layer that this property should be saved.

package persisted;

import javax.persistence.*;
// import com.google.appengine.api.datastore.Key;

@Entity
class Note implements Serializable {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 Long id

@Basic
 String message

}

A list of the JPA annotations and their usages can be found here.

Generate the views and controllers

Now it’s time to generate view and controllers for the Note class. This is done as normal, specifying which class to generate for.

C:\Users\Morten\IdeaProjects\AppEngineDemo>grails generate-all persisted.Note
Welcome to Grails 1.1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: c:\dev\grails-1.1.1

Base Directory: C:\Users\Morten\IdeaProjects\AppEngineDemo
Running script c:\dev\grails-1.1.1\scripts\GenerateAll.groovy
Environment set to development
 [groovyc] Compiling 1 source file to C:\Users\Morten\.grails\1.1.1\projects\AppEngineDemo\classes
 [copy] Copying 1 file to C:\Users\Morten\.grails\1.1.1\projects\AppEngineDemo
 [groovyc] Compiling 1 source file to C:\Users\Morten\.grails\1.1.1\projects\AppEngineDemo\classes
 [copy] Copying 1 file to C:\Users\Morten\.grails\1.1.1\projects\AppEngineDemo
Generating views for domain class persisted.Note ...
Generating controller for domain class persisted.Note ...
Finished generation for domain class persisted.Note
C:\Users\Morten\IdeaProjects\AppEngineDemo>

Notice that I specified the package name for the class.

First time deployment to Google AppEngine

Create an application on Google AppEngine using Google’s AppEngine website. When you create your application you specify an name for it. You need to include this name in the grails-app/conf/config.groovy file in your application. Add the following line to the file:

google.appengine.application = "<your application name>"

To host your application on Google AppEngine you need to set the version to a number between 1-100. It has to be an integer, floats are not accepted.

then do the following:

grails set-version 1
grails app-engine package
$APPENGINE_HOME/bin/appcfg.sh update ./target/war

and now to deploy

grails app-engine deploy

Congratulations, your first, basic Google AppEngine application is now running.

Known Issues

Since Grails on Google AppEngine is pretty new, not to mention Java on Google AppEngine. There are still some issues to work through.

Staging dir not cleared

Before we start I just want to mention some known Issues. There is an issue where the staging dir is not removed, you have to delete this manually. You can find it under:

 <user directory>\.grails\1.1.1\projects\<projectname>\stage

the 1.1.1 is the version Grails your using. This causes issues if you install the ui-performance plugin.

Rendering JSON

There is also an issue with rendering JSON. Rendering JSON can cause access exceptions when rendering entities fetched using the GORM. Please see this blog post for details.

Update: I recentlly wrote this post on Fun times with JSON rendering. Containing more details about JSON Rendering.

Generating controllers

You can run into issues generating controllers and views for your domain classes. The current workaround as far as I know is to install the hibernate plugin, generate the views or controllers, then uninstall the hibernate plugin. You can see the details here.

Command Line too long on Windows machines

If your on a Windows machine you might run into a problem where you cannot enhance your classes (preparing them for storage on the GoogleAppEngine data store). The problem is that the command line when enhancing them becomes too long. You can find more details in my previous blog posts on the subject.

Saving Entities with constraints

If you add constraints to your classes you can run into issues where Google AppEngine will try to save the entity using the wrong class. More details in this blog post.

Recommended reading

Here is link to the open JIRA issues for the AppEngine plugin.

If you find any errors in this tutorial or have ideas to improve it, please let me know.

Hope it helps!

So I have my Grails environment setup. The point is to build a REST-service that will work as a back end to a highly dynamic JavaScript page. I chose Grails, since it builds on Hibernate and Spring.

Two frameworks Id like to examine for the purpose of seeing the differences between Castle and nHibernate in the .Net world.

Building domain-classes and having the represented as XML is straight forward in Grails, but I need to take care of the login scenario. If you’d like to know more about building REST web services with Grails, I recommend reading the Mastering Grails: RESTful Grails article. Login seems like a good place to start, to ensure that my domain-controllers can dictate login as I develop the domain.

Now Grails.org has a list of tutorials, one of them, focusing on Login. It’s a good beginners tutorial showing how to use interceptors to execute user verification before showing the actual view requested. For my scenario however it has a few problems. Lets use the tutorial as a start of point.

The problems I have with the solution is with the following code:

def checkUser() {
  if(!session.user) {
    // i.e. user not logged in
    redirect(controller:'user',action:'login')
    return false
  }
}

For my scenario this has one problem, in two places. Its stateful. First of it always directs the user to the same place, of course it can be different per controller. I need it to simple say access denied.

def checkUser() {
  if(!session.user) {
    // i.e. user not logged in
    response.sendError(401)
    return false
  }
}

The above code is changed to instead of redirecting the user, it simply sets the response code to Access Denied. Now there’s just one issue left, the session code.

I don’t want to use session, as it requires my server to remember each session, preferably I want the client to remember the state.

Another issue is that I want to use Mor.ph AppSpace, if I pay for the most basic of subscriptions at Mor.ph I get two Cube, i.e. two servers with a load balancers in front. As a result I can’t be sure that the same server will service the same client all the time.

If we instead choose to check for the logged in user using the authorization header. The state is always provided by the client, instead of keeping the state on the server.

def checkUser() {
  if(!UserController.checkAuthorization(request, response)) {
    // i.e. user not logged in
    response.sendError(401)
    return false
  }
  return true
}

I let the UserController do the checking of the user, using a static method. This will let me keep the authorization code in the same place I handle users to begin with. It also allows me to change the authorization method later by changing the code in the checkAuthorization method. We could use Dependency Injection here to inject a real instance of the UserController, or even better an object with the sole responsibility to check user access. However DI is out of scope for this post.

You can implement any way of checking the user login you want. If you want a simple solution and stick with the HTTP standard you could use Basic auth. Here is a good explaination of how to implement Basic auth for Grails. Another way is too use a cookie to hold authorization information.

For this example were just sending username:password in the authorization header. My final implementation will be Basic Auth with the password hashed to a checksum. The point of the hash is to never send plain-text password across the net.

Here is the checkAuthorization method in the UserController for this example.

static boolean checkAuthorization(HttpServletRequest request, HttpServletResponse response) {
  def authString = request.getHeader('Authorization')

  if (!authString) {
    return false;
  }

  def credentials = authString.split(':')
  if( credentials.length != 2 || credentials[0] == null || credentials[0] == "" || credentials[1] == "" || credentials[1] == null)
    return false;

  def user = User.findByEmailAndPassword(credentials[0], credentials[1])

  if (user) {
    return true;
  }
  return false;
}

Now we can create some JQuery based JavaScript code to handle login.

function RestClient() {
    var self = this;
    var auth;

    function ShowLoginUI(afterLoginCallback) {
        var dialog = document.createElement('div');
        $(dialog).html("<table><tr><td>Email</td><td><input id='email' type='text'/></td></tr><tr><td>Password</td><td><input id='pass' type='password'/></td></tr></table>");
        $(dialog).dialog({ buttons: {"Login": function() {
            auth = $(this).find("#email").val() + ":" + $(this).find("#pass").val();
            afterLoginCallback();
            $(this).dialog("close");
        }, "Cancel":function() {
            $(this).dialog("close");
        }}, modal:true});
    }

    this.Get = function(url) {
        var data = null;

        data = $.ajax({
            url : url,
            method : 'GET',
            beforeSend : function(req) {
                req.setRequestHeader('Authorization', auth);
            }, cache : true,
            error: function(request, textStatus, error) {
                if (request.status == 401) {
                    ShowLoginUI(function() {
                        data = self.Get(url);
                    });
                }
            }});

        return data;
    };
}

The above code does Ajax Get-calls to the specified address. If the call failed due to Access Denied, it shows a login form and tries to execute the Ajax request again. The class remembers the authorization string, so as long as the user uses the same RestClient-object the state is maintained at the client side. Ill leave instructions on how to wire up Grails with JQuery to someone else.

Here is a simple usage example:

var a = new RestClient();
$("#test").click(function() {
  var data = a.Get("plant/create");
  $(document).append(data);
});

Good luck writing scalable login scenarios using Ajax instead of page reloads.