Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ src/test/resources/META-INF/config.properties
.classpath
.settings
.project
*.sublime*
53 changes: 50 additions & 3 deletions src/main/java/com/memetix/mst/MicrosoftTranslatorAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public abstract class MicrosoftTranslatorAPI {
protected static final String ENCODING = "UTF-8";

protected static String apiKey;
private static String DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
private static String DatamarketAccessUri =
"https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
private static String referrer;
private static String clientId;
private static String clientSecret;
Expand All @@ -61,6 +62,10 @@ public abstract class MicrosoftTranslatorAPI {
PARAM_SENTENCES_LANGUAGE = "&language=",
PARAM_LOCALE = "&locale=",
PARAM_LANGUAGE_CODES = "&languageCodes=";

protected static final String MAX_TRANSLATIONS_PARAMETER =
"&maxTranslations=";
protected static final int DEFAULT_MAX_TRANSLATIONS = 10;

/**
* Sets the API key.
Expand Down Expand Up @@ -214,13 +219,31 @@ protected static String retrieveString(final URL url) throws Exception {
*/
protected static String[] retrieveStringArr(final URL url, final String jsonProperty) throws Exception {
try {
final String response = retrieveResponse(url);
return jsonToStringArr(response,jsonProperty);
final String response = retrieveResponse(url);
return jsonToStringArr(response, jsonProperty);
} catch (Exception ex) {
throw new Exception("[microsoft-translator-api] Error retrieving translation.", ex);
}
}

/**
* Fetches the JSON response, parses the JSON Response as an Array of JSONObjects,
* retrieves the String value of the specified JSON Property, and returns the result of
* the request as a String Array.
*
* @param url The URL to query for a String response.
* @return The translated String[].
* @throws Exception on error.
*/
protected static String[] retrieveManyStringArr(final URL url, final String jsonManyProperty, final String jsonProperty) throws Exception {
try {
final String response = retrieveResponse(url);
return jsonToManyStringArr(response, jsonManyProperty, jsonProperty);
} catch (Exception ex) {
throw new Exception("[microsoft-translator-api] Error retrieving translation.", ex);
}
}

/**
* Fetches the JSON response, parses the JSON Response as an array of Strings
* and returns the result of the request as a String Array.
Expand Down Expand Up @@ -288,6 +311,30 @@ private static String[] jsonToStringArr(final String inputString, final String p
return values;
}

// Helper method to parse a JSONArray. Reads an array of JSONObjects and returns a String Array
// containing the toString() of the desired property. If propertyName is null, just return the String value.
private static String[] jsonToManyStringArr(final String inputString, final String jsonPropertyName, final String propertyName) throws Exception {
final JSONObject jSONObject = (JSONObject) JSONValue.parse(inputString);
final JSONArray jsonArr = (JSONArray) jSONObject.get(jsonPropertyName);
if (jsonArr == null || jsonArr.size() == 0) {
return null;
}
String[] values = new String[jsonArr.size()];
int i = 0;
for(Object obj : jsonArr) {
if(propertyName != null && propertyName.length() != 0) {
final JSONObject json = (JSONObject) obj;
if(json.containsKey(propertyName)) {
values[i] = json.get(propertyName).toString();
}
} else {
values[i] = obj.toString();
}
i++;
}
return values;
}

/**
* Reads an InputStream and returns its contents as a String.
* Also effects rate control.
Expand Down
29 changes: 26 additions & 3 deletions src/main/java/com/memetix/mst/translate/Translate.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ public final class Translate extends MicrosoftTranslatorAPI {

private static final String SERVICE_URL = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?";
private static final String ARRAY_SERVICE_URL = "http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?";
private static final String COLLABORATIVE_SERVICE_URL = "http://api.microsofttranslator.com/V2/Ajax.svc/GetTranslations?";
private static final String ARRAY_JSON_OBJECT_PROPERTY = "TranslatedText";

private static final String ARRAY_MANY_JSON_OBJECT_PROPERTY = "Translations";

//prevent instantiation
private Translate(){};

Expand All @@ -56,7 +58,6 @@ public static String execute(final String text, final Language from, final Langu
+ PARAM_FROM_LANG + URLEncoder.encode(from.toString(),ENCODING)
+ PARAM_TO_LANG + URLEncoder.encode(to.toString(),ENCODING)
+ PARAM_TEXT_SINGLE + URLEncoder.encode(text,ENCODING);

final URL url = new URL(SERVICE_URL + params);
final String response = retrieveString(url);
return response;
Expand Down Expand Up @@ -141,6 +142,28 @@ private static void validateServiceState(final String text) throws Exception {
validateServiceState();
}


/**
* Translates text from a given Language to another given Language using Microsoft Translator.
* Returns many translated results.
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String[].
* @throws Exception on error.
*/
public static String[] executeMany(final String text, final Language from, final Language to) throws Exception {
//Run the basic service validations first
validateServiceState(text);
final String params =
(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey, ENCODING) : "")
+ PARAM_FROM_LANG + URLEncoder.encode(from.toString(), ENCODING)
+ PARAM_TO_LANG + URLEncoder.encode(to.toString(), ENCODING)
+ PARAM_TEXT_SINGLE + URLEncoder.encode(text, ENCODING)
+ MAX_TRANSLATIONS_PARAMETER + DEFAULT_MAX_TRANSLATIONS;
final URL url = new URL(COLLABORATIVE_SERVICE_URL + params);
final String[] response = retrieveManyStringArr(url, ARRAY_MANY_JSON_OBJECT_PROPERTY, ARRAY_JSON_OBJECT_PROPERTY);
return response;
}

}