Skip to content

Commit 4f4f7a3

Browse files
authored
Bael 9166 (#18337)
* BAEL-9166 added google translator * Split the test method to two * fix syntax error
1 parent 983e4e5 commit 4f4f7a3

File tree

4 files changed

+204
-0
lines changed

4 files changed

+204
-0
lines changed

google-cloud/pom.xml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,18 @@
77
<packaging>jar</packaging>
88
<name>google-cloud</name>
99
<description>Google Cloud Tutorials</description>
10+
<build>
11+
<plugins>
12+
<plugin>
13+
<groupId>org.apache.maven.plugins</groupId>
14+
<artifactId>maven-compiler-plugin</artifactId>
15+
<configuration>
16+
<source>9</source>
17+
<target>9</target>
18+
</configuration>
19+
</plugin>
20+
</plugins>
21+
</build>
1022

1123
<parent>
1224
<groupId>com.baeldung</groupId>
@@ -20,6 +32,11 @@
2032
<artifactId>google-cloud-storage</artifactId>
2133
<version>${google-cloud-storage.version}</version>
2234
</dependency>
35+
<dependency>
36+
<groupId>com.google.cloud</groupId>
37+
<artifactId>google-cloud-translate</artifactId>
38+
<version>${google-cloud-translate.version}</version>
39+
</dependency>
2340
<dependency>
2441
<groupId>org.projectlombok</groupId>
2542
<artifactId>lombok</artifactId>
@@ -30,6 +47,7 @@
3047

3148
<properties>
3249
<google-cloud-storage.version>1.16.0</google-cloud-storage.version>
50+
<google-cloud-translate.version>2.58.0</google-cloud-translate.version>
3351
</properties>
3452

3553
</project>
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package com.baeldung.google.cloud.translator;
2+
3+
import java.io.FileInputStream;
4+
import java.io.IOException;
5+
import java.util.List;
6+
import java.util.stream.Collectors;
7+
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
import com.google.auth.oauth2.GoogleCredentials;
12+
import com.google.cloud.translate.Language;
13+
import com.google.cloud.translate.Translate;
14+
import com.google.cloud.translate.TranslateOptions;
15+
import com.google.cloud.translate.Translation;
16+
import com.google.cloud.translate.v3.GlossaryName;
17+
import com.google.cloud.translate.v3.LocationName;
18+
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
19+
import com.google.cloud.translate.v3.TranslateTextRequest;
20+
import com.google.cloud.translate.v3.TranslateTextResponse;
21+
import com.google.cloud.translate.v3.TranslationServiceClient;
22+
23+
public class Translator {
24+
25+
private static final Logger logger = LoggerFactory.getLogger(Translator.class);
26+
27+
private static Translate translate;
28+
29+
static {
30+
initializeTranslateClient();
31+
}
32+
33+
public static void initializeTranslateClient() {
34+
if (translate == null) {
35+
try {
36+
GoogleCredentials credentials = GoogleCredentials.fromStream(
37+
new FileInputStream("src/main/resources/translator_permission.json")
38+
);
39+
translate = TranslateOptions.newBuilder()
40+
.setCredentials(credentials)
41+
.build()
42+
.getService();
43+
logger.info("Google Translate client initialized.");
44+
} catch (Exception e) {
45+
logger.error("Failed to initialize Google Translate client.", e);
46+
}
47+
}
48+
}
49+
50+
public static void listSupportedLanguages() {
51+
try {
52+
List<Language> languages = translate.listSupportedLanguages();
53+
for (Language language : languages) {
54+
logger.info(String.format("Name: %s, Code: %s", language.getName(), language.getCode()));
55+
}
56+
} catch (Exception e) {
57+
// handle exception
58+
}
59+
}
60+
61+
public static void listSupportedLanguagesWithSpecificLanguage() {
62+
try {
63+
List<Language> languages = translate.listSupportedLanguages(Translate.LanguageListOption.targetLanguage("es"));
64+
for (Language language : languages) {
65+
logger.info(String.format("Name: %s, Code: %s", language.getName(), language.getCode()));
66+
}
67+
} catch (Exception e) {
68+
// handle exception
69+
}
70+
}
71+
72+
public static String translateText(String text, String targetLanguage) {
73+
String s = "";
74+
try {
75+
Translation translation = translate.translate(text, Translate.TranslateOption.targetLanguage(targetLanguage));
76+
s = translation.getTranslatedText();
77+
} catch (Exception e) {
78+
e.printStackTrace();
79+
// handle exception
80+
}
81+
return s;
82+
}
83+
84+
public static String detectLanguage(String text) {
85+
return translate.detect(text)
86+
.getLanguage();
87+
}
88+
89+
public static List<String> translateBatch(List<String> texts, String targetLanguage) {
90+
List<String> translationList = null;
91+
try {
92+
List<Translation> translations = translate.translate(texts, Translate.TranslateOption.targetLanguage(targetLanguage));
93+
translationList = translations.stream()
94+
.map(Translation::getTranslatedText)
95+
.collect(Collectors.toList());
96+
} catch (Exception e) {
97+
// handle exception
98+
}
99+
return translationList;
100+
}
101+
102+
public static String translateWithGlossary(String projectId, String location, String text, String targetLanguage, String glossaryId) {
103+
String translatedText = "";
104+
105+
try (TranslationServiceClient client = TranslationServiceClient.create()) {
106+
LocationName parent = LocationName.of(projectId, location);
107+
GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
108+
109+
TranslateTextRequest request = TranslateTextRequest.newBuilder()
110+
.setParent(parent.toString())
111+
.setTargetLanguageCode(targetLanguage)
112+
.addContents(text)
113+
.setGlossaryConfig(TranslateTextGlossaryConfig.newBuilder()
114+
.setGlossary(glossaryName.toString()).build()) // Attach glossary
115+
.build();
116+
117+
TranslateTextResponse response = client.translateText(request);
118+
translatedText = response.getTranslations(0).getTranslatedText();
119+
} catch (IOException e) {
120+
// handle exception
121+
}
122+
return translatedText;
123+
}
124+
125+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"type": "service_account",
3+
"project_id": "baeldungtutorial",
4+
"private_key_id": "xxxxxx",
5+
"private_key": "-----BEGIN PRIVATE KEY-----\n XXXXXXX \n-----END PRIVATE KEY-----\n",
6+
"client_email": "[email protected]",
7+
"client_id": "xxxxxx",
8+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
9+
"token_uri": "https://oauth2.googleapis.com/token",
10+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/translator%40baeldungtutorial.iam.gserviceaccount.com",
12+
"universe_domain": "googleapis.com"
13+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.baeldung.google.cloud.translator;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.List;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
public class TranslatorLiveTest {
10+
11+
@Test
12+
void whenTranslateTextIsCalledWithEnglishTextAndFrenchTargetLanguage_thenReturnTranslatedText() {
13+
String originalText = "Hello, world!";
14+
String targetLanguage = "es";
15+
String expectedTranslatedText = "¡Hola Mundo!";
16+
17+
String translatedText = Translator.translateText(originalText, targetLanguage);
18+
19+
assertEquals(expectedTranslatedText, translatedText);
20+
}
21+
22+
@Test
23+
void whenTranslateTextIsCalledWithEnglishHTMLAndFrenchTargetLanguage_thenReturnTranslatedHTML() {
24+
String originalHtml = "<p>Hello, world!</p>";
25+
String targetLanguage = "es";
26+
String expectedTranslatedHtml = "<p>¡Hola Mundo!</p>";
27+
28+
String translatedHtml = Translator.translateText(originalHtml, targetLanguage);
29+
30+
assertEquals(expectedTranslatedHtml, translatedHtml);
31+
}
32+
33+
@Test
34+
void whenDetectLanguageIsCalledWithSpanishText_thenReturnSpanishLanguageCode() {
35+
String text = "Hola, mundo!";
36+
String expectedLanguageCode = "es";
37+
String detectedLanguage = Translator.detectLanguage(text);
38+
assertEquals(expectedLanguageCode, detectedLanguage);
39+
}
40+
41+
@Test
42+
void whenTranslateBatchIsCalledWithMultipleTexts_thenReturnTranslatedTexts() {
43+
List<String> originalTexts = List.of("Apple", "Banana", "Orange");
44+
List<String> expectedTranslatedTexts = List.of("Pomme", "Banane", "Orange");
45+
List<String> translatedTexts = Translator.translateBatch(originalTexts, "fr");
46+
assertEquals(expectedTranslatedTexts, translatedTexts);
47+
}
48+
}

0 commit comments

Comments
 (0)