Sunday, 3 April 2011

Language Translator as XPATH query

In this blog I’ll explain how to use Google language translator API in custom XPATH function for interaction with any database with different language apart from English.

Before starting you need to download two jar file, Json_simple-1.1.jar and Google-api-translate-java.jar.

Create a java file CustomExtensions like below,


package com.shrik.ws.xslt;


import com.google.api.translate.Language;
import com.google.api.translate.Translate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class CustomExtensions {
    // sample method

    public static String helloCustomXSLT(String value) {

        return "Hello " + value;
    }
    //language translator

    public static String googleTranslationService =
        "http://ajax.googleapis.com/ajax/services/language/translate";


  

    public static String translateString(String sourceString,
                                         String sourceLanguage,
                                         String targetLanguage) {
        HttpURLConnection connection = null;
        OutputStreamWriter wr = null;
        BufferedReader rd = null;
        StringBuilder sb = null;
        String line = null;

        URL serverAddress = null;

        try {
            serverAddress =
                    new URL(googleTranslationService + "?v=1.0&&q=" + sourceString.replace(' ',
                                                                                           '+') +
                            "&&langpair=" + sourceLanguage + "%7C" +
                            targetLanguage);
            //set up out communications stuff
            connection = null;

            //Set up the initial connection
            connection = (HttpURLConnection)serverAddress.openConnection();
            connection.setRequestMethod("GET");

            connection.setDoOutput(true);
            connection.setReadTimeout(10000);

            connection.connect();

            //get the output stream writer and write the output to the server
            //not needed in this example
            //wr = new OutputStreamWriter(connection.getOutputStream());
            //wr.write("");
            //wr.flush();

            //read the result from the server
            rd =new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();

            while ((line = rd.readLine()) != null) {
                sb.append(line + '\n');
            }

            return (extractTranslationFromJSON(sb.toString()));

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //close the connection, set all objects to null
            connection.disconnect();
            rd = null;
            sb = null;
            wr = null;
            connection = null;
        }
        return null;
    }
  public static String extractTranslationFromJSON(String response) {
      final JSONObject jsonObj = (JSONObject)JSONValue.parse(response);
      String translation = null;
      if (jsonObj != null && jsonObj.containsKey("responseData")) {
          final JSONObject responseData =
              (JSONObject)jsonObj.get("responseData");
          translation = responseData.get("translatedText").toString();
      }
      return translation;
  }


   /*
      public static String translate(String sourceString, String sourceLanguage,
                                   String targetLanguage) {
        return extractTranslationFromJSON(translateString(sourceString,
                                                          sourceLanguage,
                                                          targetLanguage));

    }

    public static String googleTranslateAPI(String sourceString, String sourceLanguage,
                                            String targetLanguage ) throws Exception {
                                              Translate.setHttpReferrer(googleTranslationService);
      
            return  Translate.execute("Hello World", Language.ENGLISH, Language.GERMAN);
       
    }
    */ 
}


Then unzip the above two jars and add it in your classes directory, for Json_simple-1.1.jar add root org package and for Google-api-translate-java.jar add google and tecnick under com package.Create a META-INF folder under classes and create ext-mapper-xpath-functions-config.xml file underneath as below,

<soa-xpath-functions version="11.1.1"
                     xmlns="http://xmlns.oracle.com/soa/config/xpath"
                     xmlns:customXSLT="http://www.oracle.com/XSL/Transform/java/com.shrik.ws.xslt.CustomExtensions">
 
 
  <function name="customXSLT:helloCustomXSLT">
      <className>com.shrik.ws.xslt.CustomExtensions</className>
      <return type="string"/>
      <params>
        <param name="value" type="string"/>
      </params>
      <desc/>
      <detail>
        <![CDATA[This function returns the value prefixed by a complex Hello statement.]]>
      </detail>
  </function>
 
  <function name="customXSLT:translateString">
      <className>com.shrik.ws.xslt.CustomExtensions</className>
      <return type="string"/>
      <params>
        <param name="value1" type="string"/>
        <param name="value2" type="string"/>
        <param name="value3" type="string"/>
      </params>
      <desc/>
      <detail>
        <![CDATA[This function returns the translated value . It takes 3 input parameters, source,sourceLn,destLn.]]>
      </detail>
  </function> 
 
</soa-xpath-functions>

Create a jar deployment profile in your Jdeveloper and filter classes as below (this give you also snapshot of class hierarchy)

image
Then deploy to jar file and add the same to soa under preference menu of Jdeveloper,

image

Restart the Jdeveloper and create a sample xslt file,under user defined function you will find yours,

image

Then use it by providing any word to translate ,source language and destination language,

image

Test the XSLT and you will get the desired output,

image

image

To make the XPATH available at runtime please follow the last section of http://shrikworld.blogspot.com/2011/03/errorhandling-in-soa-11g.html.

1 comment:

joseph taxton said...

Nothing novel about any of this, that's what good translation is all about on Personal Archives - Anthony Teixeira - Professional French Translator.