94 lines
2.9 KiB
Java
94 lines
2.9 KiB
Java
package tech.nevets.deepj;
|
|
|
|
import org.json.JSONArray;
|
|
import org.json.JSONObject;
|
|
import java.io.IOException;
|
|
import java.net.URI;
|
|
import java.net.URLEncoder;
|
|
import java.net.http.HttpClient;
|
|
import java.net.http.HttpRequest;
|
|
import java.net.http.HttpResponse;
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
public class Translator {
|
|
Request request;
|
|
public Translator(String authKey) {
|
|
request = new Request(authKey);
|
|
}
|
|
public String translate(Enum<Language> langToTranslateTo, String sourceMessage) {
|
|
String response = "Error processing request";
|
|
try {
|
|
response = request.get(langToTranslateTo, sourceMessage);
|
|
} catch (IOException | InterruptedException e) {
|
|
System.out.println("Error processing request");
|
|
e.printStackTrace();
|
|
}
|
|
String message = "Error Processing Request";
|
|
JSONObject jo = new JSONObject(response);
|
|
JSONArray ja = jo.getJSONArray("translations");
|
|
for (int i = 0; i < ja.length(); i++) {
|
|
JSONObject joo = ja.getJSONObject(i);
|
|
message = joo.getString("text");
|
|
}
|
|
return message;
|
|
}
|
|
private static class Request {
|
|
|
|
private final String authKey;
|
|
public Request(String authKey) {
|
|
this.authKey = authKey;
|
|
}
|
|
public String get(Enum<Language> langEnum, String message) throws IOException, InterruptedException {
|
|
String encodedAuthKey = URLEncoder.encode(authKey, StandardCharsets.UTF_8);
|
|
String lang = langEnum.toString();
|
|
if (langEnum == Language.EN_US) {
|
|
lang = "EN-US";
|
|
} else if (langEnum == Language.EN_GB) {
|
|
lang = "EN-GB";
|
|
} else if (langEnum == Language.PT_BR) {
|
|
lang = "PT-BR";
|
|
} else if (langEnum == Language.PT_PT) {
|
|
lang = "PT-PT";
|
|
}
|
|
String encodedMessage = URLEncoder.encode(message, StandardCharsets.UTF_8);
|
|
HttpClient client = HttpClient.newHttpClient();
|
|
HttpRequest request = HttpRequest.newBuilder().GET()
|
|
.header("Accept","*/*")
|
|
.header("Content-Type", "application/x-www-form-urlencoded")
|
|
.uri(URI.create("https://api-free.deepl.com/v2/translate?auth_key=" + encodedAuthKey + "&target_lang=" + lang + "&text=" + encodedMessage)).build();
|
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
|
return response.body();
|
|
}
|
|
}
|
|
|
|
public enum Language {
|
|
BG,
|
|
CS,
|
|
DA,
|
|
DE,
|
|
EL,
|
|
EN_GB,
|
|
EN_US,
|
|
ES,
|
|
ET,
|
|
FI,
|
|
FR,
|
|
HU,
|
|
IT,
|
|
JA,
|
|
LT,
|
|
LV,
|
|
NL,
|
|
PL,
|
|
PT_BR,
|
|
PT_PT,
|
|
RO,
|
|
RU,
|
|
SK,
|
|
SL,
|
|
SV,
|
|
ZH
|
|
}
|
|
}
|
|
|