Wednesday, January 24, 2007

Grails' new dynamic encoding

Grails' dynamic encoding is something really useful and will be available in the upcoming Grails 0.4.

Right now it only has 2 standard codec -- HTMLCodec and URLCodec. I want to show you how easy it is to create a custom codec of your own here. Lets take Base64 encoding and decoding for this example.

We start by creating the basic codec class, Base64Codec.groovy and define 2 methods; encode and decode.


class Base64Codec {

static def encode = { str ->
// TODO: Implement me
}

static def decode = { str ->
// TODO: Implement me
}
}

So far so good. Grails will automatically pick up your custom codec as long as your class ends with a "Codec", like this Base64Codec.groovy for example. Well of course you need to put this class in grails-app/util folder.


class Base64Codec {

static def encode = { str ->
return new sun.misc.BASE64Encoder().encode(str.bytes)
}

static def decode = { str ->
def result = new sun.misc.BASE64Decoder().decodeBuffer(str)
return new String(result)
}
}


//Encoding string to Base64: someString.encodeAsBase64()
//Decoding Base64 string: def s = encodedString.decodeAsBase64()
A word of warning, you are not supposed to use those Sun's undocumented classes. Try something like Apache Commons Codec library for Base64 encoding and decoding.

No comments: