• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 Google LLC
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 /*
18  * EDITING INSTRUCTIONS
19  * This file is referenced in READMEs and javadoc. Any change to this file should be reflected in
20  * the project's READMEs and package-info.java.
21  */
22 
23 package com.google.cloud.examples.translate.snippets;
24 
25 import com.google.cloud.translate.Detection;
26 import com.google.cloud.translate.Translate;
27 import com.google.cloud.translate.Translate.TranslateOption;
28 import com.google.cloud.translate.TranslateOptions;
29 import com.google.cloud.translate.Translation;
30 
31 /**
32  * A snippet for Google Translation showing how to detect the language of some text and translate
33  * some other text.
34  */
35 public class DetectLanguageAndTranslate {
36 
main(String... args)37   public static void main(String... args) {
38     // Create a service object
39     //
40     // If no explicit credentials or API key are set, requests are authenticated using Application
41     // Default Credentials if available; otherwise, using an API key from the GOOGLE_API_KEY
42     // environment variable
43     Translate translate = TranslateOptions.getDefaultInstance().getService();
44 
45     // Text of an "unknown" language to detect and then translate into English
46     final String mysteriousText = "Hola Mundo";
47 
48     // Detect the language of the mysterious text
49     Detection detection = translate.detect(mysteriousText);
50     String detectedLanguage = detection.getLanguage();
51 
52     // Translate the mysterious text to English
53     Translation translation =
54         translate.translate(
55             mysteriousText,
56             TranslateOption.sourceLanguage(detectedLanguage),
57             TranslateOption.targetLanguage("en"));
58 
59     System.out.println(translation.getTranslatedText());
60   }
61 }
62