vikassharma27 / google-api-translate-java

Automatically exported from code.google.com/p/google-api-translate-java
0 stars 0 forks source link

JSON class cast exception when retrieving translation #57

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Hi,
I am trying to translate content which has a size of 8764 bytes. I am 
getting following error after translation.

java.lang.Exception: [google-api-translate-java] Error retrieving 
translation.
    at com.google.api.translate.Translate.retrieveTranslation
(Translate.java:66)
    at com.google.api.translate.Translate.translate(Translate.java:26)
    at com.translate.utils.CiCreator.copyTranslatedAttrs
(CiCreator.java:214)
    at com.translate.utils.CiCreator.createCi(CiCreator.java:127)
    at jsp_servlet._jsp.__cicreator._jspService(__cicreator.java:148)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:33)
    at 
weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run
(ServletStubImpl.java:1077)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet
(ServletStubImpl.java:465)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet
(ServletStubImpl.java:348)
    at 
weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run
(WebAppServletContext.java:7047)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs
(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs
(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet
(WebAppServletContext.java:3902)
    at weblogic.servlet.internal.ServletRequestImpl.execute
(ServletRequestImpl.java:2773)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:224)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:183)
Caused by: java.lang.ClassCastException: org.json.JSONObject$Null
    at com.google.api.translate.Translate.retrieveTranslation
(Translate.java:61)
    ... 15 more

Since the default Translate.java code uses GET method, which has size 
restrictions, to submit the text for translation, I changed the code to 
use POST method for submitting the text. I get this ClassCastException 
error now. I am pasting my code at the end for reference ( I am not able 
to attach the file). Am I doing anything incorrect in my code?

Is there a limitation on the size of text for translation? How to overcome 
that? FYI, I am submitting rich text (html) and contains tags like <br> 
and <p> tags. The style information should not be lost in the translation. 
Can someone please help me in fixing this issue?

Regards,
Pratap

========================================================================
=======================code begins=====================================

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   Translate.java

package com.google.api.translate;

import com.tecnick.htmlutils.htmlentities.HTMLEntities;
import java.io.*;
import java.net.*;
import org.json.JSONObject;

// Referenced classes of package com.google.api.translate:
//            Language

public class Translate
{

    public Translate()
    {
    }

    public static String translate(String text, String from, String to)
        throws Exception
    {
        return retrieveTranslation(text, from, to);
    }

    private static String retrieveTranslation(String text, String from, 
String to)
        throws Exception
    {
        if(!Language.isValidLanguage(from) || !Language.isValidLanguage
(to) || "".equals(to))
            throw new IllegalArgumentException("You must use a valid 
language code to translate to and from.");
        HttpURLConnection uc;
        StringBuffer url = new StringBuffer();
        //http://translate.google.com/translate_t
        url.append
("http://ajax.googleapis.com/ajax/services/language/translate");

        uc = (HttpURLConnection)(new URL(url.toString())).openConnection();
        //System.out.println
("====HttpURLConnection===="+uc.getRequestMethod());
        uc.setRequestMethod("POST");
        StringBuffer data = new StringBuffer("v=1.0");//
        data.append("&langpair=").append(from)
            .append("%7C")
            .append(to)
            .append("&q=").append(URLEncoder.encode(text, "UTF-
8"));//&q

        String s;
        OutputStreamWriter wr = null;
        try
        {           
            System.out.println("====posting 
data===="+data.length());
            uc.setDoOutput(true);
            wr = new OutputStreamWriter(uc.getOutputStream());
            wr.write(data.toString());
            wr.flush();
            String result = toString(uc.getInputStream());
            //System.out.println("====result===\n"+result);
            JSONObject json = new JSONObject(result);
            String translatedText = ((JSONObject)json.get
("responseData")).getString("translatedText");
            s = HTMLEntities.unhtmlentities(translatedText);
        }
        catch(Exception ex)
        {        
            throw new Exception("[google-api-translate-java] 
Error retrieving translation.", ex);
        }
        finally
        {
            uc.getInputStream().close();
            if(uc.getErrorStream() != null)
                uc.getErrorStream().close();
            if(wr!=null)
                wr.close();
        }        

        return s;
    }

    private static String toString(InputStream inputStream)
        throws Exception
    {
        StringBuffer outputBuilder = new StringBuffer();
        try
        {
            if(inputStream != null)
            {
                BufferedReader reader = new BufferedReader(new 
InputStreamReader(inputStream, "UTF-8"));
                String string;
                while((string = reader.readLine()) != null) 
                    outputBuilder.append(string).append('\n');
            }
        }
        catch(Exception ex)
        {
            throw new Exception("[google-api-translate-java] Error reading 
translation stream.", ex);
        }
        return outputBuilder.toString();
    }

    private static final String ENCODING = "UTF-8";
    private static final String URL_STRING 
= "http://ajax.googleapis.com/ajax/services/language/translate?
v=1.0&langpair=";
    private static final String TEXT_VAR = "&q=";
}

=============================Code ends=====================================
===========================================================================

What steps will reproduce the problem?
1.
2.
3.

What is the expected output? What do you see instead?

What version of the product are you using? On what operating system?

Please provide any additional information below.

Original issue reported on code.google.com by pratapma...@yahoo.com on 23 Jun 2009 at 3:41

GoogleCodeExporter commented 8 years ago
[deleted comment]
GoogleCodeExporter commented 8 years ago
Did you solve the problem i am having same issue.

Original comment by sko...@gmail.com on 25 Sep 2009 at 5:27

GoogleCodeExporter commented 8 years ago
As we use POST in the library now hopefully this will be fixed for you?

Original comment by rich.mid...@gmail.com on 20 Nov 2009 at 8:19

GoogleCodeExporter commented 8 years ago
I am facing the same problem of class cast , have you solved it. If so, please 
share solution of this problem JSON class cast exception when retrieving 
translation

Original comment by mhd.fa...@gmail.com on 26 Apr 2012 at 3:31