mycodesnippets.com

All about Groovy, Grails, Java and Linux

Would you like to see an Ubuntu PPA repository for Grails?

At the Grails Exchange in London during December 2010 we spoke about setting up a PPA repo for Ubuntu.

This will make installation of Grails a lot easier on an Ubuntu Linux system. Of course, this does mean that someone (probably me) would need to maintain this, which I would be more than happy to do provided that we have a enough interest in the community.

Is anyone else interested in this? Would this be of any value to anyone besides me? Please help me find out by voting below.


This poll will close on 1 March.

Cheers,
Marco.

Grails on Terracotta using Ehcache

These days, much talk goes into making your applications scale better. With the internet growing rapidly, and large companies investing vast sums of money into presenting their goods to the world, we need to become more innovative in how we handle these large volumes of traffic. Somehow, our single small instance of Tomcat fronted by a little Apache just won’t cut it any more!

So how do you go about scaling an application out? More specifically, how do you scale a Grails application? In the Java landscape we have several great clustering technologies to choose from. The product that I tend to levitate towards is the open source Terracotta. This is a practical guide to scaling out a Grails application with Terracotta using Ehcache integration.

Configure your Application

Firstly, we need to get our application ready for working with Terracotta. As expected, Terracotta (almost) doesn’t impose on your code. Here’s how I got it all working:

Step 1: Implement Serializable
All domain classes should implement java.io.Serializable. There is no need to import it because it’s already provided by Groovy!

package my.app
 
class Person implements Serializable {
    String firstName
    String lastName
 
    static constraints = {
    }
}

Step 2: Make Domain Classes Cacheable
All domain classes to be clustered should be marked as cacheable in the mapping closure of the class.

class Person implements Serializable {
...
    static mapping = {
        cache true
    }
}

Step 3: Add the Terracotta Maven Repository
This is done in the BuildConfig.groovy file. Locate the repositories section and add the following repo:

    repositories {
        ...        
        mavenRepo "http://www.terracotta.org/download/reflector/releases"
        ...
    }

Step 4: Introduce the Ehcache and Terracotta Dependencies
This can be done easily using the dependency resolution DSL in the grails-app/conf/BuildConfig.groovy file. Find the inherits("global") section and update as follows:

inherits( "global" ) {
    // uncomment to disable ehcache
    // excludes 'ehcache'
    runtime 'net.sf.ehcache:ehcache-core:2.2.0'  
    runtime 'net.sf.ehcache:ehcache-terracotta:2.2.0'
    runtime 'net.sf.ehcache:ehcache-explicitlocking:0.2'
    runtime 'org.terracotta:terracotta-toolkit-1.0-runtime:1.0.0'  
}

Step 5: Configure Ehcache to use Terracotta
Create a file called ehcache.xml in the grails-app/conf folder. This will create an Ehcache CacheManager called MyCache, and will give you some defaults to begin working with. Refer to the ehcache website to add cache configurations per Domain class in your app.

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="MyCache" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="ehcache.xsd">
 
   <defaultCache
      maxElementsInMemory="1000"
      eternal="false"
      overflowToDisk="false"
      diskPersistent="false"
      timeToIdleSeconds="1200"
      timeToLiveSeconds="1200">
          <terracotta />
   </defaultCache>
 
   <terracottaConfig url="localhost:9510" />
 
</ehcache>

The import things to look out for are the terracotta tags in this file.
The first lies within the defaultCache tags, and marks it to be clustered by Terracotta.
The second lies within the ehcache tags, and specifies where to find the terracotta server. More about that in a minute…

Step 6: Add a Custom Cache Configuration
Next, we will add a cutom cache config for our Person class. This is simply done by adding a set of cache tags to the ehcache.xml file right beneath the defaultCache tags.

...
  <defaultCache
  ...
  </defaultCache>
 
  <!-- Add the custom cache config here -->
  <cache name="my.app.Person" maxElementsInMemory="1000"
      maxElementsOnDisk="10000" eternal="false" timeToIdleSeconds="3600"
      timeToLiveSeconds="0" memoryStoreEvictionPolicy="LFU">
      <!-- Adding this element turns on clustering for myCache. -->
      <terracotta />
  </cache>
...

One final thing…

It’s very important to use a persistent database for this exercise to succeed. We will need to open our grails-app/conf/DataSource.groovy file and update it as follows, using the HSQLDB file database, in update dbCreate mode.

...
environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop','update'
            url = "jdbc:hsqldb:file:devDB"
        }
    }
    test {
...


Let’s have some fun!!!

That’s it. Most of the hard work is done, and we are now ready to start testing our clustered Grails app!

Let’s head on over to the Terracotta Site and download the Terracotta Binary Distribution. Unpack it to a convenient place (usually in /usr/local) and start up the server in a terminal.

$ /usr/local/terracotta-3.3.0/bin/start-tc-server.sh

Next, fire up the Terracotta dev console:

$ /usr/local/terracotta-3.3.0/bin/dev-console.sh

You can now start your grails app, and should see it connecting to the terracotta server running locally. Click on the Ehcache button and select the Statistics tab. This should pop up a confirmation, answer yes to this. I created a few People using the scaffolding in Grails:

I then refreshed the Person List page in the browser MANY times in order to get the result below. As you can see, I had a 99% hit ratio!


Now for the fun bit! Stop and start your Grails app! Once it’s started up and connected to Terracotta again, try refreshing the Person List page and watch what the console has to say (remember to click refresh on the console): No misses and several hits! 100% Hit ratio, with NO database access!


Well, that’s it in a nutshell! Terracotta and Grails, one happy couple. In a subsequent post, I will write about setting up a cluster of Grails apps with several Terracotta servers. You will see that running a cluster is as easy as setting up a single instance like we did in this post.

Let me know your thoughts, and please share any other experiences you might have.
Enjoy it and have lots of fun,
Cheers,
Marco.

Source Code of the above example is available here.

Grails Version Switcher Script

With Grails versions coming out in rapid succession, I can barely keep up :-) To add to that, I always want to go back to previous versions for development purposes. In response, I concocted a handy little bash script that allows you to switch between versions of grails seamlessly from the command line.

Prerequisites
All your Grails installations need to be extracted to a single base directory. I usually end up using /usr/local/ on my Linux boxes. This needs to be set inside your script as BASE_DIRECTORY (see below).

Next, place the listing below in a file and save it to some location. Then invoke the following from the command line to move it onto your path and make it executable:

$ sudo mv /path/to/my/script/grails-link /usr/local/bin/
$ sudo chmod +x /usr/local/bin/grails-link

You should now be able to type grails-link on the command line and see the following output:

Usage: grails-link <version>

How it works
If you’ve downloaded Grails 1.3.x, and extracted the zip to /usr/local, you should be able to enter the following in order to switch to your new version:

$ grails-link 1.3.x
Trying /usr/local/grails-1.3.x
Linked up Grails 1.3.x...

If not successful, you should get something like:

Trying /usr/local/grails-1.3.x
Not a valid Grails version...

Here is the script:

#!/bin/bash
 
if [ -z "$1" ]; then
    echo "Usage: grails-link <version>"
    exit
fi
 
BASE_DIR="/usr/local"
echo "Trying $BASE_DIR/grails-$1"
if [ -d "$BASE_DIR/grails-$1" ];
then
    sudo unlink "$BASE_DIR/grails"
    sudo ln -s "$BASE_DIR/grails-$1" "$BASE_DIR/grails"
    echo "Linked up Grails $1..."
else
    echo "Not a valid Grails version..."
fi

You can also get it here from this site (see downloads page).

Hope this makes your life a little easier. Let me know how it goes!

Cheers,
Marco.

Edit Grails files with Gedit and Gred on Linux

When working on a Grails project, I generally prefer using text editors over heavyweight IDEs. They seem to give me more flexibility and agility than their bulky counterparts. For Groovy and Grails in particular, I favour using the great Gnome text editor gedit.

Using this editor by itself does come with limitations since it knows nothing about Grails. Next, you can give it wings by installing additional helper files found in the gedit-grails-bundle. This will add Groovy syntax highlighting, bundles, and many other nice features like tab completion for the grails command on the command line. After this has been installed, and all instructions have been followed, gedit should be fully functional and ready to work on your Grails project. It should function much like TextMate on Mac OS X.

I began to realize that despite all of this, one thing was missing: I wanted to invoke gedit from the command line like I invoke the grails script. Wouldn’t it be great if you had a script to do this? In steps gred! It is my attempt at doing just this. It is a script that can be placed on your path, helping you to get to your files fast!

If you have Git installed, get it off github like this:

git clone git://github.com/marcoVermeulen/scripts.git

As super user, place the script in the gred folder on your path, and make it executable:

# cp scripts/gred/gred /usr/local/bin/
# chmod +x /usr/local/bin/gred

A listing of this script can also be found at the end of my post.

In order to use the script, ensure that you have the following line in your ~/.bashrc file:

export EDITOR="/usr/bin/gedit"

Also ensure that you already have gedit running before running gred the first time.

Now change to the directory of your project:

cd myproject

By simply entering the command, you will receive the following help:

Usage: gred <domain class> [option]
 options:
     -tests       :  open all unit and itegration tests.
     -unit        :  open unit tests
     -integration :  open integration tests
     -int         :  open integration tests
     -builder     :  open test object builders
     -controller  :  open controller
     -service     :  open all services
     -views       :  open all .gsp files for domain class

An example of using this script:
Having a User domain class with unit and integration tests in your Grails project,
you can open gedit on all the related artifacts by simply typing:

> gred user -all

If you only wanted to see the integration test, you could type:

> gred user -integration

or simply

> gred user -int

It is also noteworthy that the name of the domain class can be written in a case-insensitive
way for convenience.

As promised, here follows the listing. This is subject to change as I improve and expand the script. It might be worth pulling from github from time to time in case I make some updates. Since the code is changing so often, it’s becoming difficult to maintain it in two places. I’ve resorted to only updating the version on GitHub.

If you have any suggestions of how you would like the script improved, please drop me a comment.
Thanks for reading, and hope you enjoy the script!
Cheers,
Marco.

Configure Postgres to accept Remote Connections

I recently tried to get Postgres working as a remote database in a team development effort. Getting it set up for this kind of scenario took a little bit of tweaking, but wasn’t too bad. Here is what I ended up doing:

Find the Postgres config directory on your Linux box. On my Debian based Linux, that would be /etc/postgresql/8.4/main but could also be in /var/lib/pgsql/data on other distrabutions.

Now edit the pg_hba.conf file, adding the following snippet to the end section after the local entry:

# TYPE  DATABASE  USER  CIDR-ADDRESS  METHOD
local   all  all  trust
 
# add the new line here!
host    all  all  your_mates_ip  255.255.255.0  trust
...

Next we will need to edit the postgresql.conf file. Locate the section marked CONNECTIONS AND AUTHENTICATION in this file, changing the commented out listen_addresses section to:

listen_addresses = '*'

Now all that remains is for the Postgres server to be restarted. Using the startup script as sudo user:

sudo /etc/init.d/postgresql-8.4 restart
* Restarting PostgreSQL 8.4 database server      [ OK ]

You’re almost there… Lastly you need to ensure that your firewall is allowing connections on port 5432 (or whatever port you choose the Postgres listener to run on). This can be done using your distro’s GUI tools.

That’s it, your external clients should be able to access your server now! Have fun!