-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathMicrosoftTranslatorAPI.java
More file actions
320 lines (290 loc) · 11.8 KB
/
MicrosoftTranslatorAPI.java
File metadata and controls
320 lines (290 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
* microsoft-translator-java-api
*
* Copyright 2012 Jonathan Griggs <jonathan.griggs at gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.memetix.mst;
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;
/**
*
* MicrosoftAPI
*
* Makes the generic Microsoft Translator API calls. Different service classes then
* extend this to make the specific service calls.
*
* see: https://www.microsoft.com/en-us/translator/getstarted.aspx
*
* @author Jonathan Griggs
*/
public abstract class MicrosoftTranslatorAPI {
//Encoding type
protected static final String ENCODING = "UTF-8";
private static String MicrosoftCognitiveServicesAuthTokenUri = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
protected static String apiKey;
private static String referrer;
private static String token;
private static long tokenExpiration = 0;
private static String contentType = "text/plain";
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=";
/**
* Sets the API key.
*
* Note: DataMarket and Data Services are being retired and will stop accepting new orders after 12/31/2016. Existing subscriptions will be retired and cancelled starting 3/31/2017.
* the guide at: https://www.microsoft.com/en-us/translator/getstarted.aspx
*
* @param pKey The API key.
*/
public static void setKey(final String pKey) {
apiKey = pKey;
}
/**
* Sets the content type.
*
* @param type The content type.
*/
public static void setContentType(final String type) {
contentType = type;
}
/**
* Sets the Http Referrer.
* @param pReferrer The HTTP client referrer.
*/
public static void setHttpReferrer(final String pReferrer) {
referrer = pReferrer;
}
/**
* Gets the OAuth access token.
* @param key The Client key.
*/
public static String getToken(final String key) throws Exception {
//final String params = "Subscription-Key=" + URLEncoder.encode(key,ENCODING);
final URL url = new URL(MicrosoftCognitiveServicesAuthTokenUri);
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestProperty("Ocp-Apim-Subscription-Key", key);
uc.setRequestProperty("Content-Type","application/json");
uc.setRequestProperty("Accept","application/jwt");
uc.setRequestMethod("POST");
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());
if(responseCode!=200) {
throw new Exception("Error from Microsoft Translator API: " + result);
}
return result;
} finally {
if(uc!=null) {
uc.disconnect();
}
}
}
/**
* Forms an HTTP request, sends it using GET method and returns the result of the request as a String.
*
* @param url The URL to query for a String response.
* @return The translated String.
* @throws Exception on error.
*/
private static String retrieveResponse(final URL url) throws Exception {
if(apiKey!=null&&System.currentTimeMillis()>tokenExpiration) {
String authToken = getToken(apiKey);
// set expiration time to 8 minutes
tokenExpiration = System.currentTimeMillis()+(8*60*1000);
token = "Bearer " + authToken;
}
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if(referrer!=null)
uc.setRequestProperty("referer", referrer);
uc.setRequestProperty("Content-Type",contentType + "; charset=" + ENCODING);
uc.setRequestProperty("Accept-Charset",ENCODING);
if(token!=null) {
uc.setRequestProperty("Authorization",token);
}
uc.setRequestMethod("GET");
uc.setDoOutput(true);
try {
final int responseCode = uc.getResponseCode();
final String result = inputStreamToString(uc.getInputStream());
if(responseCode!=200) {
throw new Exception("Error from Microsoft Translator API: " + result);
}
return result;
} finally {
if(uc!=null) {
uc.disconnect();
}
}
}
/**
* Fetches the JSON response, parses the JSON Response, returns the result of the request as a String.
*
* @param url The URL to query for a String response.
* @return The translated String.
* @throws Exception on error.
*/
protected static String retrieveString(final URL url) throws Exception {
try {
final String response = retrieveResponse(url);
return jsonToString(response);
} catch (Exception ex) {
throw new Exception("[microsoft-translator-api] Error retrieving translation : " + ex.getMessage(), 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[] retrieveStringArr(final URL url, final String jsonProperty) throws Exception {
try {
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 Strings
* and returns the result of the request as a String Array.
*
* Overloaded to pass null as the JSON Property (assume only Strings instead of JSONObjects)
*
* @param url The URL to query for a String response.
* @return The translated String[].
* @throws Exception on error.
*/
protected static String[] retrieveStringArr(final URL url) throws Exception {
return retrieveStringArr(url,null);
}
/**
* Fetches the JSON response, parses the JSON Response, returns the result of the request as an array of integers.
*
* @param url The URL to query for a String response.
* @return The translated String.
* @throws Exception on error.
*/
protected static Integer[] retrieveIntArray(final URL url) throws Exception {
try {
final String response = retrieveResponse(url);
return jsonToIntArr(response);
} catch (Exception ex) {
throw new Exception("[microsoft-translator-api] Error retrieving translation : " + ex.getMessage(), ex);
}
}
private static Integer[] jsonToIntArr(final String inputString) throws Exception {
final JSONArray jsonArr = (JSONArray)JSONValue.parse(inputString);
Integer[] intArr = new Integer[jsonArr.size()];
int i = 0;
for(Object obj : jsonArr) {
intArr[i] = ((Long)obj).intValue();
i++;
}
return intArr;
}
private static String jsonToString(final String inputString) throws Exception {
String json = (String)JSONValue.parse(inputString);
return json.toString();
}
// 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[] jsonToStringArr(final String inputString, final String propertyName) throws Exception {
final JSONArray jsonArr = (JSONArray)JSONValue.parse(inputString);
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.
* @param inputStream The InputStream to read from.
* @return The contents of the InputStream as a String.
* @throws Exception on error.
*/
private static String inputStreamToString(final InputStream inputStream) throws Exception {
final StringBuilder outputBuilder = new StringBuilder();
try {
String string;
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
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", ""));
}
}
} catch (Exception ex) {
throw new Exception("[microsoft-translator-api] Error reading translation stream.", ex);
}
return outputBuilder.toString();
}
//Check if ready to make request, if not, throw a RuntimeException
protected static void validateServiceState() throws Exception {
if(apiKey!=null&&apiKey.length()<32) {
throw new RuntimeException("INVALID_API_KEY - Please set the API Key with your Azure Cognitive Services Developer's Key - Please see https://www.microsoft.com/en-us/translator/getstarted.aspx");
}
}
protected static String buildStringArrayParam(Object[] values) {
StringBuilder targetString = new StringBuilder("[\"");
String value;
for(Object obj : values) {
if(obj!=null) {
value = obj.toString();
if(value.length()!=0) {
if(targetString.length()>2)
targetString.append(",\"");
targetString.append(value);
targetString.append("\"");
}
}
}
targetString.append("]");
return targetString.toString();
}
}