Created
August 3, 2014 18:55
-
-
Save kddlb/8e2c6033555a9ba50de6 to your computer and use it in GitHub Desktop.
Bing translator API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package cl.kelopez.bingtranslator; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.StringWriter; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import java.net.URLEncoder; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import org.apache.commons.collections4.bidimap.DualHashBidiMap; | |
import org.apache.commons.io.IOUtils; | |
import org.apache.commons.lang3.StringEscapeUtils; | |
import org.apache.http.Header; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.methods.CloseableHttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.client.utils.URIBuilder; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.apache.http.message.BasicHeader; | |
import org.apache.http.message.BasicNameValuePair; | |
import org.json.JSONArray; | |
/** | |
* | |
* @author Kevin López Brante <kelopez.cl at gmail.com> | |
*/ | |
public class BingTranslatorAPI { | |
public static String authHTTP(String url, String authHeader) { | |
try { | |
CloseableHttpClient ch = HttpClients.createDefault(); | |
Header[] parameters = new Header[2]; | |
parameters[0] = new BasicHeader("Authentication", authHeader); | |
parameters[1] = new BasicHeader("Content-Type", "text/xml"); | |
HttpGet hp = new HttpGet(url); | |
hp.setHeaders(parameters); | |
CloseableHttpResponse hr = ch.execute(hp); | |
StringWriter writer = new StringWriter(); | |
IOUtils.copy(hr.getEntity().getContent(), writer); | |
String theString = writer.toString(); | |
return theString; | |
} catch (IOException e) { | |
System.out.println(e.getMessage()); | |
} | |
return null; | |
} | |
public static InputStream authHTTPOS(String url, String authHeader) { | |
try { | |
CloseableHttpClient ch = HttpClients.createDefault(); | |
Header[] parameters = new Header[2]; | |
parameters[0] = new BasicHeader("Authentication", authHeader); | |
parameters[1] = new BasicHeader("Content-Type", "text/xml"); | |
HttpGet hp = new HttpGet(url); | |
hp.setHeaders(parameters); | |
CloseableHttpResponse hr = ch.execute(hp); | |
return hr.getEntity().getContent(); | |
} catch (IOException e) { | |
System.out.println(e.getMessage()); | |
} | |
return null; | |
} | |
/** | |
* @param endpoint the endpoint | |
* @param params the parameters | |
* @return The nominal | |
*/ | |
public static String BingAPI(String endpoint, List<NameValuePair> params) { | |
try { | |
String APIServer = "http://api.microsofttranslator.com/V2/Ajax.svc/"; | |
String clientID = "client_id"; | |
String clientSecret = URLEncoder.encode("secret"); | |
String authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; | |
String scopeUrl = "http://api.microsofttranslator.com"; | |
String grantType = "client_credentials"; | |
String accessToken = AccessTokenAuthentication.getTokens(grantType, scopeUrl, clientID, clientSecret, authUrl); | |
String authHeader = "Bearer " + accessToken; | |
params.add(new BasicNameValuePair("appId", authHeader)); | |
URI ux = new URIBuilder(APIServer + endpoint).addParameters(params).build(); | |
//System.out.println(ux); | |
String demo = "Esta es una prueba."; | |
String response = authHTTP(ux.toString(), authHeader); | |
return response; | |
} catch (URISyntaxException ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static InputStream BingAPIOS(String endpoint, List<NameValuePair> params) { | |
try { | |
String APIServer = "http://api.microsofttranslator.com/V2/Ajax.svc/"; | |
String clientID = "client_id"; | |
String clientSecret = URLEncoder.encode("secret"); | |
String authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; | |
String scopeUrl = "http://api.microsofttranslator.com"; | |
String grantType = "client_credentials"; | |
String accessToken = AccessTokenAuthentication.getTokens(grantType, scopeUrl, clientID, clientSecret, authUrl); | |
String authHeader = "Bearer " + accessToken; | |
params.add(new BasicNameValuePair("appId", authHeader)); | |
URI ux = new URIBuilder(APIServer + endpoint).addParameters(params).build(); | |
//System.out.println(ux); | |
String demo = "Esta es una prueba."; | |
InputStream response = authHTTPOS(ux.toString(), authHeader); | |
return response; | |
} catch (URISyntaxException ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static String BingAPIURL(String endpoint, List<NameValuePair> params) { | |
try { | |
String APIServer = "http://api.microsofttranslator.com/V2/Ajax.svc/"; | |
String clientID = "client_id"; | |
String clientSecret = URLEncoder.encode("secret"); | |
String authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; | |
String scopeUrl = "http://api.microsofttranslator.com"; | |
String grantType = "client_credentials"; | |
String accessToken = AccessTokenAuthentication.getTokens(grantType, scopeUrl, clientID, clientSecret, authUrl); | |
String authHeader = "Bearer " + accessToken; | |
params.add(new BasicNameValuePair("appId", authHeader)); | |
URI ux = new URIBuilder(APIServer + endpoint).addParameters(params).build(); | |
return ux.toString(); | |
} catch (URISyntaxException ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static String BingAPI(String endpoint) { | |
try { | |
String APIServer = "http://api.microsofttranslator.com/V2/Ajax.svc/"; | |
String clientID = "client_id"; | |
String clientSecret = URLEncoder.encode("secret"); | |
String authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; | |
String scopeUrl = "http://api.microsofttranslator.com"; | |
String grantType = "client_credentials"; | |
String accessToken = AccessTokenAuthentication.getTokens(grantType, scopeUrl, clientID, clientSecret, authUrl); | |
String authHeader = "Bearer " + accessToken; | |
List<NameValuePair> params = new ArrayList<>(); | |
params.add(new BasicNameValuePair("appId", authHeader)); | |
URI ux = new URIBuilder(APIServer + endpoint).addParameters(params).build(); | |
String demo = "Esta es una prueba."; | |
String response = authHTTP(ux.toString(), authHeader); | |
return response; | |
} catch (URISyntaxException ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* Obtain a list of language codes representing languages that are supported | |
* by the Translation Service. Translate() and TranslateArray() can | |
* translate between any of these languages. | |
* | |
* @return A string array containing the language codes supported by the | |
* Translator Services. | |
*/ | |
public static List<String> GetLanguagesForTranslate() { | |
try { | |
String LTX = BingAPI("GetLanguagesForTranslate").replaceAll("[\uFEFF-\uFFFF]", ""); | |
List<String> languages = new ArrayList<>(); | |
JSONArray ja = new JSONArray(LTX); | |
//languages.add(LTX); | |
for (int i = 0; i < ja.length(); i++) { | |
languages.add(ja.getString(i)); | |
} | |
return languages; | |
} catch (Exception ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static ArrayList<String> GetLanguagesForSpeak() { | |
try { | |
String LTX = BingAPI("GetLanguagesForSpeak").replaceAll("[\uFEFF-\uFFFF]", ""); | |
ArrayList<String> languages = new ArrayList<>(); | |
JSONArray ja = new JSONArray(LTX); | |
//languages.add(LTX); | |
for (int i = 0; i < ja.length(); i++) { | |
languages.add(ja.getString(i)); | |
} | |
return languages; | |
} catch (Exception ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* Retrieves friendly names for the languages passed in as the parameter | |
* languageCodes, and localized using the passed locale language. | |
* | |
* @param languageCodeToGetLanguagesIn A string representing a combination | |
* of an ISO 639 two-letter lowercase culture code associated with a | |
* language and an ISO 3166 two-letter uppercase subculture code to localize | |
* the language names or a ISO 639 lowercase culture code by itself | |
* @return A string array containing the friendly language names of the | |
* passed languageCodes. | |
*/ | |
public static DualHashBidiMap<String, String> GetLanguagesAndNames(String languageCodeToGetLanguagesIn) { | |
try { | |
List<NameValuePair> params = new ArrayList<>(); | |
String LTX = BingAPI("GetLanguagesForTranslate").replaceAll("[\uFEFF-\uFFFF]", ""); | |
params.add(new BasicNameValuePair("locale", languageCodeToGetLanguagesIn)); | |
params.add(new BasicNameValuePair("languageCodes", LTX)); | |
String LTX2 = BingAPI("GetLanguageNames", params).replaceAll("[\uFEFF-\uFFFF]", ""); | |
ArrayList<String> lngcodes = new ArrayList<>(); | |
JSONArray lngCodes = new JSONArray(LTX); | |
for (int i = 0; i < lngCodes.length(); i++) { | |
lngcodes.add(lngCodes.getString(i)); | |
} | |
ArrayList<String> lngnames = new ArrayList<>(); | |
JSONArray lngNames = new JSONArray(LTX2); | |
DualHashBidiMap<String, String> languages = new DualHashBidiMap<>(); | |
for (int i = 0; i < lngNames.length(); i++) { | |
lngnames.add(lngNames.getString(i)); | |
languages.put(lngCodes.getString(i), lngNames.getString(i)); | |
} | |
return languages; | |
} catch (Exception ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* Use the Detect Method to identify the language of a selected piece of | |
* text. | |
* | |
* @param text A string representing the text from an unknown language. The | |
* size of the text must not exceed 10000 characters. | |
* @return A string containing a two-character Language code for the given | |
* text. | |
*/ | |
public static String Detect(String text) { | |
try { | |
List<NameValuePair> params = new ArrayList<>(); | |
params.add(new BasicNameValuePair("text", text)); | |
String LTX = BingAPI("Detect", params).replaceAll("[\uFEFF-\uFFFF]", ""); | |
return StringEscapeUtils.unescapeJson(LTX.replaceAll("\"(.*)\"", "$1")); | |
} catch (Exception ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
/** | |
* Translates a text string from one language to another. | |
* | |
* @param text A string representing the text to translate. The size of the | |
* text must not exceed 10000 characters. | |
* @param from A string representing the language code of the translation | |
* text. If left empty the response will include the result of language | |
* auto-detection. | |
* @param to A string representing the language code to translate the text | |
* into. | |
* @return A string representing the translated text. | |
*/ | |
public static String Translate(String text, String from, String to) { | |
try { | |
List<NameValuePair> params = new ArrayList<>(); | |
params.add(new BasicNameValuePair("text", text)); | |
params.add(new BasicNameValuePair("from", from)); | |
params.add(new BasicNameValuePair("to", to)); | |
params.add(new BasicNameValuePair("contentType", "text/plain")); | |
String LTX = BingAPI("Translate", params).replaceAll("[\uFEFF-\uFFFF]", ""); | |
return StringEscapeUtils.unescapeJson(LTX.replaceAll("\"(.*)\"", "$1")); | |
} catch (Exception ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
public static String Speak(String text, String lang) { | |
try { | |
List<NameValuePair> params = new ArrayList<>(); | |
params.add(new BasicNameValuePair("text", text)); | |
params.add(new BasicNameValuePair("language", lang)); | |
params.add(new BasicNameValuePair("format", "audio/wav")); | |
params.add(new BasicNameValuePair("options", "MaxQuality")); | |
String LTX = BingAPIURL("Speak", params); | |
return LTX; | |
} catch (Exception ex) { | |
Logger.getLogger(BingTranslatorAPI.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment