Skip to content

Instantly share code, notes, and snippets.

@nejckorasa
Created July 25, 2018 06:31
Show Gist options
  • Select an option

  • Save nejckorasa/425519cfde0954642382f88fd4031382 to your computer and use it in GitHub Desktop.

Select an option

Save nejckorasa/425519cfde0954642382f88fd4031382 to your computer and use it in GitHub Desktop.
Translator using yandex translations
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.annotation.Nonnull;
import javax.net.ssl.HttpsURLConnection;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.google.common.base.Preconditions;
/**
* @author Nejc Korasa
*/
public final class Translator
{
private String apiKey = null;
private static final String SERVICE_BASE_URL = "https://translate.yandex.net/api/v1.5/tr.json/translate?";
private static final String ENCODING = "UTF-8";
/**
* Creates Translator instance
*
* @param apiKey an api key to access API
*
* @see <a href="http://tech.yandex.com/translate"></a> for more details
*/
public Translator(@Nonnull final String apiKey)
{
// see https://tech.yandex.com/translate
this.apiKey = Preconditions.checkNotNull(apiKey, "apiKey");
}
/**
* Translates text from one {@link Language} to another.
*
* @param text text to be translated
* @param from language that text is translated from
* @param to language that text is translated to
*
* @return translated text
*/
public String translate(@Nonnull final String text, @Nonnull final Language from, @Nonnull final Language to) throws Exception
{
Preconditions.checkNotNull(text, "text");
Preconditions.checkNotNull(from, "from");
Preconditions.checkNotNull(to, "to");
if (text.getBytes(ENCODING).length > 10240)
{
throw new RuntimeException("Text too large");
}
final URL url = buildUrl(text, from, to);
return getResponse(url);
}
private URL buildUrl(final String text, final Language from, final Language to) throws UnsupportedEncodingException, MalformedURLException
{
final String apiParam = "key=" + URLEncoder.encode(apiKey, ENCODING);
final String langParam = "lang="
+ URLEncoder.encode(from.getKey(), ENCODING)
+ URLEncoder.encode("-", ENCODING)
+ URLEncoder.encode(to.getKey(), ENCODING);
final String textParam = "text=" + URLEncoder.encode(text, ENCODING);
final String params = apiParam + "&" + langParam + "&" + textParam;
return new URL(SERVICE_BASE_URL + params);
}
private String getResponse(final URL url) throws Exception
{
final HttpsURLConnection uc = (HttpsURLConnection)url.openConnection();
uc.setRequestProperty("Content-Type", "text/plain; charset=" + ENCODING);
uc.setRequestProperty("Accept-Charset", ENCODING);
uc.setRequestMethod("GET");
try
{
final int responseCode = uc.getResponseCode();
final String result = inputStreamToString(uc.getInputStream());
if (responseCode != 200)
{
throw new RuntimeException("Error from translator API: " + result);
}
return parseJsonResponse(result.trim());
}
finally
{
uc.disconnect();
}
}
private String parseJsonResponse(final String response) throws IOException
{
final JsonFactory factory = new JsonFactory();
final JsonParser parser = factory.createParser(response);
while (!parser.isClosed())
{
final JsonToken jsonToken = parser.nextToken();
if (jsonToken == JsonToken.FIELD_NAME)
{
final String fieldName = parser.getCurrentName();
if ("text".equals(fieldName))
{
parser.nextToken();
parser.nextToken();
return parser.getValueAsString();
}
parser.nextToken();
}
}
return null;
}
@SuppressWarnings("NestedAssignment")
private String inputStreamToString(final InputStream inputStream) throws Exception
{
final StringBuilder output = new StringBuilder();
//noinspection OverlyBroadCatchBlock
try
{
if (inputStream != null)
{
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING)))
{
String line;
while ((line = reader.readLine()) != null)
{
//noinspection DynamicRegexReplaceableByCompiledPattern
output.append(line.replaceAll("\uFEFF", ""));
}
}
}
}
catch (final Exception ex)
{
throw new Exception("Error reading translation stream!", ex);
}
return output.toString();
}
@SuppressWarnings("unused")
public enum Language
{
ENGLISH("en"),
GERMAN("de"),
GREEK("el"),
POLISH("pl"),
PORTUGUESE("pt"),
RUSSIAN("ru"),
SLOVENIAN("sl");
private final String key;
Language(final String key)
{
this.key = key;
}
public String getKey()
{
return key;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment