configuring a Neo4j GraphDatabaseService via Spring

Starting with Neo4j 1.9 the constructors for EmbeddedGraphDatabase and HighlyAvailableGraphDatabase were deprecated. The recommended way to instantiate those from Java is by using factory classes as documented in the reference manual. In the case of HighlyAvailableGraphDatabase use a different factory class HighlyAvailableGraphDatabaseFactory.

If you’re using Spring for wiring components or Spring Data Neo4j then it’s up to the container to build up the GraphDatabaseService for you. Doing this with factories is a little bit more tricky but I’ve create two gists.

Creating a EmbeddedGraphDatabase

<?xml version="1.0" encoding="UTF-8"?>

<beans  xmlns=""


    <util:map id="config">
       <entry key="enable_remote_shell" value="true"/>

    <bean id="graphDbFactory" class="org.neo4j.graphdb.factory.GraphDatabaseFactory"/>

    <bean id="graphDbBuilder" factory-bean="graphDbFactory" factory-method="newEmbeddedDatabaseBuilder">
         <constructor-arg value="/tmp/neo4j"/>

    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder" factory-method="setConfig">
        <constructor-arg ref="config"/>

    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal" factory-method="newGraphDatabase" destroy-method="shutdown" />


Creating a HighlyAvailableGraphDatabase

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns=""
    <util:map id="config">
       <entry key="ha.server_id" value="1"/>
       <entry key="ha.initial_hosts" value=":5000,:5001,:5002"/>
       <!-- put in more config parameters here, -->
    <bean id="graphDbFactory" class="org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory"/>
    <bean id="graphDbBuilder" factory-bean="graphDbFactory" factory-method="newHighlyAvailableDatabaseBuilder">
         <constructor-arg value="/tmp/neo4j"/>
    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder" factory-method="setConfig">
        <constructor-arg ref="config"/>
    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal" factory-method="newGraphDatabase" destroy-method="shutdown" />

how to use Cypher over JDBC from Groovy

Groovy has a very convenient to use API for accessing databases over JDBC. My colleagues at Neo Technology brought up a JDBC driver for Cypher. It’s very easy to bring these two together. The only ugly thing here is that you have to use a class called “Sql” to emit Cypher statements.

@GrabResolver(name="neo4j", root="")
@GrabResolver(name="restlet", root="")
@GrabConfig(systemClassLoader = true)

import groovy.sql.*

def sql = Sql.newInstance('jdbc:neo4j://localhost:7474/')

println "simple cypher statement"
sql.eachRow("start n=node(*) return n") {
	println "row $it"

println "parameterized cypher statement"
sql.eachRow("start n=node({1}) return n", [0]) {
	println "row $it"

Dependency management is done by using the @Grab annotations. However there is some tweaking required. Not all required libraries are found on Maven central, so we need to add to repos, one for neo4j and one for restlet. Since we need to register a JDBC driver, the dependencies must be configured on system classloader level.


Neo4j Cypher JDBC driver also allows the usage of parameterized Cypher which know JDBC users by the term “prepared statement”. This is shows in l. 16. Since JDBC does not support named parameters you have to use numbers for the parameters, starting with “{1}” and provide a list of parameter values.

With this small example you can access your Neo4j server very easily.



upgrading an old Neo4j database using Groovy

In a project I’m involved with there is still a very old Neo4j 1.0 database used. Now this database should be used with an up-to-date version of Neo4j (1.7.2 as of this writing).

Following Neo4j docs, upgrades are done incrementally with every x.y in-between version by starting up and shutting the DB. For upgrading, a config parameter allow_store_upgrade=true must be set.

I’ve found manually downloading each intermediate version too boring and hacked a short groovy script helping with upgrading the datastore, see

The script must be configured with the right database directory and for the desired target version of Neo4j uncomment the matching @Grab annotation. So when going from 1.0 – 1.8 this script must be called 8 times, each time with the next subsequent @Grab activated.

For those who wonder what the @Grab annotation does: it accesses a maven repository, downloads the dependencies behinde the scene and adds them to the class path.

The upgrade itself is trivial, just fire up an EmbeddedGraphDatabase with allow_store_upgrade=true and shut it down afterwards.

update on Grails Neo4j GORM plugin

The milestone release 1.0.0.M2 of the  Neo4j Grails GORM plugin was published a couple of days ago. The plugin provides a GORM compliant implementation backed by a Neo4j datastore. This means you can switch any Grails application to use Neo4j by simply exchanging the GORM plugin used.

Plugin documentation can be found at There is also a very minimal demo application available at, see for the source code. The demo app consists of three trivial domain classes with scaffolding controllers – nothing more for now.

Since there is currently the Neo4j Challange in progress, I’ve decided to participate there. As already stated the neo4jsample demo application is very minimal but it its intention is to serve as a starting point for your own Grails application using Neo4j as datastore backend. If you want support this project in the neo4j challenge, please send a tweet.

project setup for Grails with customized plugins using git submodules

Starting with it’s initial version a couple of years ago, Grails comes with a very nice predefined project structure, e.g. domain classes go into grails-app/domain. Every artefact has its well defined location. Almost every Grails application doing a little more than a simple “Hello world” will use at some extend one or more of the 500+ available plugins. The easiest way is to add plugins by using

The plugin gets downloaded from the central repository and added into your application, either in or into grails-app/conf/BuildConfig.groovy (default for Grails 2.0). In both cases the application contains only a reference to the installed version number.

This approach works very nice as long as you don’t have to change anything inside the plugin. I’ve had multiple times the necessity to modify external plugins, due to fixing bugs or due to some special requirements that are not yet covered by the existing released version. To deal with this, there are a couple of approaches:

1) most naive:

The most simple thing to do is just opening the plugin’s source files using your IDE and make your modifications. This has some real downsides:

  • your changes will be lost whenever you install a new upstream version of the plugin
  • since Grails unpacks installed plugins by default into $HOME/.grails/<grailsversion>/projects/bullseye2/plugins/<pluginname>, your changes are not part of any SCM and only reside locally.

I’ve warned you! Don’t do this!

2) build customized plugins in a seperated location

  • download the sources of the desired plugin, unpack it outside your main application
  • modify the plugins
  • create ‘your’ version: grails package-plugin
  • switch to your application and install the generated plugin: grails install-plugin <zipfile>

This approach annoys me, since you need to repeat the ‘package-plugin’/’install-plugin’ cycle for each an every change in the plugin. So inline-plugins to the rescue…

3) use inline plugins and copy the plugin’s sources into your application’s repo

Grails has the ability to use ‘inline plugin’. There are a couple of nice blog posts covering this, so I’m just using Burt Beckwith’s slides as a reference. You basically unzip the plugin’s zip artefact into some folder inside your application (e.g. plugins folder), reference it in grails-app/conf/BuildConfig.groovy and add the extracted files to your application’s repo.
In that case you’ve basically created a diverging copy of the plugin. Whenever there’s a new release of the plugin, integrating this back into your app might become a pita. You need to reapply your changes on top of the version of the plugin. That’s doable, but requires some advanced git technique, is error prone and can consume a lot of time – I know what I’m talking about here, trust me! Another major downside is that your local fixes and improvements are not easy to contribute back to upstream.

4) use inline plugins with git submodule

At that point, I’m expecting that you’re already using git for your project. If not, NOW is the time to do this and familiarize yourself with git. It’s worth it, promised!

  • create a distinct folder inside your project, e.g. ‘plugins’ that will contain all customized plugins
  • Find out the location of the plugin’s scm. A lot of plugins host their sources now on github. If so, fork this repository on github. If it’s using svn, you could mirror it to github, see a nice blog post for this. Basically you have now a forked plugin available on github.
  • clone the forded repo into your project, I’m using the spring-security-ui plugin here as example:

    The nice thing is that your application’s repo contains now a reference to the plugin’s repo and it even remembers the sha-id of the plugin you’re currently using.
  • now add plugins/grails-spring-security-ui as a inline plugin by adding to grails-app/conf/BuildConfig.groovy
  • push your changes
  • last but not least ask your collaborators on the project to pull your changes, let them do git submodule update --init. This command is only required once for each working copy.

The really nice thing about this setup is that you can easily share your plugin changes to the upstream repository by a pullrequest. And the other way is also pretty easy: when the upstream author accepts your pullrequest and/or adds a some new functionality you can directly consume this by going to your plugin’s directory and use

NB: this results in a to-be-committed change in the upstream repo since the sha-id of the referenced repo has changed.

some notes
  • whenever you commit something to a submodule the parent repo will have a non-empty status since your copy now references another another sha-id.
  • choose the URL of the custom plugin repo carefully. If you’re the only developer make changes in the plugin, you might use the repo’s public address and override locally the push url to your private URL by

    Now there’s a difference in fetch and push URLs:

    Your collaborators will only get the public fetch URL for both and won’t be able to commit to your private repo (that’s why we’re calling it private, right?).

    The other scenario is when you want multiple developers commit to the plugin repo. In this case you need to grant them access to your private repo (or even set up a github organization for that) and use the private URL in the ‘git submodule add’ command.

Contributing your changes back to the plugin upstream repo is very well explained at Fork a repo.


With the approach explained you’re able to customize any plugin and track the plugin changes from your applications repo. Contributing your bugfixes and improvements back to the upstream author is a piece of cake now as well as benefiting from upstream changes.

I’d be greedly waiting for your thoughts and for discussion on this setup. Combining this with git-flow looks like a kind of best practice for Grails projects – at least for me.

embedding the git/hg/svn’s revision number inside a grails application

When your application goes to production, you should be prepared for handling bugs. Users and customers will find them and hopefully report them. I’ve been multiple times in a situation where a well written bug report including a stacktrace doesn’t help me much because the stacktrace doesn’t match the current development state of the code. Therefore it simplifies life if the bug report contains a build number or a SCM revision number. With this small recipe, you can easily add this information to your application.

Find out your current SCM revision

Every version control system does this differently, so here’s a short summary of what command might be used for what SCM:

SCM command to get revision information
Mercurial hg id -i -n -b -t
Git git rev-parse HEAD
Subversion svnversion

If your SCM of choice is not listed and you know the command, please let me know by posting a comment.

Create a template that contains the revision information

For the following, I’ll use mercurial, it should be easy to adopt this to the SCM of choice. Using a Gant-Script scripts/_Events.groovy you could hook into the build process and easily generate a Grails template that just contains the output of one of the above commands.

This recreated grails-app/views/_version.gsp upon each build, so we’re sure to have always the most recent revision ids there. It is crucial that the file containing the revision information is itself not under version control. To exclude this file you have to list it in .hgignore, .gitignore or use svn propedit svn:ignore.

Using the _version.gsp template

The final step is to embed the previously created _version.gsp somewhere in your code. For my usecase, I want to have the revision ids available on each and every page, so I’ll put it into the layout template grails-app/views/layout/main.gsp:

Be sure not to omit the leading “/” in the g:render tag, otherwise _version.gsp gets not found in case of a deeper nested view path.

a perfect team: Grails Taggable plugin and JQuery Tagit

In a recent Grails project the customer asked for support of a tagging functionality for some domain classes. In order not to clutter the tagspace too much auto-complete should be available when editing the tags.

In fact there is a very simple and elegant solution for this. On the application’s side, there’s the Grails Taggable plugin available. For the frontend side JQuery has a nice plugin called  Tagit plugin caring about editing tags and auto-completion. Both play together very well – showing this is the intention of this post.

Setting up the ‘to-be-tagged’ domain class

After installing the taggable plugin the usual way using

setting up the ‘to-be-tagged’ domain classes is fairly trivial, the only thing left is to add ‘implements Taggable’ to the ‘to-be-tagged’ domain classes, e.g.

By marking the domain class with the taggable interface it gets injected some methods for manipulating its tags on instance level

  • addTag,
  • addTags,
  • getTags,
  • parseTags,
  • removeTag,
  • setTags

as well as some new methods on class level:

  • getAllTags,
  • getTotalTags,
  • countByTag.

Setting up JQuery Tagit in the Grails application

Since the Tagit plugin depends on JQueryUI for autocompletion, lets first install this in the application. Using the resources plugin for managing our css/js/image resources is also a good idea:

Download an unzip the latest version of tagit (1.5 when authoring this post) to some temporary location. We basically need to copy three files contained in the zip:

  • tagit/js/tagit.js to <grailsapp>/web-app/js
  • one of tagit/css/tagit-<yourchoice>.css and tagit/css/ui-anim_basic_16x16.gif to <grailsapp>/web-app/css

Since we’ve added resources to our project let’s declare them as a module for the resources plugin. For more information on this concept, checkout the docs of the Grails resources plugin.

Editing the view

Next thing is the frontend. To get started, let’s generate a controller and views for the given domain class:

For simplicity, we’ll only care about the edit view for the rest of this post. The code of the generated view is the starting point. First we need to make use of the declared resources and second we need to render the already existing tags and apply the tagit plugin.

$(function() { $(“ul[name=’tags’]”).tagit({select:true, tagSource: “${g.createLink(action: ‘tags’)}”}); });


  • ${it}

L.3 adds the js/css resources. L.9 is requires some explanation, we’re decorating the ul tag having an attribute name='tags' with the tagit widget. The parameter select=true is crucial since it passes back the chosen tags upon form submission as a multivalued select-box. Specifying a tagSource URL provides auto-completion. In l.15-19 we’re displaying the existing tags in a simple unordered list. N.B. the name attribute mirrors the name of the select-box being created.

Editing the controller

The ProductController must be modified to store given tags upon form submission and to provide auto-completion. For storing tags, the update action requires a single line change:

tags isn’t a real property it is not covered by l.69 and an explicit call to setTags() is necessary.

For auto-completion a new action tags is introduced:

JQuery-UI auto-completion passes the partially entered tag in request parameter term. The code above searches for all tags starting with the given term and returns their name as JSON.

Result & Conclusion

With these very few lines of code a comfortable user interface for tagging with auto-completion could be established. Kudos to the authors of the JQuery Tagit and Grails Taggable plugins. These two plugins are a perfect match.

Grails Searchable plugin: fighting down OOME when rebuilding the search index

In one of my projects we store blob data (word documents, pdfs,…) in a Grails domain class. This data should all be indexed by a search engine and provide a convenient search interface. Pretty easy to solve using the Grails Searchable plugin – customer satisfied.

The project went live, everything was fine the first time. Until a certain point, we found that rebuilding the index throwed OutOfMemoryException (OOME). Nothing unusual in the java world,  increasing -Xmx helped out for some time.

With a growing set of data we reached a point where -Xmx comes near the size of physical RAM in the machine. Plugging more RAM is not an option here, so I’ve decided to tackle down the cause of this.

After some debugging session I’ve found out that rebuilding the index is performed in batches. Grails Searchable uses the Compass Framework under the hood. Compass  uses a default batch size of 200. For whatever reason the Grails searchable plugin superseeds that to a fixed (!) value of 5000. This means that during indexing 5000 database rows (each one holding a megabyte-sized blob) are read into RAM and then stored in the index! As long as there are no blobs in the database 5000 might be a good value, the larger the batch size the faster indexing will work.

The best solution here would be a configuration parameter for the fetchCount, I’ve filed an JIRA for this. Until this is fixed, thers a workaround: reconfigure the compassGpsDevice bean in the application’s resources.groovy like this

Mission Accomplished.

using Redmine with IntelliJ X EAP

Since the times when I’ve started using Grails some years ago, I became a passionate user of IntelliJ IDEA. Basically the single one thing I’ve been missing when moving over from Eclipse was the lack of something like Mylyn. Since version 9, IntelliJ comes up with basic task and context management features. Support for Jira has always been great by a plugin from Atlassian.  Redmine is the also a great issue tracker/wiki/project management application. But there was no IDE integration into IntelliJ so far. The upcoming IntelliJ X version has support for this in their latest EAP.

It took me some time to figure out how that works, so I want to share what I’ve found out so far:

  • go to File|Settings dialog, select Tasks|Servers
  • add a redmine server

    IntelliJ settings dialog

    The API Token must be taken from the “My account” page, link “API Access Key”. The project ID is the short project identifier found on Redmine’s project settings page

  • test and validate the connection
  • apply the changes in settings dialog
  • Open a new task (Alt-Shift-N)
  • Enter either the id or a word contained in the issue’s title and press Crtl-Space to find matching issues from redmine.
  • Select one of the issues being found and create a new context and changelist for that one.

Having the redmine tasks in the IDE will be a big time safer for me.


If your redmine server uses https with a self-signed certificate, you must append the certifacte to JVM’s keystore:

Grails countries plugin 0.2 released

Thanks to the contributions of other hackers I’m announcing the 0.2 release of the Grails countries plugin. The changes:

  • added languages for country and continent names:
  • country list is now maintained outside CountryBootstrap.groovy in seperate csv files
  • reworked properties file to consistently use ISO-3166 3-letter-code as key