Skip to content

Commit

Permalink
Fixed issue that broke the ability to use an old-style Bing API Key
Browse files Browse the repository at this point in the history
  • Loading branch information
boatmeme committed May 26, 2012
1 parent ad567d6 commit 790a943
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

<groupId>com.memetix</groupId>
<artifactId>microsoft-translator-java-api</artifactId>
<version>0.7-SNAPSHOT</version>
<version>0.6.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>microsoft-translator-java-api</name>
Expand Down
16 changes: 14 additions & 2 deletions src/main/java/com/memetix/mst/MicrosoftTranslatorAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public abstract class MicrosoftTranslatorAPI {
private static String clientSecret;
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=",
Expand All @@ -72,6 +73,17 @@ 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.
*/
public static void setContentType(final String pKey) {
contentType = pKey;
}

/**
* Sets the Client ID.
* All new applications should obtain a ClientId and Client Secret by following
Expand Down Expand Up @@ -153,7 +165,7 @@ private static String retrieveResponse(final URL url) throws Exception {
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if(referrer!=null)
uc.setRequestProperty("referer", referrer);
uc.setRequestProperty("Content-Type","text/plain; charset=" + ENCODING);
uc.setRequestProperty("Content-Type",contentType + "; charset=" + ENCODING);
uc.setRequestProperty("Accept-Charset",ENCODING);
if(token!=null) {
uc.setRequestProperty("Authorization",token);
Expand Down Expand Up @@ -307,7 +319,7 @@ private static String inputStreamToString(final InputStream inputStream) throws
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 (clientId==null||clientSecret==null) {
} 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");
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/test/java/com/memetix/mst/translate/TranslateTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public void setUp() throws Exception {
@After
public void tearDown() throws Exception {
Translate.setKey(null);
Translate.setContentType("text/plain");
Translate.setClientId(null);
Translate.setClientSecret(null);
Translate.setHttpReferrer(null);
Expand Down Expand Up @@ -99,6 +100,12 @@ public void testTranslate_EncodeSpace() throws Exception {
public void testTranslate_AutoDetectOrigin() throws Exception {
assertEquals("Bonjour, mon nom est",Translate.execute("Hello, my name is", Language.AUTO_DETECT, Language.FRENCH));
}

@Test
public void testTranslate_HTMLContentType() throws Exception {
Translate.setContentType("text/html");
assertEquals("<hello>Bonjour, mon nom est</hello>",Translate.execute("<hello>Hello, my name is</hello>", Language.AUTO_DETECT, Language.FRENCH));
}
@Test
public void testTranslate_AutoDetectOrigin_French() throws Exception {
assertEquals("Salut tout le monde", Translate.execute("Hallo welt", Language.AUTO_DETECT, Language.FRENCH));
Expand Down Expand Up @@ -169,6 +176,14 @@ public void testTranslate_WrongKey() throws Exception {
exception.expectMessage("INVALID_API_KEY - Please set the API Key with your Bing Developer's Key");
Translate.execute("ハローワールド", Language.AUTO_DETECT, Language.ENGLISH);
}

@Test
public void testTranslate_SetKeyNoClientIdAndSecret() throws Exception {
Translate.setClientId(null);
Translate.setClientSecret(null);
String translate = Translate.execute("ハローワールド", Language.AUTO_DETECT, Language.ENGLISH);
assertNotNull(translate);
}
/*
@Test
public void testTranslate_Exception() throws Exception {
Expand Down

9 comments on commit 790a943

@weibinke
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi ,
I follow the example code and it works yesterday.But tody i found Translate.excute failed always.I found Translate.execute blocks alway.I sure that my network is ok.
My code is:
Translate.setClientId(CLIENT_ID);
Translate.setClientSecret(CLIENT_SECRET);
result = Translate.execute(target, LanguageHelper.getLanguageByName(context, fromLang), LanguageHelper.getLanguageByName(context, toLang));

I had update the newest jar-0.6.1 ,the problem also exist.
I'm sure my network and clientid is ok.Because i follow http://msdn.microsoft.com/en-us/library/hh454950.aspx and setup an php on my web server.It can get token and gettranslate.

That's strange.Would you help.If you have any suggestion ,please tell my .Email:[email protected].

Thanks!

@weibinke
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi ,
I follow the example code and it works yesterday.But tody i found Translate.excute failed always.I found Translate.execute blocks alway.I sure that my network is ok.
My code is:
Translate.setClientId(CLIENT_ID);
Translate.setClientSecret(CLIENT_SECRET);
result = Translate.execute(target, LanguageHelper.getLanguageByName(context, fromLang), LanguageHelper.getLanguageByName(context, toLang));

I had update the newest jar-0.6.1 ,the problem also exist.
I'm sure my network and clientid is ok.Because i follow http://msdn.microsoft.com/en-us/library/hh454950.aspx and setup an php on my web server.It can get token and gettranslate.

That's strange.Would you help.If you have any suggestion ,please tell my .Email:[email protected].

Thanks!

@boatmeme
Copy link
Owner Author

@boatmeme boatmeme commented on 790a943 May 26, 2012 via email

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@weibinke
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes i had registered my own app and replaced CLIENT_ID and CLIENT_SECRET in the example.It works for two days.But today,when i try to use my application,i found it failed to return from 'Translate.excute'.It just block for a long time.But I didn't modify anything.
And i'm sure that my clientid and clientsecret is valid.Because i use it to build a php page,it works.The page url is:http://platformtools.sinaapp.com/translate.php

I also try to deal with http api myself.But the problem also exists.It block on:
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);

Seem that server didn' response,but my network is ok.That's strange.
My code is :
public final static String CLIENT_ID = "translatetest55";
public final static String CLIENT_SECRET = "2+mDhC9lgXju8PRKKld7va5COr1QN3Sqjkx6vdh1rrU=";
Translate.setClientId(CLIENT_ID);
Translate.setClientSecret(CLIENT_SECRET);
String result = Translate.execute(target, LanguageHelper.getLanguageByName(context, fromLang), LanguageHelper.getLanguageByName(context, toLang));

The clientid and clientkey is which i use now.You can try it.

I try to Translate.setKey(APP_KEY) to set an old appkey and left clientid and clienk key null.Then everything works fine.But i want to use the new clientid because i'm building a new application.

Best regards
weibinke

@boatmeme
Copy link
Owner Author

@boatmeme boatmeme commented on 790a943 May 26, 2012 via email

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@boatmeme
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I tested this on my end and it worked for me with your credentials. I will see if I can think of anything else that could be wrong. In the meantime, if you are still successful using the old app ID method, you may continue using that with the same usage privileges as the Windows Azure Marketplace Apps.

@weibinke
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok thank you very much.I think there may be something else wrong and it affect my application's network connect.

@weibinke
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think i may found the issue:
When using new api method,we should first visit "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13" to get access token.My application run on android phone.There may be something wrong with my android device.I found it could not connect to this host.I write som code using HttpURLConnection or HttpsURLConnection to connect the url,it just return connect timeout.I try to connect to some other https url,it could connect successfully.Then i reboot my android device,and try again.Guess what?Everything is right now.

So maybe the problem is my android device.It had something problem to acess the Auth url of microsoft.After reboot ,everything seems right now,although i don't known when the network access will go wrong.

Thanks a lot for helping me.

Another question:
DatamarketAccessUri is https url ,so should we use HttpsURLConnection instead of HttpURLConnection in getToken() function?And maybe we should disable ssl vertification of the request because i am afraid of some device may have had problem on verifying the peer's certificate.See http://stackoverflow.com/questions/6681969/java-ignore-certificate-validation .

Thanks again for your great job.Your sdk is great!

private static String DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";

public static String getToken(String clientId, String clientSecret)
throws Exception
{
String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com&client_id=" + URLEncoder.encode(clientId, "UTF-8") + "&client_secret=" + URLEncoder.encode(clientSecret, "UTF-8");

URL url = new URL(DatamarketAccessUri);
HttpURLConnection uc = (HttpURLConnection)url.openConnection();
if (referrer != null)
  uc.setRequestProperty("referer", referrer);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
uc.setRequestProperty("Accept-Charset", "UTF-8");
uc.setRequestMethod("POST");
uc.setDoOutput(true);

OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
wr.write(params);
wr.flush();
try
{
  int responseCode = uc.getResponseCode();
  String result = inputStreamToString(uc.getInputStream());
  if (responseCode != 200) {
    throw new Exception("Error from Microsoft Translator API: " + result);
  }
  String str1 = result;
  return str1;
}
finally
{
  if (uc != null)
    uc.disconnect(); 
}throw localObject;

}

@boatmeme
Copy link
Owner Author

@boatmeme boatmeme commented on 790a943 May 27, 2012 via email

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.