Skip to content

Commit 899b6cd

Browse files
committed
Add TranslateExample class, update gcloud-java-examples README
1 parent 5bdc8db commit 899b6cd

3 files changed

Lines changed: 229 additions & 0 deletions

File tree

gcloud-java-examples/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,16 @@ To run examples from your command line:
168168
via the NIO API. It lists gcloud-java-nio as a dependency, and that enables it to interpret
169169
`gs://` paths.
170170
171+
* Here's an example run of `TranslateExample`.
172+
173+
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.
174+
```
175+
target/appassembler/bin/TranslateExample <apiKey> languages
176+
target/appassembler/bin/TranslateExample <apiKey> detect Hello,\ World!
177+
target/appassembler/bin/TranslateExample <apiKey> translate ¡Hola\ Mundo!
178+
target/appassembler/bin/TranslateExample <apiKey> es translate Hello,\ World!
179+
```
180+
171181
Troubleshooting
172182
---------------
173183

gcloud-java-examples/pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,10 @@
100100
<mainClass>com.google.cloud.examples.storage.StorageExample</mainClass>
101101
<name>StorageExample</name>
102102
</program>
103+
<program>
104+
<mainClass>com.google.cloud.examples.translate.TranslateExample</mainClass>
105+
<name>TranslateExample</name>
106+
</program>
103107
</programs>
104108
</configuration>
105109
</plugin>
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.cloud.examples.translate;
18+
19+
import com.google.cloud.translate.Detection;
20+
import com.google.cloud.translate.Language;
21+
import com.google.cloud.translate.Translate;
22+
import com.google.cloud.translate.TranslateOptions;
23+
import com.google.cloud.translate.Translation;
24+
25+
import java.util.Arrays;
26+
import java.util.HashMap;
27+
import java.util.List;
28+
import java.util.Map;
29+
30+
/**
31+
* An example of using Google Translate.
32+
*
33+
* <p>This example demonstrates a simple/typical Translate usage.
34+
*
35+
* <p>See the
36+
* <a href="https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/gcloud-java-examples/README.md">
37+
* README</a> for compilation instructions. Run this code with
38+
* <pre>{@code target/appassembler/bin/TranslateExample
39+
* -Dexec.args="<apiKey> [<targetLanguage>]
40+
* list languages <languageCode>?
41+
* detect <text>+
42+
* translate <text>+"}</pre>
43+
*
44+
* <p>The first parameter is an optional {@code targetLanguage}. If the target language is not
45+
* supplied, {@code en} is used (see {@link TranslateOptions.Builder#targetLanguage(String)}).
46+
*/
47+
public class TranslateExample {
48+
49+
private static final Map<String, TranslateAction> ACTIONS = new HashMap<>();
50+
51+
private abstract static class TranslateAction<T> {
52+
53+
abstract void run(Translate translate, T arg) throws Exception;
54+
55+
abstract T parse(String... args) throws Exception;
56+
57+
protected String params() {
58+
return "";
59+
}
60+
}
61+
62+
/**
63+
* This class demonstrates how to list supported languages.
64+
*
65+
* @see <a href="https://cloud.google.com/translate/v2/discovering-supported-languages-with-rest">
66+
* Discovering Supported Languages</a>
67+
*/
68+
private static class ListLanguagesAction extends TranslateAction<Void> {
69+
@Override
70+
public void run(Translate translate, Void arg) {
71+
List<Language> languages = translate.listSupportedLanguages();
72+
System.out.println("Supported languages:");
73+
for (Language language : languages) {
74+
System.out.println(language);
75+
}
76+
}
77+
78+
@Override
79+
Void parse(String... args) throws Exception {
80+
if (args.length == 0) {
81+
return null;
82+
}
83+
throw new IllegalArgumentException("This action takes no arguments.");
84+
}
85+
}
86+
87+
/**
88+
* This class demonstrates how detect the language of some texts.
89+
*
90+
* @see <a href="https://cloud.google.com/translate/v2/detecting-language-with-rest">Detecting
91+
* Language</a>
92+
*/
93+
private static class DetectLanguageAction extends TranslateAction<List<String>> {
94+
@Override
95+
public void run(Translate translate, List<String> texts) {
96+
List<Detection> detections = translate.detect(texts);
97+
if (texts.size() == 1) {
98+
System.out.println("Detected language is:");
99+
} else {
100+
System.out.println("Detected languages are:");
101+
}
102+
for (Detection detection : detections) {
103+
System.out.println(detection);
104+
}
105+
}
106+
107+
@Override
108+
List<String> parse(String... args) throws Exception {
109+
if (args.length >= 1) {
110+
return Arrays.asList(args);
111+
} else {
112+
throw new IllegalArgumentException("Missing required texts.");
113+
}
114+
}
115+
116+
@Override
117+
public String params() {
118+
return "<text>+";
119+
}
120+
}
121+
122+
/**
123+
* This class demonstrates how to translate some texts.
124+
*
125+
* @see <a href="https://cloud.google.com/translate/v2/translating-text-with-rest">Translating
126+
* Text</a>
127+
*/
128+
private static class TranslateTextAction extends TranslateAction<List<String>> {
129+
@Override
130+
public void run(Translate translate, List<String> texts) {
131+
List<Translation> translations = translate.translate(texts);
132+
if (texts.size() == 1) {
133+
System.out.println("Translation is:");
134+
} else {
135+
System.out.println("Translations are:");
136+
}
137+
for (Translation translation : translations) {
138+
System.out.println(translation);
139+
}
140+
}
141+
142+
@Override
143+
List<String> parse(String... args) throws Exception {
144+
if (args.length >= 1) {
145+
return Arrays.asList(args);
146+
} else {
147+
throw new IllegalArgumentException("Missing required texts.");
148+
}
149+
}
150+
151+
@Override
152+
public String params() {
153+
return "<text>+";
154+
}
155+
}
156+
157+
static {
158+
ACTIONS.put("languages", new ListLanguagesAction());
159+
ACTIONS.put("detect", new DetectLanguageAction());
160+
ACTIONS.put("translate", new TranslateTextAction());
161+
}
162+
163+
private static void printUsage() {
164+
StringBuilder actionAndParams = new StringBuilder();
165+
for (Map.Entry<String, TranslateAction> entry : ACTIONS.entrySet()) {
166+
actionAndParams.append(System.lineSeparator()).append('\t').append(entry.getKey());
167+
String param = entry.getValue().params();
168+
if (param != null && !param.isEmpty()) {
169+
actionAndParams.append(' ').append(param);
170+
}
171+
}
172+
System.out.printf("Usage: %s <apiKey> [<targetLanguage>] operation <args>*%s%n",
173+
TranslateExample.class.getSimpleName(), actionAndParams);
174+
}
175+
176+
@SuppressWarnings("unchecked")
177+
public static void main(String... args) throws Exception {
178+
if (args.length < 2) {
179+
System.out.println("Missing required api key and action");
180+
printUsage();
181+
return;
182+
}
183+
TranslateOptions.Builder optionsBuilder = TranslateOptions.builder(args[0]);
184+
TranslateAction action;
185+
String actionName;
186+
if (args.length >= 3 && !ACTIONS.containsKey(args[1])) {
187+
actionName = args[2];
188+
optionsBuilder.targetLanguage(args[1]);
189+
args = Arrays.copyOfRange(args, 3, args.length);
190+
} else {
191+
actionName = args[1];
192+
args = Arrays.copyOfRange(args, 2, args.length);
193+
}
194+
action = ACTIONS.get(actionName);
195+
if (action == null) {
196+
System.out.println("Unrecognized action.");
197+
printUsage();
198+
return;
199+
}
200+
Translate translate = optionsBuilder.build().service();
201+
Object arg;
202+
try {
203+
arg = action.parse(args);
204+
} catch (IllegalArgumentException ex) {
205+
System.out.printf("Invalid input for action '%s'. %s%n", actionName, ex.getMessage());
206+
System.out.printf("Expected: %s%n", action.params());
207+
return;
208+
} catch (Exception ex) {
209+
System.out.println("Failed to parse arguments.");
210+
ex.printStackTrace();
211+
return;
212+
}
213+
action.run(translate, arg);
214+
}
215+
}

0 commit comments

Comments
 (0)