September, 2009


25
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
  exit
  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.


21
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 {
    grailsHome()
    mavenCentral()

    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()
    ivySettings.defaultInit()
    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…

mavenLocal()

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…

mavenLocal(“/opt/maven/repository”)

Grails 1.2 is beginning to look very exciting.


7
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();
      requiredFields.add("date");
      return requiredFields;
    }

    public List getOptionalFields() {
      List optionalFields = new ArrayList();
      optionalFields.add("time");
      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 = {
    propertyEditorRegistrar(CustomPropertyEditorRegistrar)

    // .... 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.


2
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.