Search in sources :

Example 1 with TranslateException

use of com.google.cloud.translate.TranslateException in project structr by structr.

the class TranslateFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) {
    if (arrayHasLengthAndAllElementsNotNull(sources, 3)) {
        try {
            final String gctAPIKey = TranslationModule.TranslationAPIKey.getValue();
            if (gctAPIKey == null) {
                logger.error("Google Cloud Translation API Key not configured in structr.conf");
                return "";
            }
            final String text = sources[0].toString();
            final String sourceLanguage = sources[1].toString();
            final String targetLanguage = sources[2].toString();
            final Translate translate = TranslateOptions.builder().apiKey(gctAPIKey).build().service();
            Translation translation = translate.translate(text, TranslateOption.sourceLanguage(sourceLanguage), TranslateOption.targetLanguage(targetLanguage));
            return translation.translatedText();
        } catch (TranslateException te) {
            logger.error("TranslateException: {}", te.getLocalizedMessage());
        } catch (Throwable t) {
            logException(t, "{}: Exception for parameter: {}", new Object[] { getName(), getParametersAsString(sources) });
        }
        return "";
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return usage(ctx.isJavaScriptContext());
}
Also used : Translation(com.google.cloud.translate.Translation) TranslateException(com.google.cloud.translate.TranslateException) Translate(com.google.cloud.translate.Translate)

Aggregations

Translate (com.google.cloud.translate.Translate)1 TranslateException (com.google.cloud.translate.TranslateException)1 Translation (com.google.cloud.translate.Translation)1