One of the most requested features for groovyblogs is the ability to filter posts by language. Well I’ve been working hard to get this implemented. I wrote ages ago how the first version used the Textcat classification library to do some of the heavy lifting, which worked fine, but only had a small set of languages.

I was mentioning this to my buddy Sven and he suggested I checkout the Google translation AJAX APIs that are now available - and even sent me a code snippet to get me going.

Turns out that accessing these services from Grails is a total snack. Here’s a complete worked example of how you can integrate both language detection and translation in a tiny amount of Groovy code (feel free to cut and paste into your local groovyConsole and take for a spin):


def text =  'das ist ein test'.encodeAsURL()

def detect = 'http://www.google.com/uds/GlangDetect?v=1.0&q=' + text
def response = grails.converters.JSON.parse(detect.toURL().text)

println "Lang is: ${response.responseData.language}"

def targetLang = "en"
def translate = "http://www.google.com/uds/Gtranslate?v=1.0&q=" + text +
    "&langpair=${response.responseData.language}%7C${targetLang}"
def response2 = grails.converters.JSON.parse(translate.toURL().text)

println "Translation is: ${response2.responseData.translatedText}"

Which gives you the expected output of:

Lang is: de
Translation is: This is a test

Cute stuff! Language detection and translation in just a few lines! Coming soon to a groovyblogs near you…