Saturday, September 08, 2007

Auto-translate Resource Bundles using Google Translate

Internationalization is one of the common requirements in web applications. One of the challenges faced by a team is the non-availability of translated resource bundles during development (mostly due to logistical reasons). But it is important to test various scenarios during the application development.

In this post I will present a simple idea which utilizes Google Translate to auto-generate translated Java Resource Bundles for the language of choice. Just send a HTTP GET request with the text to be translated to Google Translate URL and read the translated text by parsing the response. In order to translate an entire resource bundle just pass a source bundle (For example, English) and read each property and write to target language resource bundle file.

Here is the URL for translating "welcome" from English to Spanish|es&text=welcome

Here is a snippet of Java code which utilizes Apache Commons HttpClient library :

String url = " langpair=en|es&text=";
String text = "welcome";

HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url + text);

String xml = getMethod.getResponseBodyAsString();
xml = xml.substring(xml.lastIndexOf("<div id=result_box dir=ltr>"));
String translated_text = xml.substring(27, xml.indexOf("</div>"));

Technorati tags: , , ,

Disqus for techtalk