Category Archives: tech

Better structured date editor for Grails

It’s really surprising and annoying that the default structured editor for dates and times in Grails is so limited. It only allows one to edit (or enter) time information down to the minute. Seconds and smaller are ignored, even though the editor specifically returns an epoch time in milliseconds with the getTime() method! The default editor also only works for java.util.Date and java.sql.Date — not the also common java.sql.Timestamp.

I’ve created a new editor that works for all 3 types mentioned and allows one to edit/enter more complete time information, including seconds (yeah!), millisecond or nanosecond, and also allows the use of an “epoch” time field to edit a raw integer.

See the editor code at (GitHub) or download

I setup the editor in my own registrar class, e.g. src/groovy/mypackage/CustomPropertyEditorRegistrar.groovy where I make several editor customizations:

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import java.beans.PropertyEditor;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.math.BigDecimal;
import java.util.Locale;
import edu.ucar.eol.spring.SqlTimestampPropertyEditor;
import edu.ucar.eol.grails.StructuredDateOrTimestampEditor;

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
  public void registerCustomEditors(PropertyEditorRegistry registry) {
    registry.registerCustomEditor(java.sql.Timestamp.class, new StructuredDateOrTimestampEditor());
    registry.registerCustomEditor(java.util.Date.class, new StructuredDateOrTimestampEditor());
    registry.registerCustomEditor(java.sql.Date.class, new StructuredDateOrTimestampEditor());

and then register the bean with Spring
in grails-app/conf/spring/resources.groovy :

beans = {

Finally, to make use of it you’ll need the proper HTML in your view. I’m also using Joda time, and modified the Grails plugin’s taglib at DateTimeTagLib.groovy (GitHub) or download DateTimeTagLib.groovy

It has all worked great so far.

Sorry, I don’t have any real tests but here are some things you can try in your grails shell :

sed = new net.sinequanon.grails.StructuredDateOrTimestampEditor("yyyy-MM-dd HH:mm:ss.S")

ts = sed.assemble(java.sql.Timestamp, [epoch:'1'])
===> 1970-01-01 00:00:00.001

ts = sed.assemble(java.sql.Timestamp, [:])
===> null

ts = sed.assemble(java.sql.Timestamp, [year:'2014', millisecond:'123'])
===> 2014-01-01 00:00:00.123

ts = sed.assemble(java.sql.Timestamp, [year:'2014', nanosecond:'456'])
===> 2014-01-01 00:00:00.000000456

// nanosecond takes precedence over millisecond
ts = sed.assemble(java.sql.Timestamp, [year:'2014', millisecond:'123', nanosecond:'456'])
===> 2014-01-01 00:00:00.000000456

ts = sed.assemble(java.sql.Timestamp, [year:'2014', epoch:'5', millisecond:'123'])
===> 1970-01-01 00:00:00.005

// epoch is milliseconds and sets the time before nanosecond overwrites the fractional portion
ts = sed.assemble(java.sql.Timestamp, [year:'2014', epoch:'5', nanosecond:'456'])
===> 1970-01-01 00:00:00.000000456


mysql history munging

At work, I run the mysql clients on multiple hosts with multiple versions. My home directory is a network mount and thus my .mysql_history file is shared between all these hosts. Often the command history gets weirdly munged, with spaces converted to \040 — the character sequence for the octal escape code for ASCII space. Here’s a little workaround/fix:

/bin/sed 's/\\040/ /g;' ~/.mysql_history > ~/
/bin/mv -f ~/ ~/.mysql_history

Make that into an alias or script. Just make sure you quit all instances of the mysql client before running. Then when you restart, the history should get reloaded correctly.

I haven’t bothered to figure out why this is happening, i.e. what the version problems are or 32/64 bit or readline/editline or the sequence of starting multiple clients on multiple hosts…

Grails plugin CKEditor with aspell

Here’s an info dump of some things I did to get Linux aspell-based spell checking working with the Grails CKEditor plugin.


ckeditor {
    config = "/js/ckeditor/ckconfig.gsp" // CKEDITOR.config.customConfig ; note the gsp extension


<%@ page contentType="text/javascript" %>


//CKEDITOR.plugins.addExternal('aspell', '${request.contextPath}/js/ckeditor/plugins/aspell/');
CKEDITOR.plugins.addExternal('aspell', '${resource(dir:"js/ckeditor/plugins/aspell/")}');

CKEDITOR.editorConfig = function( config )
    config.removePlugins = 'filebrowser,ofm,flash,save,font';
    config.extraPlugins = 'aspell';

    config.toolbar_zinc =
                { name: 'document', items : [ 'Bold', 'Italic', 'NumberedList', 'BulletedList', 'Blockquote', 'Subscript', 'Superscript', 'SpecialChar', '-', 'RemoveFormat' ] },
                { name: 'tools', items : [ 'Source', 'ShowBlocks', '-', 'About', 'Maximize' ] },
                { name: 'clipboard', items : [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
                { name: 'editing', items : [ 'Find', 'Replace', '-', 'SelectAll', '-', 'SpellCheck' ] },


Get aspell.7z, system pacakges aspell and aspell-en (or your language), and CKEditor plugin aspell. Add the following:


oSpeller.spellCheckScript = editor.plugins.aspell.path+'spellerpages/server-scripts/spellchecker.jsp';

Documented in another post about spellchecker

CKEditor spellchecker.jsp

Here is a JSP version of the server-side script needed for the CKEditor plugin for aspell. It was inspired by/based upon a post in the forums. I’ve made some mods to get it to work, be more complete, and be more like the current perl version, with fixes recommended in the main thread. It’s not fully tested but hopefully it will help somebody.

Note that for best results, you will need Apache Commons Lang. You can comment out that code but then you’ll get false-positive misspellings of partial words before and after the HTML entities.

Install the attached file as .../aspell/spellerpages/server-scripts/spellchecker.jsp


Grails standalone classes need package

I was reminded again today that standalone classes in Grails must belong to a package. That is, a class in src/groovy or src/java needs to be in a package. For example:

file: src/groovy/mypackage/MyClass.groovy

package mypackage
class MyClass { ... }

If the class is without a package (appearing as src/groovy/MyClass.groovy), it will compile correctly but no Grails classes (like your controller or service) will be able to find it, generating an org.codehaus.groovy.control.MultipleCompilationErrorsException with the message unable to resolve class MyClass

GORM nullables and unsaved transient instance

I have nullable one-to-many relations in Grails/GORM and started getting “object references an unsaved transient instance” exceptions from Hibernate. In the Grails forms, selecting a blank/no-selection value for the field sent''. GORM then tries to create a new empty object and during the save(flush:true), it complains with the exception:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: MyOtherClass

This stackoverflow answer gave me the clue about params and I now remove the nullable field from params when it’s blank.

def myObject = MyClass.get(
if (null == || '' == {
        myObject.myOtherObject = null
        } = params
if (!myObject.hasErrors() && true)) {

Groovy (Grails) markup builder for select/option menu

I was trying to use the Groovy XML MarkupBuilder to have Grails output an HTML fragment for an AJAX call and just couldn’t get it to work. I wanted to generate an HTML select/option menu from a list of lists:

assert results == [[null,null], [17, 'foo'], [42, 'bar'], [69, 'bahz']]

(That list was returned from a Hibernate Criteria Builder with some specialized projections.)

First I tried to do it simply, following Grails docs:

render {
  select(size:10) {
    results.each {
      if (it[0] && it[1])
        option( value:it[0], it[1] )

I kept getting a blank list. Eventually I figured out that the Grails GSP select tag was interfering with the markup builder DSL, so I tried using that, with list access code in a closure in a GString expression:

render { from:results, optionKey:"${{it[0]}}", optionValue:"${{it[1]}}"

Except that both expressions are in the same block and share “it”. So we have to use different explicit closure parameters:

render { from:results, optionKey:"${{itk -> itk[0]}}", optionValue:"${{itv->itv[1]}}"

but that fails with an error like:

No signature of method: is applicable for argument types: (java.lang.Integer) values: [0] Possible solutions: getAt(java.lang.String)

so I tried making the indices into strings:

render { from:results, optionKey:"${{itk -> itk['0']}}", optionValue:"${{itv->itv['1']}}"

which resulted in the error:

No such property: 0 for class:

The Grails docs give the example
which makes it seem like real code is available. But the “itk”/”itv” closure parameters apparently aren’t *really* the list values, which would happily accept the Groovy magic Object.getAt() method.

Something like this seemed to work:

render { builder ->,onchange:"myJsFunc(this);") {
  results.each {
    if (it[0] && it[1])
      option( value:it[0], it[1] )

If you’re in Grails (and not just straight Groovy), really try to use a view for this!