Sep 09

Installing couchdb on Snow Leopard

Usually the process is pretty easy. If you have MacPorts, and if you don’t, I recommend you get it, you just type sudo port install couchdb.

With Snow Leopard, this installation is a bit broken. The port install works, but then you get an exception, something like Trace/BPT trap. It’s not really due to CouchDB, but rather one of its dependencies, SpiderMonkey (Mozilla’s embeddable JS engine written in C).

So here is a simple solution…

  sudo port install couchdb
  sudo port uninstall -f spidermonkey
  cd /tmp
  curl -O http://ftp.mozilla.org/pub/mozilla.org/js/js-1.7.0.tar.gz
  curl -O http://svn.macports.org/repository/macports/trunk/dports/lang/spidermonkey/files/patch-jsprf.c
  tar xvzf js-1.7.0.tar.gz
  cd js/src
  patch -p0 -i ../../patch-jsprf.c
  make -f Makefile.ref
  sudo su
  JS_DIST=/usr/local/spidermonkey make -f Makefile.ref export
  sudo ranlib /usr/local/spidermonkey/lib/libjs.a
  # if you get an error here, ignore it

  sudo ln -s /usr/local/spidermonkey/include /usr/local/include/js
  sudo ln -s /usr/local/spidermonkey/lib/libjs.dylib /usr/local/lib/libjs.dylib
  # If you're feeling saucey, the js shell can be useful for quick syntax checking and the like.
  sudo ln -s /usr/local/spidermonkey/bin/js /usr/local/bin/js

That’s it, you should be able to do sudo couchdb and it should run startup fine.

Let me know if you find any issues during this install and/or after.

Sep 09

Grails 1.2 dependency management

Grails 1.2 comes with a great dependency management. You no longer have to manually manage the dependencies and don’t have to resort to using maven for this task. Grails uses Apache Ivy under the hood for transitive dependency management. Ivy allows to set up multiple resolvers and resolution patterns though allowing you to adapt to maven repositories and many other, even custom repository schemes. Grails takes it a step further and allows you to do this with a pretty nice looking DSL.

Application dependencies are configured in BuildConfig.groovy file and they look something like this…

grails.project.dependency.resolution = {
  inherits "global" // inherit Grails' default dependencies
  log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
  repositories {

    mavenRepo "http://download.java.net/maven/2/"
    mavenRepo "http://repository.jboss.com/maven2/
  dependencies {
    // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
    runtime 'com.mysql:mysql-connector-java:5.1.5'

By default, grails pulls dependencies from your grails installation library. You can also uncomment (as you see above), the mavenCentral() repository. These are the defaults and don’t require any more configuration. You can also specify a custom maven-compatible repo URL using mavenRepo.

There is also a flat dir resolver, allowing you to resolve dependencies to some local directory. You can do this as:

flatDir name: ‘localRepo’, dirs:’/some/path/to/repo’

So I naively tried using flatDir to resolve a local maven repo, which of course didn’t work, since it’s not defined with the maven artifact resolution pattern. In order for that to work, you have to define your own resolver for now. I just submitted a patch to add a mavenLocal() resolver. Should make it to HEAD shortly.

So, for now, you can do

  private org.apache.ivy.plugins.resolver.DependencyResolver createLocalMavenResolver() {
    def localMavenResolver = new FileSystemResolver();
    localMavenResolver.local = true
    localMavenResolver.name = "localMavenResolver"
    localMavenResolver.m2compatible = true
    localMavenResolver.addArtifactPattern "${userHome}/.m2/repository/[organisation]/[module]/[revision]/[artifact]-[revision](-[classifier]).[ext]"
    def ivySettings = new IvySettings()
    localMavenResolver.settings = ivySettings
    return localMavenResolver

Then use this method as…

resolver createLocalMavenResolver()

resolver method basically allows you to specify your own Ivy resolver. But that seems like too much work for something as common as local maven repo, especially since anyone who’s going to use maven dependency artifacts, probably will install some locally.

So once the patch makes it in, you can just uncomment…


By default this resolver will resolve dependencies in home_dir/.m2/repository, but you can also specify your own path to the repository by just passing it as an argument…


Grails 1.2 is beginning to look very exciting.

Sep 09

Grails multi-control property editor implementation

Data binding using current frameworks, Spring, Grails, etc… usually provide a way to marshal/unmarshal input control data into data types. The frameworks usually transparently handle the most common datatypes and allow you to configure/implement others. That process is pretty straightforward and in many cases trivial. When using Spring MVC, for example, one would extend java.beans.PropertyEditorSupport and implement the setAsText and maybe getAsText methods.

I think this handles a large portion of data bindings in web applications, but there wasn’t (at least in frameworks I worked with), a straightforward/reusable way of binding multiple html fields to one data type. I’ve always either had to roll my own custom solution and/or rely on a command (transfer) objects to have a one to one representation of form fields, which I would then bind to the domain object inside a controller action. Some use cases can really benefit from command objects and its decoupling from the domain, but I try to bind directly to domain objects as much as I can, reducing the amount of noise that transfer objects generate. Another solution which I’ve personally never implemented because I thought it was too ugly and leaked too much domain binding implementation into the view layer, was to use a hidden field and then format the multi-field controls into a single text value representation during a submit event, though allowing you to still have a one to one binding between the hidden control and the domain object field.

Today I discovered Grails StructuredPropertyEditor, and after figuring out how to implement it, I was on my way to reducing a bunch of binding boilerplate. This solution is not documented, as many other grails related intricacies, though it does seem like a stable/supported API. After digging through the source code, I figured it out and wanted to share it. So here it is…

I have a form which collects date and time information. The date uses a custom datepicker control and the time uses a custom time control. So two controls, that I need to marshal into one DateTime field in my domain class.

We start off by implementing a custom property editor, which extends PropertyEditorSupport and implements a grails specific StructuredPropertyEditor interface. I decided to use an excellent DateTime implementation class which comes with Joda Time library to store the date/time information. You can easily use any other type of your liking, including the java.lang.Date class.

  public class DateTimePropertyEditor extends PropertyEditorSupport implements StructuredPropertyEditor {

    DateTimeFormatter dateTimeFormat;

    public DateTimePropertyEditor(String format) {
      this.dateTimeFormat = DateTimeFormat.forPattern(format);

    public List getRequiredFields() {
      List requiredFields = new ArrayList();
      return requiredFields;

    public List getOptionalFields() {
      List optionalFields = new ArrayList();
      return optionalFields;

    public Object assemble(Class type, Map fieldValues) throws IllegalArgumentException {
      if (!fieldValues.containsKey("date")) {
        throw new IllegalArgumentException("Can't populate a date without a year");

      String date = (String) fieldValues.get("date");

      try {
        if (StringUtils.isBlank(date)) {
          throw new IllegalArgumentException("Can't populate date/time without a date");
        String time = (String) fieldValues.get("time");
        if (StringUtils.isBlank(time)) time = "00:00 AM";
        String dateTime = date + " " + time;

        return dateTimeFormat.parseDateTime(dateTime);
      catch (Exception nfe) {
        throw new IllegalArgumentException("Unable to parse structured DateTime from request for date.");


Now that we have the property editor defined, we should create a registrar to register it with the application.

  public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

      public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(DateTime.class, new DateTimePropertyEditor("MM/dd/yyyy hh:mm a"));

Now that we have both the property editor and its registrar, we have to declare the registrar bean in the spring beans resources file /grails-app/conf/spring/resources.groovy

  beans = {

    // .... other beans ....

That’s it, we’re done. The only thing left to do is actually create the html controls. There are a few conventions that must be followed in order for the StructuredPropertyEditor to grab the right fields.

  1. You must have a hidden field that’s there pretty much to declare the name of the field you’re binding to and also to state that it’s a ‘struct’ field, which means it’s a structured control made up of various other controls.
  2. The second rule, is that the names of the sub-fields that you are using in StructuredPropertyEditor, in our case ‘date’ and ‘time’, have to be prepended with the field name. So if the field name is ‘myField’, the sub-fields would be prepended with ‘myField_’. In our case, the html inputs should be named ‘myField_date’ and ‘myField_time’.

Here is a GSP snippet…

  <g:hiddenField name="startTime" value="struct" />
  <g:textField name="startTime_date"/>
  <g:textField name="startTime_time"/>

Notice how the field we’re binding is ‘startTime’ and the sub-fields that make up the whole, are ‘startTime_date’ and ‘startTime_time’ linked to ‘date’ and ‘time’ fields used in the assembly of the final field.

Now, all you have to do in the controller, is bind as you usually would, in my case…

bindData(domainObj, params)

That’s it, quick and simple and you have reusable marshaling of multi-control data types.

Sep 09

GORM custom id mapping

I’m not sure why this is so undocumented. There is documentation about all these options, but you must collect them all from different sections. So I figured I’ll document it here for the sake of people finding it, before they post it to the grails users list for the thousandth time never really getting a straightforward response it seems.

GORM defaults to using ‘id’ field as the primary key, so it injects it if you don’t explicitly define it. You can easily change its type from Long to say String, but some Hibernate baggage follows. Basically, anything outside of the default Long id will not work, unless you also map is as an ‘assigned’ id, though hibernate will not try to automatically assign a long id during persistence of a new object. There are also cases that besides the type changes, you want to have the field name something else. I mean, when you have a User class, you might want to refer to its primary key as username and not just a plain generic id.

Here is how you completely remap the primary field (non-composite).

class User {
  String username;
  String password;

  static constraints = {

  static mapping = {
    table 'users'
    id generator: 'assigned', name: "username", type: 'string'

This will allow you to use username as the primary key field on this domain class, as opposed to id. id field no longer exists and is completely replaces by a string field username. The proper database schema is also created with username column as the primary key.

Aug 09

RESTfully insane or insanely RESTful

First let me say, I love REST. I really enjoy its implementation simplicity and the fact that it’s mostly based on HTTP, for which frameworks have been developed and bullet tested for quite some time. I can’t same the same for SOAP and its convoluted related set of standards. Complexity is never good, but its especially not good when it’s not needed to accomplish a particular task at hand. That’s how SOAP and WS-* feels to me. Out of hundreds of times that I was forced to use it, there might have been a handful of valid scenarios when a simpler solution wouldn’t suffice.

So now that I got the fact that I enjoy REST out in the open, I feel that RESTful architectures need more time to evolve and develop a set of patterns. There just isn’t enough empirical information at this point to truly come up wit a set of patterns. Yes, there are books that are great and various other sources of information which help, but I wouldn’t per say call them real architectural patterns at this point, more like a set of experiences developing one or two applications that are labeled as patterns because of its buzzword status and ability to sell books. Patterns are extracted through years and years of empirical information gathering.

Today I was working on an interface, and trying to follow the good ol’ RESTful idioms to design a RESTful API for a particular service. I quickly realized that the constraints of destructive and non-destructive operations bound to particular verbs is a beauty when in its pure form, but don’t always elegantly allow you to model a use-case.

Take my use case as an example. We have a graphing services API which provides graphs to application clients. These clients can be a web front end, or any other client of choosing. Graphs take time to generate, so we want to create the graph resource on a PUT request and then expose a URI with which this graph can be accessed. Easy enough, sure, this is programming REST 101. But here is a catch. Depending on the resource, its lifecycle state changes based on various constraints. One of those resources has a constraint that it can only ever be viewed once and must be destroyed or not allowed to be accessed ever again. So for each graph request, we PUT and GET. But that means that the GET operation is now a destructible operation, which is supposedly against RESTful principals. Someone mentioned to me that such operations should be put behind a POST request, though you generate and return the resource. That’s fine, except there are constraints. If this resource is an image, which is what it is in the graph’s case, it must be embedded in the src=”uri” attribute of the image element in the html page. So can’t POST there. But even if we can use a POST in this case, what about the case where we want a resource accessed a certain amount of times, or what if we want to track the amount of time this resource is accessed, or what if accessing the resource is a stateful operation which modifies other state, whether its own resource’s state or some other resource’s state. One will say that something’s amiss here, but that’s not true. In imperative languages, state is king (not that it’s a good thing), but it’s really easy to model real world interaction scenarios. Where looking at something, or someone, changes some property about what ever you’re looking at. If a pretty lady looks at a guys (who’s a resource), his state will change or it will trigger an action, he will either perform an action, like going over and talking to the lady, or get nervous and start sweating, either one of these actions where triggered by resource view operation. Sorry, maybe it’s not the best example, but the only one that popped into my head at this time of night.

Now, you get my point? I think REST is great, but the lesson here is that you should approach it just like anything else, with caution. When you see something that can’t be done with RESTful purity, don’t beat yourself up. REST is not yet fully mature and we are yet to discover things we can and cannot do with it given today’s interpretation of what it should be. Things change with time, so just do what makes sense today.

Page 8 of 13« First...678910...Last »