AI2 Component  (Version nb184)
YandexTranslate.java
Go to the documentation of this file.
1 // -*- mode: java; c-basic-offset: 2; -*-
2 // Copyright 2009-2011 Google, All Rights reserved
3 // Copyright 2011-2014 MIT, All rights reserved
4 // Released under the Apache License, Version 2.0
5 // http://www.apache.org/licenses/LICENSE-2.0
6 
7 package com.google.appinventor.components.runtime;
8 
9 import android.app.Activity;
10 
11 import android.text.TextUtils;
12 
20 
24 
27 
28 import java.io.IOException;
29 import java.io.InputStreamReader;
30 
31 import java.net.HttpURLConnection;
32 import java.net.URL;
33 import java.net.URLEncoder;
34 
35 import org.json.JSONException;
36 import org.json.JSONObject;
37 
54 @DesignerComponent(version = YaVersion.YANDEX_COMPONENT_VERSION,
55  description = "Use this component to translate words and sentences between different " +
56  "languages. This component needs Internet access, as it will request " +
57  "translations to the Yandex.Translate service. Specify the source and " +
58  "target language in the form source-target using two letter language " +
59  "codes. So\"en-es\" will translate from English to Spanish while " +
60  "\"es-ru\" will translate from Spanish to Russian. If you leave " +
61  "out the source language, the service will attempt to detect the source " +
62  "language. So providing just \"es\" will attempt to detect the source " +
63  "language and translate it to Spanish.<p /> This component is powered by the " +
64  "Yandex translation service. See http://api.yandex.com/translate/ " +
65  "for more information, including the list of available languages and the " +
66  "meanings of the language codes and status codes. " +
67  "<p />Note: Translation happens asynchronously in the background. When the " +
68  "translation is complete, the \"GotTranslation\" event is triggered.",
69  category = ComponentCategory.MEDIA,
70  nonVisible = true,
71  iconName = "images/yandex.png")
72 @UsesPermissions(permissionNames = "android.permission.INTERNET")
73 @SimpleObject
74 public final class YandexTranslate extends AndroidNonvisibleComponent {
75 
76  public static final String YANDEX_TRANSLATE_SERVICE_URL =
77  "https://translate.yandex.net/api/v1.5/tr.json/translate?key=";
78  private final String yandexKey;
79  private String userYandexKey = "DEFAULT";
80  private final Activity activity;
81 
87  public YandexTranslate(ComponentContainer container) {
88  super(container.$form());
89 
90  // Set up the Yandex.Translate Tagline in the 'About' screen
91  form.setYandexTranslateTagline();
92 
93  // TODO (user) To provide users with this component you will need to obtain a key with the
94  // Yandex.Translate service at http://api.yandex.com/translate/
95  yandexKey = "";
96  activity = container.$context();
97  }
98 
109  @SimpleFunction(description = "By providing a target language to translate to (for instance, " +
110  "'es' for Spanish, 'en' for English, or 'ru' for Russian), and a word or sentence to " +
111  "translate, this method will request a translation to the Yandex.Translate service.\n" +
112  "Once the text is translated by the external service, the event GotTranslation will be " +
113  "executed.\nNote: Yandex.Translate will attempt to detect the source language. You can " +
114  "also specify prepending it to the language translation. I.e., es-ru will specify Spanish " +
115  "to Russian translation.")
116  public void RequestTranslation(final String languageToTranslateTo,
117  final String textToTranslate) {
118 
119  if (TextUtils.isEmpty(yandexKey) &&
120  (TextUtils.isEmpty(userYandexKey) || TextUtils.equals(userYandexKey, "DEFAULT"))) {
121  form.dispatchErrorOccurredEvent(YandexTranslate.this, "RequestTranslation",
123  return;
124  }
125 
126  AsynchUtil.runAsynchronously(new Runnable() {
127  @Override
128  public void run() {
129  try {
130  performRequest(languageToTranslateTo, textToTranslate);
131  } catch (IOException e) {
132  form.dispatchErrorOccurredEvent(YandexTranslate.this, "RequestTranslation",
134  } catch (JSONException je) {
135  form.dispatchErrorOccurredEvent(YandexTranslate.this, "RequestTranslation",
137  }
138  }
139  });
140  }
141 
150  private void performRequest(String languageToTranslateTo, String textToTranslate)
151  throws IOException, JSONException {
152 
153  final String finalURL = YANDEX_TRANSLATE_SERVICE_URL +
154  ((TextUtils.equals(this.userYandexKey, "DEFAULT") ||
155  TextUtils.isEmpty(this.userYandexKey))?this.yandexKey:this.userYandexKey) +
156  "&lang=" + languageToTranslateTo +
157  "&text=" + URLEncoder.encode(textToTranslate, "UTF-8");
158 
159  URL url = new URL(finalURL);
160  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
161  if (connection != null) {
162  try {
163  final String responseContent = getResponseContent(connection);
164 
165  JSONObject jsonResponse = new JSONObject(responseContent);
166 
167  final String responseCode = jsonResponse.getString("code");
168 
169  // The translation will be in position Zero of the array returned with key 'text'
170  org.json.JSONArray response = jsonResponse.getJSONArray("text");
171  final String translation = (String)response.get(0);
172 
173  // Dispatch the event.
174  activity.runOnUiThread(new Runnable() {
175  @Override
176  public void run() {
177  GotTranslation(responseCode, translation);
178  }
179  });
180 
181  } finally {
182  connection.disconnect();
183  }
184  }
185  }
186 
193  private static String getResponseContent(HttpURLConnection connection) throws IOException {
194  // Use the content encoding to convert bytes to characters.
195  String encoding = connection.getContentEncoding();
196  if (encoding == null) {
197  encoding = "UTF-8";
198  }
199  InputStreamReader reader = new InputStreamReader(connection.getInputStream(), encoding);
200  try {
201  int contentLength = connection.getContentLength();
202  StringBuilder sb = (contentLength != -1)
203  ? new StringBuilder(contentLength)
204  : new StringBuilder();
205  char[] buf = new char[1024];
206  int read;
207  while ((read = reader.read(buf)) != -1) {
208  sb.append(buf, 0, read);
209  }
210  return sb.toString();
211  } finally {
212  reader.close();
213  }
214  }
215 
222  @SimpleEvent(description = "Event triggered when the Yandex.Translate service returns the " +
223  "translated text. This event also provides a response code for error handling. If the " +
224  "responseCode is not 200, then something went wrong with the call, and the translation will " +
225  "not be available.")
226  public void GotTranslation(String responseCode, String translation) {
227  EventDispatcher.dispatchEvent(this, "GotTranslation", responseCode, translation);
228  }
229 
238  defaultValue = "DEFAULT")
239  @SimpleProperty(description = "Set the API Key to use with Yandex. " +
240  "You do not need to set this if you are using the MIT system because " +
241  "MIT has its own key builtin. If set, the key provided here will be " +
242  "used instead")
243  public void ApiKey(String apiKey) {
244  this.userYandexKey = apiKey;
245  }
246 
247 }
com.google.appinventor.components.runtime.EventDispatcher
Definition: EventDispatcher.java:22
com.google.appinventor.components.annotations.SimpleFunction
Definition: SimpleFunction.java:23
com.google.appinventor.components.runtime.util.ErrorMessages
Definition: ErrorMessages.java:17
com.google.appinventor.components.runtime.util.ErrorMessages.ERROR_TRANSLATE_SERVICE_NOT_AVAILABLE
static final int ERROR_TRANSLATE_SERVICE_NOT_AVAILABLE
Definition: ErrorMessages.java:185
com.google.appinventor.components.runtime.util
-*- mode: java; c-basic-offset: 2; -*-
Definition: AccountChooser.java:7
com.google.appinventor.components.common.YaVersion
Definition: YaVersion.java:14
com.google.appinventor.components.annotations.DesignerProperty
Definition: DesignerProperty.java:25
com.google.appinventor.components.common.PropertyTypeConstants.PROPERTY_TYPE_STRING
static final String PROPERTY_TYPE_STRING
Definition: PropertyTypeConstants.java:237
com.google.appinventor.components
com.google.appinventor.components.runtime.YandexTranslate.ApiKey
void ApiKey(String apiKey)
Definition: YandexTranslate.java:243
com.google.appinventor.components.annotations.DesignerComponent
Definition: DesignerComponent.java:22
com.google.appinventor.components.annotations.SimpleEvent
Definition: SimpleEvent.java:20
com.google.appinventor.components.runtime.util.ErrorMessages.ERROR_TRANSLATE_JSON_RESPONSE
static final int ERROR_TRANSLATE_JSON_RESPONSE
Definition: ErrorMessages.java:186
com.google.appinventor.components.annotations.UsesPermissions
Definition: UsesPermissions.java:21
com.google.appinventor.components.runtime.YandexTranslate.YandexTranslate
YandexTranslate(ComponentContainer container)
Definition: YandexTranslate.java:87
com.google.appinventor.components.runtime.EventDispatcher.dispatchEvent
static boolean dispatchEvent(Component component, String eventName, Object...args)
Definition: EventDispatcher.java:188
com.google.appinventor.components.runtime.AndroidNonvisibleComponent
Definition: AndroidNonvisibleComponent.java:17
com.google.appinventor.components.annotations.SimpleProperty
Definition: SimpleProperty.java:23
com.google.appinventor.components.runtime.util.AsynchUtil.runAsynchronously
static void runAsynchronously(final Runnable call)
Definition: AsynchUtil.java:23
com.google.appinventor.components.runtime.ComponentContainer
Definition: ComponentContainer.java:16
com.google.appinventor.components.runtime
Copyright 2009-2011 Google, All Rights reserved.
Definition: AccelerometerSensor.java:8
com.google.appinventor.components.runtime.YandexTranslate.YANDEX_TRANSLATE_SERVICE_URL
static final String YANDEX_TRANSLATE_SERVICE_URL
Definition: YandexTranslate.java:76
com.google.appinventor.components.common
Definition: ComponentCategory.java:7
com.google.appinventor.components.runtime.util.ErrorMessages.ERROR_TRANSLATE_NO_KEY_FOUND
static final int ERROR_TRANSLATE_NO_KEY_FOUND
Definition: ErrorMessages.java:184
com.google.appinventor.components.runtime.YandexTranslate
Definition: YandexTranslate.java:74
com.google.appinventor.components.common.ComponentCategory
Definition: ComponentCategory.java:48
com.google.appinventor.components.runtime.Form.dispatchErrorOccurredEvent
void dispatchErrorOccurredEvent(final Component component, final String functionName, final int errorNumber, final Object... messageArgs)
Definition: Form.java:1011
com.google.appinventor.components.annotations.SimpleObject
Definition: SimpleObject.java:23
com.google.appinventor.components.runtime.util.AsynchUtil
Definition: AsynchUtil.java:17
com.google
com
com.google.appinventor.components.runtime.YandexTranslate.GotTranslation
void GotTranslation(String responseCode, String translation)
Definition: YandexTranslate.java:226
com.google.appinventor.components.runtime.ComponentContainer.$form
Form $form()
com.google.appinventor.components.runtime.ComponentContainer.$context
Activity $context()
com.google.appinventor.components.runtime.YandexTranslate.RequestTranslation
void RequestTranslation(final String languageToTranslateTo, final String textToTranslate)
Definition: YandexTranslate.java:116
com.google.appinventor.components.runtime.AndroidNonvisibleComponent.form
final Form form
Definition: AndroidNonvisibleComponent.java:19
com.google.appinventor.components.common.PropertyTypeConstants
Definition: PropertyTypeConstants.java:14
com.google.appinventor.components.annotations
com.google.appinventor