Using Category in groovy

30 / Nov / 2012 by raj 2 comments

In one of my projects, I needed to save file from a particular url. I found a groovier way of doing this using category.

[java]
class FileBinaryCategory {
def static leftShift(File file, URL url) {
url.withInputStream {is ->
file.withOutputStream {os ->
def bs = new BufferedOutputStream(os)
bs << is
}
}
}
}
[/java]

Here, I created a category class and created a static method named leftShift inside it. Here is how I used the category to download the file.

[java]
File download(String address) {
def file = File.createTempFile(address.encodeAsMD5(), ".zip")
use(FileBinaryCategory) {
file << address.toURL()
}
return file
}
[/java]

A category class consists of static methods. The first argument of the method defines the type to which that method is applied. In my case, the first argument is of type File.
The advantage of using category is that it can be applied to a specific part of the code by using the use keyword.

In line 4, the static method leftShift is called and a temporary file is passed as first argument and address.toURL() is passed as the second argument. The leftShift method simply copies the content from given address to the file.

Grails provides @Category annotation to achieve the same. You can find more about it here.

Raj Gupta
raj.gupta@intelligrape.com
@rajdgreat007

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *