diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md index 0eed7ca402f5..4db9fed26be2 100644 --- a/gcloud-java-examples/README.md +++ b/gcloud-java-examples/README.md @@ -168,6 +168,16 @@ To run examples from your command line: via the NIO API. It lists gcloud-java-nio as a dependency, and that enables it to interpret `gs://` paths. + * Here's an example run of `TranslateExample`. + + Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translate API" is enabled and that you have a valid API key. + ``` + target/appassembler/bin/TranslateExample languages + target/appassembler/bin/TranslateExample detect Hello,\ World! + target/appassembler/bin/TranslateExample translate ¡Hola\ Mundo! + target/appassembler/bin/TranslateExample es translate Hello,\ World! + ``` + Troubleshooting --------------- diff --git a/gcloud-java-examples/pom.xml b/gcloud-java-examples/pom.xml index 6a1052a49e21..92faf02019cd 100644 --- a/gcloud-java-examples/pom.xml +++ b/gcloud-java-examples/pom.xml @@ -100,6 +100,10 @@ com.google.cloud.examples.storage.StorageExample StorageExample + + com.google.cloud.examples.translate.TranslateExample + TranslateExample + diff --git a/gcloud-java-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java b/gcloud-java-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java new file mode 100644 index 000000000000..3b2e10a7bee8 --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java @@ -0,0 +1,215 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * 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.google.cloud.examples.translate; + +import com.google.cloud.translate.Detection; +import com.google.cloud.translate.Language; +import com.google.cloud.translate.Translate; +import com.google.cloud.translate.TranslateOptions; +import com.google.cloud.translate.Translation; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * An example of using Google Translate. + * + *

This example demonstrates a simple/typical Translate usage. + * + *

See the + * + * README for compilation instructions. Run this code with + *

{@code target/appassembler/bin/TranslateExample
+ *  -Dexec.args=" []
+ *  list languages ?
+ *  detect +
+ *  translate +"}
+ * + *

The first parameter is an optional {@code targetLanguage}. If the target language is not + * supplied, {@code en} is used (see {@link TranslateOptions.Builder#targetLanguage(String)}). + */ +public class TranslateExample { + + private static final Map ACTIONS = new HashMap<>(); + + private abstract static class TranslateAction { + + abstract void run(Translate translate, T arg) throws Exception; + + abstract T parse(String... args) throws Exception; + + protected String params() { + return ""; + } + } + + /** + * This class demonstrates how to list supported languages. + * + * @see + * Discovering Supported Languages + */ + private static class ListLanguagesAction extends TranslateAction { + @Override + public void run(Translate translate, Void arg) { + List languages = translate.listSupportedLanguages(); + System.out.println("Supported languages:"); + for (Language language : languages) { + System.out.println(language); + } + } + + @Override + Void parse(String... args) throws Exception { + if (args.length == 0) { + return null; + } + throw new IllegalArgumentException("This action takes no arguments."); + } + } + + /** + * This class demonstrates how detect the language of some texts. + * + * @see Detecting + * Language + */ + private static class DetectLanguageAction extends TranslateAction> { + @Override + public void run(Translate translate, List texts) { + List detections = translate.detect(texts); + if (texts.size() == 1) { + System.out.println("Detected language is:"); + } else { + System.out.println("Detected languages are:"); + } + for (Detection detection : detections) { + System.out.println(detection); + } + } + + @Override + List parse(String... args) throws Exception { + if (args.length >= 1) { + return Arrays.asList(args); + } else { + throw new IllegalArgumentException("Missing required texts."); + } + } + + @Override + public String params() { + return "+"; + } + } + + /** + * This class demonstrates how to translate some texts. + * + * @see Translating + * Text + */ + private static class TranslateTextAction extends TranslateAction> { + @Override + public void run(Translate translate, List texts) { + List translations = translate.translate(texts); + if (texts.size() == 1) { + System.out.println("Translation is:"); + } else { + System.out.println("Translations are:"); + } + for (Translation translation : translations) { + System.out.println(translation); + } + } + + @Override + List parse(String... args) throws Exception { + if (args.length >= 1) { + return Arrays.asList(args); + } else { + throw new IllegalArgumentException("Missing required texts."); + } + } + + @Override + public String params() { + return "+"; + } + } + + static { + ACTIONS.put("languages", new ListLanguagesAction()); + ACTIONS.put("detect", new DetectLanguageAction()); + ACTIONS.put("translate", new TranslateTextAction()); + } + + private static void printUsage() { + StringBuilder actionAndParams = new StringBuilder(); + for (Map.Entry entry : ACTIONS.entrySet()) { + actionAndParams.append(System.lineSeparator()).append('\t').append(entry.getKey()); + String param = entry.getValue().params(); + if (param != null && !param.isEmpty()) { + actionAndParams.append(' ').append(param); + } + } + System.out.printf("Usage: %s [] operation *%s%n", + TranslateExample.class.getSimpleName(), actionAndParams); + } + + @SuppressWarnings("unchecked") + public static void main(String... args) throws Exception { + if (args.length < 2) { + System.out.println("Missing required api key and action"); + printUsage(); + return; + } + TranslateOptions.Builder optionsBuilder = TranslateOptions.builder(args[0]); + TranslateAction action; + String actionName; + if (args.length >= 3 && !ACTIONS.containsKey(args[1])) { + actionName = args[2]; + optionsBuilder.targetLanguage(args[1]); + args = Arrays.copyOfRange(args, 3, args.length); + } else { + actionName = args[1]; + args = Arrays.copyOfRange(args, 2, args.length); + } + action = ACTIONS.get(actionName); + if (action == null) { + System.out.println("Unrecognized action."); + printUsage(); + return; + } + Object arg; + try { + arg = action.parse(args); + } catch (IllegalArgumentException ex) { + System.out.printf("Invalid input for action '%s'. %s%n", actionName, ex.getMessage()); + System.out.printf("Expected: %s%n", action.params()); + return; + } catch (Exception ex) { + System.out.println("Failed to parse arguments."); + ex.printStackTrace(); + return; + } + Translate translate = optionsBuilder.build().service(); + action.run(translate, arg); + } +}