Could Not Run Sketch (Target VM Failed to Initialize)

edited February 2016 in Library Questions

Having some problems with running this sketch in Processing. Can anyone tell me what I'm doing wrong?

public class GoogleTranslate {

private String key;

public GoogleTranslate(String apiKey) {
    key = apiKey;
}

String translate(String text, String from, String to) {
    StringBuilder result = new StringBuilder();
    try {
        String encodedText = URLEncoder.encode(text, "UTF-8");
        String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + key + "&q=" + encodedText + "&target=" + to + "&source=" + from;

        URL url = new URL(urlStr);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        InputStream stream;
        if (conn.getResponseCode() == 200) //success
        {
            stream = conn.getInputStream();
        } else
            stream = conn.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        JsonParser parser = new JsonParser();

        JsonElement element = parser.parse(result.toString());

        if (element.isJsonObject()) {
            JsonObject obj = element.getAsJsonObject();
            if (obj.get("error") == null) {
                String translatedText = obj.get("data").getAsJsonObject().
                get("translations").getAsJsonArray().
                get(0).getAsJsonObject().
                get("translatedText").getAsString();
                return translatedText;

            }
        }

        if (conn.getResponseCode() != 200) {
            System.err.println(result);
        }

    } catch (IOException ex){
      System.err.println(ex.getMessage());

    } catch (JsonSyntaxException ex) {
        System.err.println(ex.getMessage());
    }

    return null;
}
public void main() {

    GoogleTranslate translator = new GoogleTranslate("APIKEY");
    String text = translator.translte("How are you. I am fine", "en", "de");
    System.out.println(text);
}

}

Tagged:
Sign In or Register to comment.