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
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ is my goal to mimic the code structure, naming conventions, functionality, and u
## Requires

* Java 1.5 or greater
* A Windows Azure Marketplace Client ID and Client Secret - [Documentation](http://msdn.microsoft.com/en-us/library/hh454950.aspx)

_Please note: If you signed up for a Bing Developer Key after March 31, 2012, you will not be able to use your App Id with this API. Please visit the aforementioned documentation link_
* A Microsoft Translator Text Translation Subscription Key - [Documentation](http://docs.microsofttranslator.com/text-translate.html)

Quickstart
===========
Expand All @@ -25,9 +23,8 @@ Download the latest [JAR with Dependencies](https://microsoft-translator-java-ap

public class Main {
public static void main(String[] args) throws Exception {
// Set your Windows Azure Marketplace client info - See http://msdn.microsoft.com/en-us/library/hh454950.aspx
Translate.setClientId(/* Enter your Windows Azure Client Id here */);
Translate.setClientSecret(/* Enter your Windows Azure Client Secret here */);
// Set your Microsoft Translator Text Translation Subscription Key - See http://docs.microsofttranslator.com/text-translate.html
Translate.setSubscriptionKey(/* Microsoft Translator Text Translation Subscription Key here */);

String translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);

Expand Down
95 changes: 29 additions & 66 deletions src/main/java/com/memetix/mst/MicrosoftTranslatorAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
Expand All @@ -35,73 +33,47 @@
* Makes the generic Microsoft Translator API calls. Different service classes then
* extend this to make the specific service calls.
*
* Uses the AJAX Interface V2 - see: http://msdn.microsoft.com/en-us/library/ff512404.aspx
* Uses the AJAX Interface V2 - see: http://docs.microsofttranslator.com/text-translate.html
*
* @author Jonathan Griggs
*/
public abstract class MicrosoftTranslatorAPI {
//Encoding type
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 TokenServiceUri = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
private static String referrer;
private static String clientId;
private static String clientSecret;
private static String subscriptionKey;
private static String token;
private static long tokenExpiration = 0;
private static String contentType = "text/plain";

protected static final String PARAM_APP_ID = "appId=",
PARAM_TO_LANG = "&to=",
protected static final String PARAM_TO_LANG = "&to=",
PARAM_FROM_LANG = "&from=",
PARAM_TEXT_SINGLE = "&text=",
PARAM_TEXT_ARRAY = "&texts=",
PARAM_SPOKEN_LANGUAGE = "&language=",
PARAM_SENTENCES_LANGUAGE = "&language=",
PARAM_LOCALE = "&locale=",
PARAM_LANGUAGE_CODES = "&languageCodes=";
private static final long TOKEN_DURATION = 10 * 60 * 1000;

/**
* Sets the API key.
*
* Note: Should ONLY be used with API Keys generated prior to March 31, 2012. All new applications should obtain a ClientId and Client Secret by following
* the guide at: http://msdn.microsoft.com/en-us/library/hh454950.aspx
* @param pKey The API key.
*/
public static void setKey(final String pKey) {
apiKey = pKey;
}

/**
* Sets the API key.
*
* Note: Should ONLY be used with API Keys generated prior to March 31, 2012. All new applications should obtain a ClientId and Client Secret by following
* the guide at: http://msdn.microsoft.com/en-us/library/hh454950.aspx
* @param pKey The API key.
* Sets the Http Content Type.
* @param pContentType The HTTP content type.
*/
public static void setContentType(final String pKey) {
contentType = pKey;
public static void setContentType(final String pContentType) {
contentType = pContentType;
}

/**
* Sets the Client ID.
* All new applications should obtain a ClientId and Client Secret by following
* the guide at: http://msdn.microsoft.com/en-us/library/hh454950.aspx
* @param pKey The Client Id.
* Sets the Subscription Key.
* All new applications should obtain a Subscription Key by following the
* guide at: http://docs.microsofttranslator.com/text-translate.html
* @param pSubscriptionKey The Subscription Key.
*/
public static void setClientId(final String pClientId) {
clientId = pClientId;
}

/**
* Sets the Client Secret.
* All new applications should obtain a ClientId and Client Secret by following
* the guide at: http://msdn.microsoft.com/en-us/library/hh454950.aspx
* @param pKey The Client Secret.
*/
public static void setClientSecret(final String pClientSecret) {
clientSecret = pClientSecret;
public static void setSubscriptionKey(final String pSubscriptionKey) {
subscriptionKey = pSubscriptionKey;
}

/**
Expand All @@ -113,27 +85,19 @@ public static void setHttpReferrer(final String pReferrer) {
}
/**
* Gets the OAuth access token.
* @param clientId The Client key.
* @param clientSecret The Client Secret
* @param subscriptionKey The Subscription Key
*/
public static String getToken(final String clientId, final String clientSecret) throws Exception {
final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
+ "&client_id=" + URLEncoder.encode(clientId,ENCODING)
+ "&client_secret=" + URLEncoder.encode(clientSecret,ENCODING) ;

final URL url = new URL(DatamarketAccessUri);
public static String getToken(final String subscriptionKey) throws Exception {
final URL url = new URL(TokenServiceUri);
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if(referrer!=null)
uc.setRequestProperty("referer", referrer);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + ENCODING);
uc.setRequestProperty("Accept-Charset",ENCODING);
uc.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
uc.setRequestMethod("POST");
uc.setFixedLengthStreamingMode(0);
uc.setDoOutput(true);

OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
wr.write(params);
wr.flush();

try {
final int responseCode = uc.getResponseCode();
final String result = inputStreamToString(uc.getInputStream());
Expand All @@ -156,11 +120,9 @@ public static String getToken(final String clientId, final String clientSecret)
* @throws Exception on error.
*/
private static String retrieveResponse(final URL url) throws Exception {
if(clientId!=null&&clientSecret!=null&&System.currentTimeMillis()>tokenExpiration) {
String tokenJson = getToken(clientId,clientSecret);
Integer expiresIn = Integer.parseInt((String)((JSONObject)JSONValue.parse(tokenJson)).get("expires_in"));
tokenExpiration = System.currentTimeMillis()+((expiresIn*1000)-1);
token = "Bearer " + (String)((JSONObject)JSONValue.parse(tokenJson)).get("access_token");
if(subscriptionKey!=null&&System.currentTimeMillis()>tokenExpiration) {
token = "Bearer " + getToken(subscriptionKey);
tokenExpiration = System.currentTimeMillis()+TOKEN_DURATION-1;
}
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if(referrer!=null)
Expand Down Expand Up @@ -305,7 +267,10 @@ private static String inputStreamToString(final InputStream inputStream) throws
while (null != (string = reader.readLine())) {
// Need to strip the Unicode Zero-width Non-breaking Space. For some reason, the Microsoft AJAX
// services prepend this to every response
outputBuilder.append(string.replaceAll("\uFEFF", ""));
string = string.replaceAll("\uFEFF", "");
// Need to replace the Non-breaking Space into simple space
string = string.replace('\u00A0', ' ');
outputBuilder.append(string);
}
}
} catch (Exception ex) {
Expand All @@ -317,10 +282,8 @@ private static String inputStreamToString(final InputStream inputStream) throws

//Check if ready to make request, if not, throw a RuntimeException
protected static void validateServiceState() throws Exception {
if(apiKey!=null&&apiKey.length()<16) {
throw new RuntimeException("INVALID_API_KEY - Please set the API Key with your Bing Developer's Key");
} else if (apiKey==null&&(clientId==null||clientSecret==null)) {
throw new RuntimeException("Must provide a Windows Azure Marketplace Client Id and Client Secret - Please see http://msdn.microsoft.com/en-us/library/hh454950.aspx for further documentation");
if (subscriptionKey==null) {
throw new RuntimeException("Must provide a Microsoft Translator Text Translation Subscription Key - Please see http://docs.microsofttranslator.com/text-translate.html for further documentation");
}
}

Expand Down
2 changes: 0 additions & 2 deletions src/main/java/com/memetix/mst/detect/Detect.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ public static Language execute(final String text) throws Exception {
//Run the basic service validations first
validateServiceState(text);
final URL url = new URL(SERVICE_URL
+(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+PARAM_TEXT_SINGLE+URLEncoder.encode(text, ENCODING));

final String response = retrieveString(url);
Expand All @@ -68,7 +67,6 @@ public static String[] execute(final String[] texts) throws Exception {
validateServiceState(texts);
final String textArr = buildStringArrayParam(texts);
final URL url = new URL(ARRAY_SERVICE_URL
+(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+PARAM_TEXT_ARRAY+URLEncoder.encode(textArr, ENCODING));
final String[] response = retrieveStringArr(url);
return response;
Expand Down
14 changes: 3 additions & 11 deletions src/main/java/com/memetix/mst/language/Language.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,8 @@ public String toString() {
return language;
}

public static void setKey(String pKey) {
LanguageService.setKey(pKey);
}

public static void setClientId(String pId) {
LanguageService.setClientId(pId);
}
public static void setClientSecret(String pSecret) {
LanguageService.setClientSecret(pSecret);
public static void setSubscriptionKey(String pSubscriptionKey) {
LanguageService.setSubscriptionKey(pSubscriptionKey);
}

/**
Expand Down Expand Up @@ -221,7 +214,6 @@ public static String[] execute(final Language[] targets, final Language locale)
final String targetString = buildStringArrayParam(Language.values());

final URL url = new URL(SERVICE_URL
+(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+PARAM_LOCALE+URLEncoder.encode(locale.toString(), ENCODING)
+PARAM_LANGUAGE_CODES + URLEncoder.encode(targetString, ENCODING));
localizedNames = retrieveStringArr(url);
Expand All @@ -245,7 +237,7 @@ public static String[] execute() throws Exception {
validateServiceState();
String[] codes = new String[0];

final URL url = new URL(SERVICE_URL +(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : ""));
final URL url = new URL(SERVICE_URL);
codes = retrieveStringArr(url);
return codes;
}
Expand Down
13 changes: 2 additions & 11 deletions src/main/java/com/memetix/mst/language/SpokenDialect.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,8 @@ public String toString() {
return language;
}

public static void setKey(String pKey) {
SpokenDialectService.setKey(pKey);
}

public static void setClientId(String pId) {
SpokenDialectService.setClientId(pId);
}

public static void setClientSecret(String pSecret) {
SpokenDialectService.setClientSecret(pSecret);
public static void setSubscriptionKey(String pSubscriptionKey) {
SpokenDialectService.setSubscriptionKey(pSubscriptionKey);
}

/**
Expand Down Expand Up @@ -172,7 +164,6 @@ public static String[] execute(final SpokenDialect[] targets, final Language loc
final String targetString = buildStringArrayParam(SpokenDialect.values());

final URL url = new URL(SERVICE_URL
+(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+PARAM_LOCALE+URLEncoder.encode(locale.toString(), ENCODING)
+PARAM_LANGUAGE_CODES + URLEncoder.encode(targetString, ENCODING));
localizedNames = retrieveStringArr(url);
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/memetix/mst/sentence/BreakSentences.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ public static Integer[] execute(final String text, final Language fromLang) thro
//Run the basic service validations first
validateServiceState(text,fromLang);
final URL url = new URL(SERVICE_URL
+(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+PARAM_SENTENCES_LANGUAGE+URLEncoder.encode(fromLang.toString(), ENCODING)
+PARAM_TEXT_SINGLE+URLEncoder.encode(text, ENCODING));

Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/memetix/mst/speak/Speak.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ public static String execute(final String text, final SpokenDialect language) th
//Run the basic service validations first
validateServiceState(text);
final URL url = new URL(SERVICE_URL
+(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+PARAM_SPOKEN_LANGUAGE+URLEncoder.encode(language.toString(),ENCODING)
+PARAM_TEXT_SINGLE+URLEncoder.encode(text, ENCODING));
final String response = retrieveString(url);
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/com/memetix/mst/translate/Translate.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ public static String execute(final String text, final Language from, final Langu
//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_FROM_LANG + URLEncoder.encode(from.toString(),ENCODING)
+ PARAM_TO_LANG + URLEncoder.encode(to.toString(),ENCODING)
+ PARAM_TEXT_SINGLE + URLEncoder.encode(text,ENCODING);

Expand Down Expand Up @@ -92,8 +91,7 @@ public static String[] execute(final String[] texts, final Language from, final
//Run the basic service validations first
validateServiceState(texts);
final String params =
(apiKey != null ? PARAM_APP_ID + URLEncoder.encode(apiKey,ENCODING) : "")
+ PARAM_FROM_LANG + URLEncoder.encode(from.toString(),ENCODING)
PARAM_FROM_LANG + URLEncoder.encode(from.toString(),ENCODING)
+ PARAM_TO_LANG + URLEncoder.encode(to.toString(),ENCODING)
+ PARAM_TEXT_ARRAY + URLEncoder.encode(buildStringArrayParam(texts),ENCODING);

Expand Down
Loading