diff --git a/jobs/v3/src/main/java/com/google/samples/GeneralSearchSample.java b/jobs/v3/src/main/java/com/google/samples/GeneralSearchSample.java index cd006097f85..7c2ee11384e 100644 --- a/jobs/v3/src/main/java/com/google/samples/GeneralSearchSample.java +++ b/jobs/v3/src/main/java/com/google/samples/GeneralSearchSample.java @@ -58,6 +58,7 @@ public final class GeneralSearchSample { private static CloudTalentSolution talentSolutionClient = JobServiceQuickstart.getTalentSolutionClient(); + // [START job_discovery_basic_keyword_search] // [START basic_keyword_search] /** Simple search jobs with keyword. */ @@ -95,7 +96,9 @@ public static void basicSearcJobs(String companyName, String query) System.out.printf("Simple search jobs results: %s\n", searchJobsResponse); } // [END basic_keyword_search] - + // [END job_discovery_basic_keyword_search] + + // [START job_discovery_category_filter_search] // [START category_filter] /** Search on category filter. */ @@ -133,7 +136,9 @@ public static void categoryFilterSearch(String companyName, List categor System.out.printf("Category search jobs results: %s\n", searchJobsResponse); } // [END category_filter] + // [END job_discovery_category_filter_search] + // [START job_discovery_employment_types_filter_search] // [START employment_types_filter] /** Search on employment types. */ @@ -171,7 +176,9 @@ public static void employmentTypesSearch(String companyName, List employ System.out.printf("Employee type search jobs results: %s\n", searchJobsResponse); } // [END employment_types_filter] + // [END job_discovery_employment_types_filter_search] + // [START job_discovery_date_range_filter_search] // [START date_range_filter] /** @@ -218,7 +225,9 @@ public static void dateRangeSearch(String companyName, String startTime, String System.out.printf("Search results on jobs with a date range: %s\n", searchJobsResponse); } // [END date_range_filter] + // [END job_discovery_date_range_filter_search] + // [START job_discovery_language_code_filter_search] // [START language_code_filter] /** Search on language codes. */ @@ -256,7 +265,9 @@ public static void languageCodeSearch(String companyName, List languageC System.out.printf("Search results on jobs with a language code: %s\n", searchJobsResponse); } // [END language_code_filter] + // [END job_discovery_language_code_filter_search] + // [START job_discovery_company_display_name_search] // [START company_display_name_filter] /** Search on company display name. */ @@ -294,7 +305,9 @@ public static void companyDisplayNameSearch(String companyName, List com System.out.printf("Search results by display name of company: %s\n", searchJobsResponse); } // [END company_display_name_filter] - + // [END job_discovery_company_display_name_search] + + // [START job_discovery_compensation_search] // [START compensation_filter] /** Search on compensation. */ @@ -346,6 +359,7 @@ public static void compensationSearch(String companyName) System.out.printf("Search results by compensation: %s\n", searchJobsResponse); } // [END compensation_filter] + // [END job_discovery_compensation_search] public static void main(String... args) throws Exception { Company companyToBeCreated = BasicCompanySample.generateCompany().setDisplayName("Google"); diff --git a/translate/README.md b/translate/README.md deleted file mode 100644 index 1e03b2d9f8d..00000000000 --- a/translate/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Translate Samples have been moved - -[https://github.com/googleapis/java-translate](https://github.com/googleapis/java-translate). \ No newline at end of file diff --git a/translate/pom.xml b/translate/pom.xml new file mode 100644 index 00000000000..cfdcd8e0ef3 --- /dev/null +++ b/translate/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + com.example.translate + translate-snippets + jar + Google Cloud Translate Snippets + https://github.com/GoogleCloudPlatform/java-docs-samples/tree/main/translate + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + 1.8 + 1.8 + UTF-8 + + + + + + + + com.google.cloud + libraries-bom + 26.1.3 + pom + import + + + + + + + com.google.cloud + google-cloud-translate + + + + com.google.cloud + google-cloud-storage + + + junit + junit + 4.13.2 + test + + + com.google.truth + truth + 1.1.3 + test + + + com.google.cloud + google-cloud-core + 2.8.20 + test + tests + + + + + diff --git a/translate/resources/fake_invoice.pdf b/translate/resources/fake_invoice.pdf new file mode 100644 index 00000000000..b9107fba129 Binary files /dev/null and b/translate/resources/fake_invoice.pdf differ diff --git a/translate/snippets/pom.xml b/translate/snippets/pom.xml new file mode 100644 index 00000000000..5a2c8b3c4da --- /dev/null +++ b/translate/snippets/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + com.google.cloud + translate-snippets + jar + Google Cloud Translate Snippets + https://github.com/googleapis/java-translate + + + + com.google.cloud.samples + shared-configuration + 1.2.0 + + + + 1.8 + 1.8 + UTF-8 + + + + + + + + com.google.cloud + libraries-bom + 26.1.3 + pom + import + + + + + + + com.google.cloud + google-cloud-translate + + + + com.google.cloud + google-cloud-storage + + + junit + junit + 4.13.2 + test + + + com.google.truth + truth + 1.1.3 + test + + + com.google.cloud + google-cloud-core + 2.8.20 + test + tests + + + + + diff --git a/translate/snippets/resources/fake_invoice.pdf b/translate/snippets/resources/fake_invoice.pdf new file mode 100644 index 00000000000..b9107fba129 Binary files /dev/null and b/translate/snippets/resources/fake_invoice.pdf differ diff --git a/translate/snippets/src/main/java/com/example/translate/BatchTranslateText.java b/translate/snippets/src/main/java/com/example/translate/BatchTranslateText.java new file mode 100644 index 00000000000..6f0f20138dd --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/BatchTranslateText.java @@ -0,0 +1,99 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateText { + + public static void batchTranslateText() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + batchTranslateText(projectId, sourceLanguage, targetLanguage, inputUri, outputUri); + } + + // Batch translate text + public static void batchTranslateText( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `us-central1` + LocationName parent = LocationName.of(projectId, "us-central1"); + + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .build(); + + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text] diff --git a/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java b/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java new file mode 100644 index 00000000000..6c5b713c9bc --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java @@ -0,0 +1,118 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text_with_glossary] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateTextWithGlossary { + + public static void batchTranslateTextWithGlossary() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + String glossaryId = "your-glossary-display-name"; + batchTranslateTextWithGlossary( + projectId, sourceLanguage, targetLanguage, inputUri, outputUri, glossaryId); + } + + // Batch Translate Text with a Glossary. + public static void batchTranslateTextWithGlossary( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + String glossaryId) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + // Configure where to store the output in a GCS bucket + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + // Configure the glossary used in the request + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + // Build the request that will be sent to the API + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .putGlossaries(targetLanguage, glossaryConfig) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + // Display the translation for each input text provided + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text_with_glossary] diff --git a/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java b/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java new file mode 100644 index 00000000000..0fe8bd26802 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java @@ -0,0 +1,125 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text_with_glossary_and_model] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateTextWithGlossaryAndModel { + + public static void batchTranslateTextWithGlossaryAndModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + String glossaryId = "your-glossary-display-name"; + String modelId = "YOUR-MODEL-ID"; + batchTranslateTextWithGlossaryAndModel( + projectId, sourceLanguage, targetLanguage, inputUri, outputUri, glossaryId, modelId); + } + + // Batch translate text with Model and Glossary + public static void batchTranslateTextWithGlossaryAndModel( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + String glossaryId, + String modelId) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + // Configure where to store the output in a GCS bucket + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + // Configure the glossary used in the request + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + // Configure the model used in the request + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Build the request that will be sent to the API + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .putGlossaries(targetLanguage, glossaryConfig) + .putModels(targetLanguage, modelPath) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + // Display the translation for each input text provided + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text_with_glossary_and_model] diff --git a/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithModel.java b/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithModel.java new file mode 100644 index 00000000000..216a2060e30 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/BatchTranslateTextWithModel.java @@ -0,0 +1,115 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text_with_model] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateTextWithModel { + + public static void batchTranslateTextWithModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + String modelId = "YOUR-MODEL-ID"; + batchTranslateTextWithModel( + projectId, sourceLanguage, targetLanguage, inputUri, outputUri, modelId); + } + + // Batch translate text using AutoML Translation model + public static void batchTranslateTextWithModel( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + String modelId) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + // Configure where to store the output in a GCS bucket + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + // Configure the model used in the request + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Build the request that will be sent to the API + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .putModels(targetLanguage, modelPath) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + // Display the translation for each input text provided + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text_with_model] diff --git a/translate/snippets/src/main/java/com/example/translate/CreateGlossary.java b/translate/snippets/src/main/java/com/example/translate/CreateGlossary.java new file mode 100644 index 00000000000..ab9f7de4f0e --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/CreateGlossary.java @@ -0,0 +1,98 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_create_glossary] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.CreateGlossaryMetadata; +import com.google.cloud.translate.v3.CreateGlossaryRequest; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.Glossary; +import com.google.cloud.translate.v3.GlossaryInputConfig; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; + +public class CreateGlossary { + + public static void createGlossary() throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String glossaryId = "your-glossary-display-name"; + List languageCodes = new ArrayList<>(); + languageCodes.add("your-language-code"); + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + createGlossary(projectId, glossaryId, languageCodes, inputUri); + } + + // Create a equivalent term sets glossary + // https://cloud.google.com/translate/docs/advanced/glossary#format-glossary + public static void createGlossary( + String projectId, String glossaryId, List languageCodes, String inputUri) + throws IOException, ExecutionException, InterruptedException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + + // Supported Languages: https://cloud.google.com/translate/docs/languages + Glossary.LanguageCodesSet languageCodesSet = + Glossary.LanguageCodesSet.newBuilder().addAllLanguageCodes(languageCodes).build(); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + GlossaryInputConfig inputConfig = + GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build(); + + Glossary glossary = + Glossary.newBuilder() + .setName(glossaryName.toString()) + .setLanguageCodesSet(languageCodesSet) + .setInputConfig(inputConfig) + .build(); + + CreateGlossaryRequest request = + CreateGlossaryRequest.newBuilder() + .setParent(parent.toString()) + .setGlossary(glossary) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.createGlossaryAsync(request); + + System.out.println("Waiting for operation to complete..."); + Glossary response = future.get(); + System.out.println("Created Glossary."); + System.out.printf("Glossary name: %s\n", response.getName()); + System.out.printf("Entry count: %s\n", response.getEntryCount()); + System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri()); + } + } +} +// [END translate_v3_create_glossary] diff --git a/translate/snippets/src/main/java/com/example/translate/DeleteGlossary.java b/translate/snippets/src/main/java/com/example/translate/DeleteGlossary.java new file mode 100644 index 00000000000..78266cdb5e1 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/DeleteGlossary.java @@ -0,0 +1,63 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_delete_glossary] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.DeleteGlossaryMetadata; +import com.google.cloud.translate.v3.DeleteGlossaryRequest; +import com.google.cloud.translate.v3.DeleteGlossaryResponse; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class DeleteGlossary { + + public static void deleteGlossary() throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String glossaryId = "your-glossary-display-name"; + deleteGlossary(projectId, glossaryId); + } + + // Delete a specific glossary based on the glossary ID + public static void deleteGlossary(String projectId, String glossaryId) + throws InterruptedException, ExecutionException, IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId); + DeleteGlossaryRequest request = + DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build(); + + // Start an asynchronous request + OperationFuture future = + client.deleteGlossaryAsync(request); + + System.out.println("Waiting for operation to complete..."); + DeleteGlossaryResponse response = future.get(); + System.out.format("Deleted Glossary: %s\n", response.getName()); + } + } +} +// [END translate_v3_delete_glossary] diff --git a/translate/snippets/src/main/java/com/example/translate/DetectLanguage.java b/translate/snippets/src/main/java/com/example/translate/DetectLanguage.java new file mode 100644 index 00000000000..a1b4c5fb19f --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/DetectLanguage.java @@ -0,0 +1,70 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_detect_language] +import com.google.cloud.translate.v3.DetectLanguageRequest; +import com.google.cloud.translate.v3.DetectLanguageResponse; +import com.google.cloud.translate.v3.DetectedLanguage; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class DetectLanguage { + + public static void detectLanguage() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String text = "your-text"; + + detectLanguage(projectId, text); + } + + // Detecting the language of a text string + public static void detectLanguage(String projectId, String text) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + DetectLanguageRequest request = + DetectLanguageRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setContent(text) + .build(); + + DetectLanguageResponse response = client.detectLanguage(request); + + // Display list of detected languages sorted by detection confidence. + // The most probable language is first. + for (DetectedLanguage language : response.getLanguagesList()) { + // The language detected + System.out.printf("Language code: %s\n", language.getLanguageCode()); + // Confidence of detection result for this language + System.out.printf("Confidence: %s\n", language.getConfidence()); + } + } + } +} +// [END translate_v3_detect_language] diff --git a/translate/snippets/src/main/java/com/example/translate/GetGlossary.java b/translate/snippets/src/main/java/com/example/translate/GetGlossary.java new file mode 100644 index 00000000000..c3e8283bd13 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/GetGlossary.java @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_get_glossary] +import com.google.cloud.translate.v3.GetGlossaryRequest; +import com.google.cloud.translate.v3.Glossary; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class GetGlossary { + + public static void getGlossary() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String glossaryId = "your-glossary-display-name"; + getGlossary(projectId, glossaryId); + } + + // Get a particular glossary based on the glossary ID + public static void getGlossary(String projectId, String glossaryId) throws IOException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId); + GetGlossaryRequest request = + GetGlossaryRequest.newBuilder().setName(glossaryName.toString()).build(); + + Glossary response = client.getGlossary(request); + + System.out.printf("Glossary name: %s\n", response.getName()); + System.out.printf("Entry count: %s\n", response.getEntryCount()); + System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri()); + } + } +} +// [END translate_v3_get_glossary] diff --git a/translate/snippets/src/main/java/com/example/translate/GetSupportedLanguages.java b/translate/snippets/src/main/java/com/example/translate/GetSupportedLanguages.java new file mode 100644 index 00000000000..08eb5d46b65 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/GetSupportedLanguages.java @@ -0,0 +1,58 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_get_supported_languages] +import com.google.cloud.translate.v3.GetSupportedLanguagesRequest; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.SupportedLanguage; +import com.google.cloud.translate.v3.SupportedLanguages; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class GetSupportedLanguages { + + public static void getSupportedLanguages() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + getSupportedLanguages(projectId); + } + + // Getting a list of supported language codes + public static void getSupportedLanguages(String projectId) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + GetSupportedLanguagesRequest request = + GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build(); + + SupportedLanguages response = client.getSupportedLanguages(request); + + // List language codes of supported languages + for (SupportedLanguage language : response.getLanguagesList()) { + System.out.printf("Language Code: %s\n", language.getLanguageCode()); + } + } + } +} +// [END translate_v3_get_supported_languages] diff --git a/translate/snippets/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java b/translate/snippets/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java new file mode 100644 index 00000000000..d3de319ad5c --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java @@ -0,0 +1,65 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_get_supported_languages_for_target] +import com.google.cloud.translate.v3.GetSupportedLanguagesRequest; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.SupportedLanguage; +import com.google.cloud.translate.v3.SupportedLanguages; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class GetSupportedLanguagesForTarget { + + public static void getSupportedLanguagesForTarget() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String languageCode = "your-language-code"; + getSupportedLanguagesForTarget(projectId, languageCode); + } + + // Listing supported languages with target language name + public static void getSupportedLanguagesForTarget(String projectId, String languageCode) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + GetSupportedLanguagesRequest request = + GetSupportedLanguagesRequest.newBuilder() + .setParent(parent.toString()) + .setDisplayLanguageCode(languageCode) + .build(); + + SupportedLanguages response = client.getSupportedLanguages(request); + + // List language codes of supported languages + for (SupportedLanguage language : response.getLanguagesList()) { + System.out.printf("Language Code: %s\n", language.getLanguageCode()); + System.out.printf("Display Name: %s\n", language.getDisplayName()); + } + } + } +} +// [END translate_v3_get_supported_languages_for_target] diff --git a/translate/snippets/src/main/java/com/example/translate/ListGlossaries.java b/translate/snippets/src/main/java/com/example/translate/ListGlossaries.java new file mode 100644 index 00000000000..129d58ec7b7 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/ListGlossaries.java @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_list_glossary] +import com.google.cloud.translate.v3.Glossary; +import com.google.cloud.translate.v3.ListGlossariesRequest; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class ListGlossaries { + + public static void listGlossaries() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + listGlossaries(projectId); + } + + // List all the glossaries in a specified location + public static void listGlossaries(String projectId) throws IOException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "us-central1"); + ListGlossariesRequest request = + ListGlossariesRequest.newBuilder().setParent(parent.toString()).build(); + + for (Glossary responseItem : client.listGlossaries(request).iterateAll()) { + System.out.printf("Glossary name: %s\n", responseItem.getName()); + System.out.printf("Entry count: %s\n", responseItem.getEntryCount()); + System.out.printf( + "Input URI: %s\n", responseItem.getInputConfig().getGcsSource().getInputUri()); + } + } + } +} +// [END translate_v3_list_glossary] diff --git a/translate/snippets/src/main/java/com/example/translate/QuickstartSample.java b/translate/snippets/src/main/java/com/example/translate/QuickstartSample.java new file mode 100644 index 00000000000..d946c13aada --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/QuickstartSample.java @@ -0,0 +1,43 @@ +/* + * Copyright 2016 Google Inc. + * + * 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.example.translate; + +// [START translate_quickstart] +// Imports the Google Cloud client library +import com.google.cloud.translate.Translate; +import com.google.cloud.translate.Translate.TranslateOption; +import com.google.cloud.translate.TranslateOptions; +import com.google.cloud.translate.Translation; + +public class QuickstartSample { + public static void main(String... args) throws Exception { + // Instantiates a client + Translate translate = TranslateOptions.getDefaultInstance().getService(); + + // The text to translate + String text = "Hello, world!"; + + // Translates some text into Russian + Translation translation = + translate.translate( + text, TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage("ru")); + + System.out.printf("Text: %s%n", text); + System.out.printf("Translation: %s%n", translation.getTranslatedText()); + } +} +// [END translate_quickstart] diff --git a/translate/snippets/src/main/java/com/example/translate/TranslateText.java b/translate/snippets/src/main/java/com/example/translate/TranslateText.java new file mode 100644 index 00000000000..a18fed2b694 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/TranslateText.java @@ -0,0 +1,78 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_translate_text] +// [START translate_v3_translate_text_0] +// Imports the Google Cloud Translation library. +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +// [END translate_v3_translate_text_0] + +public class TranslateText { + + // [START translate_v3_translate_text_1] + // Set and pass variables to overloaded translateText() method for translation. + public static void translateText() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String targetLanguage = "your-target-language"; + String text = "your-text"; + translateText(projectId, targetLanguage, text); + } + // [END translate_v3_translate_text_1] + + // [START translate_v3_translate_text_2] + // Translate text to target language. + public static void translateText(String projectId, String targetLanguage, String text) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } + // [END translate_v3_translate_text_2] +} +// [END translate_v3_translate_text] diff --git a/translate/snippets/src/main/java/com/example/translate/TranslateTextWithGlossary.java b/translate/snippets/src/main/java/com/example/translate/TranslateTextWithGlossary.java new file mode 100644 index 00000000000..78c35aa66e7 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/TranslateTextWithGlossary.java @@ -0,0 +1,85 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_translate_text_with_glossary] +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class TranslateTextWithGlossary { + + public static void translateTextWithGlossary() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String text = "your-text"; + String glossaryId = "your-glossary-display-name"; + translateTextWithGlossary(projectId, sourceLanguage, targetLanguage, text, glossaryId); + } + + // Translates a given text using a glossary. + public static void translateTextWithGlossary( + String projectId, + String sourceLanguage, + String targetLanguage, + String text, + String glossaryId) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setSourceLanguageCode(sourceLanguage) + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .setGlossaryConfig(glossaryConfig) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getGlossaryTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } +} +// [END translate_v3_translate_text_with_glossary] diff --git a/translate/snippets/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java b/translate/snippets/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java new file mode 100644 index 00000000000..a383689deec --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java @@ -0,0 +1,92 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_translate_text_with_glossary_and_model] +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class TranslateTextWithGlossaryAndModel { + + public static void translateTextWithGlossaryAndModel() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String text = "your-text"; + String glossaryId = "your-glossary-display-name"; + String modelId = "YOUR-MODEL-ID"; + translateTextWithGlossaryAndModel( + projectId, sourceLanguage, targetLanguage, text, glossaryId, modelId); + } + + // Translating Text with Glossary and Model + public static void translateTextWithGlossaryAndModel( + String projectId, + String sourceLanguage, + String targetLanguage, + String text, + String glossaryId, + String modelId) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setSourceLanguageCode(sourceLanguage) + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .setGlossaryConfig(glossaryConfig) + .setModel(modelPath) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getGlossaryTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } +} +// [END translate_v3_translate_text_with_glossary_and_model] diff --git a/translate/snippets/src/main/java/com/example/translate/TranslateTextWithModel.java b/translate/snippets/src/main/java/com/example/translate/TranslateTextWithModel.java new file mode 100644 index 00000000000..9d81c7979d9 --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translate/TranslateTextWithModel.java @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_translate_text_with_model] +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class TranslateTextWithModel { + + public static void translateTextWithModel() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String text = "your-text"; + String modelId = "YOUR-MODEL-ID"; + translateTextWithModel(projectId, sourceLanguage, targetLanguage, text, modelId); + } + + // Translating Text with Model + public static void translateTextWithModel( + String projectId, String sourceLanguage, String targetLanguage, String text, String modelId) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setSourceLanguageCode(sourceLanguage) + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .setModel(modelPath) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } +} +// [END translate_v3_translate_text_with_model] diff --git a/translate/snippets/src/main/java/com/example/translatev3beta1/BatchTranslateDocument.java b/translate/snippets/src/main/java/com/example/translatev3beta1/BatchTranslateDocument.java new file mode 100644 index 00000000000..13e449d153a --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translatev3beta1/BatchTranslateDocument.java @@ -0,0 +1,123 @@ +/* + * Copyright 2021 Google LLC + * + * 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.example.translatev3beta1; + +// [START translate_v3beta1_batch_translate_document] + +import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.retrying.TimedRetryAlgorithm; +import com.google.cloud.translate.v3beta1.BatchDocumentInputConfig; +import com.google.cloud.translate.v3beta1.BatchDocumentOutputConfig; +import com.google.cloud.translate.v3beta1.BatchTranslateDocumentMetadata; +import com.google.cloud.translate.v3beta1.BatchTranslateDocumentRequest; +import com.google.cloud.translate.v3beta1.BatchTranslateDocumentResponse; +import com.google.cloud.translate.v3beta1.GcsDestination; +import com.google.cloud.translate.v3beta1.GcsSource; +import com.google.cloud.translate.v3beta1.LocationName; +import com.google.cloud.translate.v3beta1.TranslationServiceClient; +import com.google.cloud.translate.v3beta1.TranslationServiceSettings; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.threeten.bp.Duration; + +public class BatchTranslateDocument { + + public static void batchTranslateDocument() + throws IOException, ExecutionException, InterruptedException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + int timeout = 400; // timeout in seconds + batchTranslateDocument(projectId, sourceLanguage, targetLanguage, inputUri, outputUri, timeout); + } + + // Batch translate document + public static void batchTranslateDocument( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + int timeout) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + // refer to https://github.com/googleapis/java-translate/issues/613 + TranslationServiceSettings.Builder translationServiceSettingsBuilder = + TranslationServiceSettings.newBuilder(); + TimedRetryAlgorithm timedRetryAlgorithm = + OperationTimedPollAlgorithm.create( + RetrySettings.newBuilder().setTotalTimeout(Duration.ofSeconds(1000)).build()); + translationServiceSettingsBuilder + .batchTranslateDocumentOperationSettings() + .setPollingAlgorithm(timedRetryAlgorithm); + TranslationServiceSettings translationServiceSettings = + translationServiceSettingsBuilder.build(); + + // Initialize client that sends requests. This client can be reused for multiple requests. After + // completing all of your requests, call the "close" method on the client to clean + // up any remaining background resources. + try (TranslationServiceClient client = + TranslationServiceClient.create(translationServiceSettings)) { + // The ``global`` location is not supported for batch translation + LocationName parent = LocationName.of(projectId, "us-central1"); + + // Google Cloud Storage location for the source input. This can be a single file + // (for example, ``gs://translation-test/input.docx``) or a wildcard + // (for example, ``gs://translation-test/*``). + // Supported file types: https://cloud.google.com/translate/docs/supported-formats + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + + BatchDocumentInputConfig batchDocumentInputConfig = + BatchDocumentInputConfig.newBuilder().setGcsSource(gcsSource).build(); + + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + + BatchDocumentOutputConfig batchDocumentOutputConfig = + BatchDocumentOutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + BatchTranslateDocumentRequest request = + BatchTranslateDocumentRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(batchDocumentInputConfig) + .setOutputConfig(batchDocumentOutputConfig) + .build(); + + OperationFuture future = + client.batchTranslateDocumentAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between timeout + long randomNumber = ThreadLocalRandom.current().nextInt(timeout, timeout + 100); + BatchTranslateDocumentResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + System.out.println("Total Pages: " + response.getTotalPages()); + } + } +} +// [END translate_v3beta1_batch_translate_document] diff --git a/translate/snippets/src/main/java/com/example/translatev3beta1/TranslateDocument.java b/translate/snippets/src/main/java/com/example/translatev3beta1/TranslateDocument.java new file mode 100644 index 00000000000..7a342a3802e --- /dev/null +++ b/translate/snippets/src/main/java/com/example/translatev3beta1/TranslateDocument.java @@ -0,0 +1,76 @@ +/* + * Copyright 2021 Google LLC + * + * 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.example.translatev3beta1; + +// [START translate_v3beta1_translate_document] + +import com.google.cloud.translate.v3beta1.DocumentInputConfig; +import com.google.cloud.translate.v3beta1.LocationName; +import com.google.cloud.translate.v3beta1.TranslateDocumentRequest; +import com.google.cloud.translate.v3beta1.TranslateDocumentResponse; +import com.google.cloud.translate.v3beta1.TranslationServiceClient; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class TranslateDocument { + + public static void translateDocument() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String filePath = "your-text"; + translateDocument(projectId, filePath); + } + + // Translating Document + public static void translateDocument(String projectId, String filePath) throws IOException { + // Initialize client that sends requests. This client can be reused for multiple requests. After + // completing all of your requests, call the "close" method on the client to clean + // up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // The ``global`` location is not supported for batch translation + LocationName parent = LocationName.of(projectId, "us-central1"); + + // Supported file types: https://cloud.google.com/translate/docs/supported-formats + ByteString content = ByteString.readFrom(new FileInputStream(filePath)); + + DocumentInputConfig documentInputConfig = + DocumentInputConfig.newBuilder() + .setContent(content) + .setMimeType("application/pdf") + .build(); + + TranslateDocumentRequest request = + TranslateDocumentRequest.newBuilder() + .setParent(parent.toString()) + .setTargetLanguageCode("fr-FR") + .setDocumentInputConfig(documentInputConfig) + .build(); + + TranslateDocumentResponse response = client.translateDocument(request); + + // To view translated document, write `response.document_translation.byte_stream_outputs` + // to file. If not provided in the TranslationRequest, the translated file will only be + // returned through a byte-stream and its output mime type will be the same as the input + // file's mime type + System.out.println( + "Response: Detected Language Code - " + + response.getDocumentTranslation().getDetectedLanguageCode()); + } + } +} +// [END translate_v3beta1_translate_document] diff --git a/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextTests.java b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextTests.java new file mode 100644 index 00000000000..6d130f47467 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextTests.java @@ -0,0 +1,121 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = "gs://cloud-samples-data/translation/text.txt"; + private static final String PREFIX = "BATCH_TRANSLATION_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + private static void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clean up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateText() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateText.batchTranslateText(PROJECT_ID, "en", "es", INPUT_URI, outputUri); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 13"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java new file mode 100644 index 00000000000..f359edf9bd5 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java @@ -0,0 +1,128 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Glossary sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextWithGlossaryAndModelTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://cloud-samples-data/translation/text_with_custom_model_and_glossary.txt"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + private static final String MODEL_ID = "TRL3645318651705294848"; + private static final String PREFIX = "BATCH_TRANSLATION_MODEL_GLOS_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + private static final void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + private PrintStream originalPrintStream; + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clear up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateTextWithGlossaryAndModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateTextWithGlossaryAndModel.batchTranslateTextWithGlossaryAndModel( + PROJECT_ID, "en", "ja", INPUT_URI, outputUri, GLOSSARY_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 25"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java new file mode 100644 index 00000000000..7e2702effe2 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java @@ -0,0 +1,127 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Glossary and Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextWithGlossaryTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://cloud-samples-data/translation/text_with_glossary.txt"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + private static final String PREFIX = "BATCH_TRANSLATION_GLOSSARY_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static final void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clear up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + // Clean up + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateTextWithGlossary() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateTextWithGlossary.batchTranslateTextWithGlossary( + PROJECT_ID, "en", "ja", INPUT_URI, outputUri, GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 9"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java new file mode 100644 index 00000000000..efcd65daf0c --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java @@ -0,0 +1,123 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextWithModelTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://cloud-samples-data/translation/custom_model_text.txt"; + private static final String MODEL_ID = "TRL3645318651705294848"; + private static final String PREFIX = "BATCH_TRANSLATION_WITH_MODEL_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static final void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clear up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateTextWithModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateTextWithModel.batchTranslateTextWithModel( + PROJECT_ID, "en", "ja", INPUT_URI, outputUri, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 15"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/CreateGlossaryTests.java b/translate/snippets/src/test/java/com/example/translate/CreateGlossaryTests.java new file mode 100644 index 00000000000..3d88ba31548 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/CreateGlossaryTests.java @@ -0,0 +1,95 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class CreateGlossaryTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = + String.format("test_%s", UUID.randomUUID().toString().replace("-", "_").substring(0, 26)); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() throws InterruptedException, ExecutionException, IOException { + // Delete the created glossary + DeleteGlossary.deleteGlossary(PROJECT_ID, GLOSSARY_ID); + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testCreateGlossary() throws InterruptedException, ExecutionException, IOException { + List languageCodes = new ArrayList<>(); + languageCodes.add("en"); + languageCodes.add("ja"); + CreateGlossary.createGlossary(PROJECT_ID, GLOSSARY_ID, languageCodes, GLOSSARY_INPUT_URI); + + String got = bout.toString(); + assertThat(got).contains("Created"); + assertThat(got).contains(GLOSSARY_ID); + assertThat(got).contains(GLOSSARY_INPUT_URI); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/DeleteGlossaryTests.java b/translate/snippets/src/test/java/com/example/translate/DeleteGlossaryTests.java new file mode 100644 index 00000000000..0a5f4ce0181 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/DeleteGlossaryTests.java @@ -0,0 +1,93 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Create and Delete Glossary samples. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DeleteGlossaryTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = + String.format("test_%s", UUID.randomUUID().toString().replace("-", "_").substring(0, 26)); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() throws InterruptedException, ExecutionException, IOException { + // Create a glossary to be deleted + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + List languageCodes = new ArrayList<>(); + languageCodes.add("en"); + languageCodes.add("ja"); + CreateGlossary.createGlossary(PROJECT_ID, GLOSSARY_ID, languageCodes, GLOSSARY_INPUT_URI); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDeleteGlossary() throws InterruptedException, ExecutionException, IOException { + DeleteGlossary.deleteGlossary(PROJECT_ID, GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains("us-central1"); + assertThat(got).contains(GLOSSARY_ID); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/DetectLanguageTests.java b/translate/snippets/src/test/java/com/example/translate/DetectLanguageTests.java new file mode 100644 index 00000000000..0f756a4e4f1 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/DetectLanguageTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Detect Languages sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLanguageTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectLanguage() throws IOException { + DetectLanguage.detectLanguage(PROJECT_ID, "Hæ sæta"); + String got = bout.toString(); + assertThat(got).contains("is"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/GetGlossaryTests.java b/translate/snippets/src/test/java/com/example/translate/GetGlossaryTests.java new file mode 100644 index 00000000000..dc58e333127 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/GetGlossaryTests.java @@ -0,0 +1,83 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Get Glossary sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class GetGlossaryTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + // Create a glossary that can be used in the test + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetGlossary() throws IOException { + GetGlossary.getGlossary(PROJECT_ID, GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains(GLOSSARY_ID); + assertThat(got).contains(GLOSSARY_INPUT_URI); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/GetSupportedLanguagesForTargetTests.java b/translate/snippets/src/test/java/com/example/translate/GetSupportedLanguagesForTargetTests.java new file mode 100644 index 00000000000..238e6af53c3 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/GetSupportedLanguagesForTargetTests.java @@ -0,0 +1,76 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Get Supported Languages For Target sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class GetSupportedLanguagesForTargetTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetSupportedLanguages() throws IOException { + GetSupportedLanguagesForTarget.getSupportedLanguagesForTarget(PROJECT_ID, "is"); + String got = bout.toString(); + assertThat(got).contains("Language Code: sq"); + assertThat(got).contains("Display Name: albanska"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/GetSupportedLanguagesTests.java b/translate/snippets/src/test/java/com/example/translate/GetSupportedLanguagesTests.java new file mode 100644 index 00000000000..e2da272b992 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/GetSupportedLanguagesTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Get Supported Languages sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class GetSupportedLanguagesTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetSupportedLanguages() throws IOException { + GetSupportedLanguages.getSupportedLanguages(PROJECT_ID); + String got = bout.toString(); + assertThat(got).contains("zh-CN"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/ListGlossariesTests.java b/translate/snippets/src/test/java/com/example/translate/ListGlossariesTests.java new file mode 100644 index 00000000000..c50e97d8872 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/ListGlossariesTests.java @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for List Glossaries sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ListGlossariesTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testListGlossaries() throws IOException { + ListGlossaries.listGlossaries(PROJECT_ID); + String got = bout.toString(); + assertThat(got).contains("Glossary name:"); + assertThat(got).contains(GLOSSARY_INPUT_URI); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java b/translate/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java new file mode 100644 index 00000000000..1565cb4a3a8 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Google Inc. + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for quickstart sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class QuickstartSampleIT { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testQuickstart() throws Exception { + // Act + QuickstartSample.main(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Text: Hello, world!"); + assertThat(got).contains("Translation: "); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/TranslateTextTests.java b/translate/snippets/src/test/java/com/example/translate/TranslateTextTests.java new file mode 100644 index 00000000000..6d93272fcec --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/TranslateTextTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Text sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateText() throws IOException { + TranslateText.translateText(PROJECT_ID, "es", "Hello world"); + String got = bout.toString(); + assertThat(got).contains("Hola Mundo"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java b/translate/snippets/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java new file mode 100644 index 00000000000..b25d7652717 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java @@ -0,0 +1,84 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Glossary and Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextWithGlossaryAndModelTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String MODEL_ID = "TRL3645318651705294848"; + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateTextWithGlossaryAndModel() throws IOException { + TranslateTextWithGlossaryAndModel.translateTextWithGlossaryAndModel( + PROJECT_ID, "en", "ja", "That' il do it. deception", GLOSSARY_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("やるよ欺く"); // custom model + assertThat(got).contains("欺く"); // glossary + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java b/translate/snippets/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java new file mode 100644 index 00000000000..83a8054f6b3 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Text With Glossary sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextWithGlossaryTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateTextWithGlossary() throws IOException { + TranslateTextWithGlossary.translateTextWithGlossary( + PROJECT_ID, "en", "ja", "account", GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains("アカウント"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translate/TranslateTextWithModelTests.java b/translate/snippets/src/test/java/com/example/translate/TranslateTextWithModelTests.java new file mode 100644 index 00000000000..6c986c3b0a4 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translate/TranslateTextWithModelTests.java @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextWithModelTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String MODEL_ID = "TRL3645318651705294848"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateTextWithModel() throws IOException { + TranslateTextWithModel.translateTextWithModel( + PROJECT_ID, "en", "ja", "That' il do it. deception", MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("やるよ欺瞞"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translatev3beta1/BatchTranslateDocumentTests.java b/translate/snippets/src/test/java/com/example/translatev3beta1/BatchTranslateDocumentTests.java new file mode 100644 index 00000000000..8c68aac45db --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translatev3beta1/BatchTranslateDocumentTests.java @@ -0,0 +1,117 @@ +/* + * Copyright 2021 Google LLC + * + * 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.example.translatev3beta1; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Document sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateDocumentTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://java-docs-samples-testing/translation/invoice2.docx"; + private static final String PREFIX = "BATCH_DOC_TRANSLATION_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull(String.format(varName), System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clean up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testBatchTranslateDocument() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateDocument.batchTranslateDocument( + PROJECT_ID, "en-US", "fr-FR", INPUT_URI, outputUri, 1000); + + String got = bout.toString(); + assertThat(got).contains("Total Pages:"); + } +} diff --git a/translate/snippets/src/test/java/com/example/translatev3beta1/TranslateDocumentTests.java b/translate/snippets/src/test/java/com/example/translatev3beta1/TranslateDocumentTests.java new file mode 100644 index 00000000000..02780eee0d5 --- /dev/null +++ b/translate/snippets/src/test/java/com/example/translatev3beta1/TranslateDocumentTests.java @@ -0,0 +1,73 @@ +/* + * Copyright 2021 Google LLC + * + * 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.example.translatev3beta1; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Document sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateDocumentTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull(String.format(varName), System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateText() throws IOException { + TranslateDocument.translateDocument(PROJECT_ID, "resources/fake_invoice.pdf"); + String got = bout.toString(); + assertThat(got).contains("Response: Detected Language Code"); + } +} diff --git a/translate/src/main/java/com/example/translate/BatchTranslateText.java b/translate/src/main/java/com/example/translate/BatchTranslateText.java new file mode 100644 index 00000000000..6f0f20138dd --- /dev/null +++ b/translate/src/main/java/com/example/translate/BatchTranslateText.java @@ -0,0 +1,99 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateText { + + public static void batchTranslateText() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + batchTranslateText(projectId, sourceLanguage, targetLanguage, inputUri, outputUri); + } + + // Batch translate text + public static void batchTranslateText( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `us-central1` + LocationName parent = LocationName.of(projectId, "us-central1"); + + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .build(); + + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text] diff --git a/translate/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java b/translate/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java new file mode 100644 index 00000000000..6c5b713c9bc --- /dev/null +++ b/translate/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java @@ -0,0 +1,118 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text_with_glossary] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateTextWithGlossary { + + public static void batchTranslateTextWithGlossary() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + String glossaryId = "your-glossary-display-name"; + batchTranslateTextWithGlossary( + projectId, sourceLanguage, targetLanguage, inputUri, outputUri, glossaryId); + } + + // Batch Translate Text with a Glossary. + public static void batchTranslateTextWithGlossary( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + String glossaryId) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + // Configure where to store the output in a GCS bucket + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + // Configure the glossary used in the request + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + // Build the request that will be sent to the API + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .putGlossaries(targetLanguage, glossaryConfig) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + // Display the translation for each input text provided + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text_with_glossary] diff --git a/translate/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java b/translate/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java new file mode 100644 index 00000000000..0fe8bd26802 --- /dev/null +++ b/translate/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java @@ -0,0 +1,125 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text_with_glossary_and_model] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateTextWithGlossaryAndModel { + + public static void batchTranslateTextWithGlossaryAndModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + String glossaryId = "your-glossary-display-name"; + String modelId = "YOUR-MODEL-ID"; + batchTranslateTextWithGlossaryAndModel( + projectId, sourceLanguage, targetLanguage, inputUri, outputUri, glossaryId, modelId); + } + + // Batch translate text with Model and Glossary + public static void batchTranslateTextWithGlossaryAndModel( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + String glossaryId, + String modelId) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + // Configure where to store the output in a GCS bucket + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + // Configure the glossary used in the request + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + // Configure the model used in the request + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Build the request that will be sent to the API + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .putGlossaries(targetLanguage, glossaryConfig) + .putModels(targetLanguage, modelPath) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + // Display the translation for each input text provided + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text_with_glossary_and_model] diff --git a/translate/src/main/java/com/example/translate/BatchTranslateTextWithModel.java b/translate/src/main/java/com/example/translate/BatchTranslateTextWithModel.java new file mode 100644 index 00000000000..216a2060e30 --- /dev/null +++ b/translate/src/main/java/com/example/translate/BatchTranslateTextWithModel.java @@ -0,0 +1,115 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_batch_translate_text_with_model] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.BatchTranslateMetadata; +import com.google.cloud.translate.v3.BatchTranslateResponse; +import com.google.cloud.translate.v3.BatchTranslateTextRequest; +import com.google.cloud.translate.v3.GcsDestination; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.InputConfig; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.OutputConfig; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class BatchTranslateTextWithModel { + + public static void batchTranslateTextWithModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + String outputUri = "gs://your-gcs-bucket/path/to/results/"; + String modelId = "YOUR-MODEL-ID"; + batchTranslateTextWithModel( + projectId, sourceLanguage, targetLanguage, inputUri, outputUri, modelId); + } + + // Batch translate text using AutoML Translation model + public static void batchTranslateTextWithModel( + String projectId, + String sourceLanguage, + String targetLanguage, + String inputUri, + String outputUri, + String modelId) + throws IOException, ExecutionException, InterruptedException, TimeoutException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + InputConfig inputConfig = + InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build(); + + // Configure where to store the output in a GCS bucket + GcsDestination gcsDestination = + GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build(); + OutputConfig outputConfig = + OutputConfig.newBuilder().setGcsDestination(gcsDestination).build(); + + // Configure the model used in the request + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Build the request that will be sent to the API + BatchTranslateTextRequest request = + BatchTranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setSourceLanguageCode(sourceLanguage) + .addTargetLanguageCodes(targetLanguage) + .addInputConfigs(inputConfig) + .setOutputConfig(outputConfig) + .putModels(targetLanguage, modelPath) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.batchTranslateTextAsync(request); + + System.out.println("Waiting for operation to complete..."); + + // random number between 300 - 450 (maximum allowed seconds) + long randomNumber = ThreadLocalRandom.current().nextInt(450, 600); + BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS); + + // Display the translation for each input text provided + System.out.printf("Total Characters: %s\n", response.getTotalCharacters()); + System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters()); + } + } +} +// [END translate_v3_batch_translate_text_with_model] diff --git a/translate/src/main/java/com/example/translate/CreateGlossary.java b/translate/src/main/java/com/example/translate/CreateGlossary.java new file mode 100644 index 00000000000..ab9f7de4f0e --- /dev/null +++ b/translate/src/main/java/com/example/translate/CreateGlossary.java @@ -0,0 +1,98 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_create_glossary] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.CreateGlossaryMetadata; +import com.google.cloud.translate.v3.CreateGlossaryRequest; +import com.google.cloud.translate.v3.GcsSource; +import com.google.cloud.translate.v3.Glossary; +import com.google.cloud.translate.v3.GlossaryInputConfig; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; + +public class CreateGlossary { + + public static void createGlossary() throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String glossaryId = "your-glossary-display-name"; + List languageCodes = new ArrayList<>(); + languageCodes.add("your-language-code"); + String inputUri = "gs://your-gcs-bucket/path/to/input/file.txt"; + createGlossary(projectId, glossaryId, languageCodes, inputUri); + } + + // Create a equivalent term sets glossary + // https://cloud.google.com/translate/docs/advanced/glossary#format-glossary + public static void createGlossary( + String projectId, String glossaryId, List languageCodes, String inputUri) + throws IOException, ExecutionException, InterruptedException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + + // Supported Languages: https://cloud.google.com/translate/docs/languages + Glossary.LanguageCodesSet languageCodesSet = + Glossary.LanguageCodesSet.newBuilder().addAllLanguageCodes(languageCodes).build(); + + // Configure the source of the file from a GCS bucket + GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build(); + GlossaryInputConfig inputConfig = + GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build(); + + Glossary glossary = + Glossary.newBuilder() + .setName(glossaryName.toString()) + .setLanguageCodesSet(languageCodesSet) + .setInputConfig(inputConfig) + .build(); + + CreateGlossaryRequest request = + CreateGlossaryRequest.newBuilder() + .setParent(parent.toString()) + .setGlossary(glossary) + .build(); + + // Start an asynchronous request + OperationFuture future = + client.createGlossaryAsync(request); + + System.out.println("Waiting for operation to complete..."); + Glossary response = future.get(); + System.out.println("Created Glossary."); + System.out.printf("Glossary name: %s\n", response.getName()); + System.out.printf("Entry count: %s\n", response.getEntryCount()); + System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri()); + } + } +} +// [END translate_v3_create_glossary] diff --git a/translate/src/main/java/com/example/translate/DeleteGlossary.java b/translate/src/main/java/com/example/translate/DeleteGlossary.java new file mode 100644 index 00000000000..78266cdb5e1 --- /dev/null +++ b/translate/src/main/java/com/example/translate/DeleteGlossary.java @@ -0,0 +1,63 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_delete_glossary] +import com.google.api.gax.longrunning.OperationFuture; +import com.google.cloud.translate.v3.DeleteGlossaryMetadata; +import com.google.cloud.translate.v3.DeleteGlossaryRequest; +import com.google.cloud.translate.v3.DeleteGlossaryResponse; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +public class DeleteGlossary { + + public static void deleteGlossary() throws InterruptedException, ExecutionException, IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String glossaryId = "your-glossary-display-name"; + deleteGlossary(projectId, glossaryId); + } + + // Delete a specific glossary based on the glossary ID + public static void deleteGlossary(String projectId, String glossaryId) + throws InterruptedException, ExecutionException, IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId); + DeleteGlossaryRequest request = + DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build(); + + // Start an asynchronous request + OperationFuture future = + client.deleteGlossaryAsync(request); + + System.out.println("Waiting for operation to complete..."); + DeleteGlossaryResponse response = future.get(); + System.out.format("Deleted Glossary: %s\n", response.getName()); + } + } +} +// [END translate_v3_delete_glossary] diff --git a/translate/src/main/java/com/example/translate/DetectLanguage.java b/translate/src/main/java/com/example/translate/DetectLanguage.java new file mode 100644 index 00000000000..a1b4c5fb19f --- /dev/null +++ b/translate/src/main/java/com/example/translate/DetectLanguage.java @@ -0,0 +1,70 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_detect_language] +import com.google.cloud.translate.v3.DetectLanguageRequest; +import com.google.cloud.translate.v3.DetectLanguageResponse; +import com.google.cloud.translate.v3.DetectedLanguage; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class DetectLanguage { + + public static void detectLanguage() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String text = "your-text"; + + detectLanguage(projectId, text); + } + + // Detecting the language of a text string + public static void detectLanguage(String projectId, String text) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + DetectLanguageRequest request = + DetectLanguageRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setContent(text) + .build(); + + DetectLanguageResponse response = client.detectLanguage(request); + + // Display list of detected languages sorted by detection confidence. + // The most probable language is first. + for (DetectedLanguage language : response.getLanguagesList()) { + // The language detected + System.out.printf("Language code: %s\n", language.getLanguageCode()); + // Confidence of detection result for this language + System.out.printf("Confidence: %s\n", language.getConfidence()); + } + } + } +} +// [END translate_v3_detect_language] diff --git a/translate/src/main/java/com/example/translate/GetGlossary.java b/translate/src/main/java/com/example/translate/GetGlossary.java new file mode 100644 index 00000000000..c3e8283bd13 --- /dev/null +++ b/translate/src/main/java/com/example/translate/GetGlossary.java @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_get_glossary] +import com.google.cloud.translate.v3.GetGlossaryRequest; +import com.google.cloud.translate.v3.Glossary; +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class GetGlossary { + + public static void getGlossary() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + String glossaryId = "your-glossary-display-name"; + getGlossary(projectId, glossaryId); + } + + // Get a particular glossary based on the glossary ID + public static void getGlossary(String projectId, String glossaryId) throws IOException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId); + GetGlossaryRequest request = + GetGlossaryRequest.newBuilder().setName(glossaryName.toString()).build(); + + Glossary response = client.getGlossary(request); + + System.out.printf("Glossary name: %s\n", response.getName()); + System.out.printf("Entry count: %s\n", response.getEntryCount()); + System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri()); + } + } +} +// [END translate_v3_get_glossary] diff --git a/translate/src/main/java/com/example/translate/GetSupportedLanguages.java b/translate/src/main/java/com/example/translate/GetSupportedLanguages.java new file mode 100644 index 00000000000..08eb5d46b65 --- /dev/null +++ b/translate/src/main/java/com/example/translate/GetSupportedLanguages.java @@ -0,0 +1,58 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_get_supported_languages] +import com.google.cloud.translate.v3.GetSupportedLanguagesRequest; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.SupportedLanguage; +import com.google.cloud.translate.v3.SupportedLanguages; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class GetSupportedLanguages { + + public static void getSupportedLanguages() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + getSupportedLanguages(projectId); + } + + // Getting a list of supported language codes + public static void getSupportedLanguages(String projectId) throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + GetSupportedLanguagesRequest request = + GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build(); + + SupportedLanguages response = client.getSupportedLanguages(request); + + // List language codes of supported languages + for (SupportedLanguage language : response.getLanguagesList()) { + System.out.printf("Language Code: %s\n", language.getLanguageCode()); + } + } + } +} +// [END translate_v3_get_supported_languages] diff --git a/translate/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java b/translate/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java new file mode 100644 index 00000000000..d3de319ad5c --- /dev/null +++ b/translate/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java @@ -0,0 +1,65 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_get_supported_languages_for_target] +import com.google.cloud.translate.v3.GetSupportedLanguagesRequest; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.SupportedLanguage; +import com.google.cloud.translate.v3.SupportedLanguages; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class GetSupportedLanguagesForTarget { + + public static void getSupportedLanguagesForTarget() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String languageCode = "your-language-code"; + getSupportedLanguagesForTarget(projectId, languageCode); + } + + // Listing supported languages with target language name + public static void getSupportedLanguagesForTarget(String projectId, String languageCode) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "global"); + GetSupportedLanguagesRequest request = + GetSupportedLanguagesRequest.newBuilder() + .setParent(parent.toString()) + .setDisplayLanguageCode(languageCode) + .build(); + + SupportedLanguages response = client.getSupportedLanguages(request); + + // List language codes of supported languages + for (SupportedLanguage language : response.getLanguagesList()) { + System.out.printf("Language Code: %s\n", language.getLanguageCode()); + System.out.printf("Display Name: %s\n", language.getDisplayName()); + } + } + } +} +// [END translate_v3_get_supported_languages_for_target] diff --git a/translate/src/main/java/com/example/translate/ListGlossaries.java b/translate/src/main/java/com/example/translate/ListGlossaries.java new file mode 100644 index 00000000000..129d58ec7b7 --- /dev/null +++ b/translate/src/main/java/com/example/translate/ListGlossaries.java @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_list_glossary] +import com.google.cloud.translate.v3.Glossary; +import com.google.cloud.translate.v3.ListGlossariesRequest; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class ListGlossaries { + + public static void listGlossaries() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + listGlossaries(projectId); + } + + // List all the glossaries in a specified location + public static void listGlossaries(String projectId) throws IOException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + LocationName parent = LocationName.of(projectId, "us-central1"); + ListGlossariesRequest request = + ListGlossariesRequest.newBuilder().setParent(parent.toString()).build(); + + for (Glossary responseItem : client.listGlossaries(request).iterateAll()) { + System.out.printf("Glossary name: %s\n", responseItem.getName()); + System.out.printf("Entry count: %s\n", responseItem.getEntryCount()); + System.out.printf( + "Input URI: %s\n", responseItem.getInputConfig().getGcsSource().getInputUri()); + } + } + } +} +// [END translate_v3_list_glossary] diff --git a/translate/src/main/java/com/example/translate/TranslateTextWithGlossary.java b/translate/src/main/java/com/example/translate/TranslateTextWithGlossary.java new file mode 100644 index 00000000000..78c35aa66e7 --- /dev/null +++ b/translate/src/main/java/com/example/translate/TranslateTextWithGlossary.java @@ -0,0 +1,85 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_translate_text_with_glossary] +import com.google.cloud.translate.v3.GlossaryName; +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextGlossaryConfig; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class TranslateTextWithGlossary { + + public static void translateTextWithGlossary() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String text = "your-text"; + String glossaryId = "your-glossary-display-name"; + translateTextWithGlossary(projectId, sourceLanguage, targetLanguage, text, glossaryId); + } + + // Translates a given text using a glossary. + public static void translateTextWithGlossary( + String projectId, + String sourceLanguage, + String targetLanguage, + String text, + String glossaryId) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + + GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); + TranslateTextGlossaryConfig glossaryConfig = + TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build(); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setSourceLanguageCode(sourceLanguage) + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .setGlossaryConfig(glossaryConfig) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getGlossaryTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } +} +// [END translate_v3_translate_text_with_glossary] diff --git a/translate/src/main/java/com/example/translate/TranslateTextWithModel.java b/translate/src/main/java/com/example/translate/TranslateTextWithModel.java new file mode 100644 index 00000000000..9d81c7979d9 --- /dev/null +++ b/translate/src/main/java/com/example/translate/TranslateTextWithModel.java @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +// [START translate_v3_translate_text_with_model] +import com.google.cloud.translate.v3.LocationName; +import com.google.cloud.translate.v3.TranslateTextRequest; +import com.google.cloud.translate.v3.TranslateTextResponse; +import com.google.cloud.translate.v3.Translation; +import com.google.cloud.translate.v3.TranslationServiceClient; +import java.io.IOException; + +public class TranslateTextWithModel { + + public static void translateTextWithModel() throws IOException { + // TODO(developer): Replace these variables before running the sample. + String projectId = "YOUR-PROJECT-ID"; + // Supported Languages: https://cloud.google.com/translate/docs/languages + String sourceLanguage = "your-source-language"; + String targetLanguage = "your-target-language"; + String text = "your-text"; + String modelId = "YOUR-MODEL-ID"; + translateTextWithModel(projectId, sourceLanguage, targetLanguage, text, modelId); + } + + // Translating Text with Model + public static void translateTextWithModel( + String projectId, String sourceLanguage, String targetLanguage, String text, String modelId) + throws IOException { + + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests. After completing all of your requests, call + // the "close" method on the client to safely clean up any remaining background resources. + try (TranslationServiceClient client = TranslationServiceClient.create()) { + // Supported Locations: `global`, [glossary location], or [model location] + // Glossaries must be hosted in `us-central1` + // Custom Models must use the same location as your model. (us-central1) + String location = "us-central1"; + LocationName parent = LocationName.of(projectId, location); + String modelPath = + String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId); + + // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats + TranslateTextRequest request = + TranslateTextRequest.newBuilder() + .setParent(parent.toString()) + .setMimeType("text/plain") + .setSourceLanguageCode(sourceLanguage) + .setTargetLanguageCode(targetLanguage) + .addContents(text) + .setModel(modelPath) + .build(); + + TranslateTextResponse response = client.translateText(request); + + // Display the translation for each input text provided + for (Translation translation : response.getTranslationsList()) { + System.out.printf("Translated text: %s\n", translation.getTranslatedText()); + } + } + } +} +// [END translate_v3_translate_text_with_model] diff --git a/translate/src/test/java/com/example/translate/BatchTranslateTextTests.java b/translate/src/test/java/com/example/translate/BatchTranslateTextTests.java new file mode 100644 index 00000000000..6d130f47467 --- /dev/null +++ b/translate/src/test/java/com/example/translate/BatchTranslateTextTests.java @@ -0,0 +1,121 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = "gs://cloud-samples-data/translation/text.txt"; + private static final String PREFIX = "BATCH_TRANSLATION_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + private static void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clean up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateText() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateText.batchTranslateText(PROJECT_ID, "en", "es", INPUT_URI, outputUri); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 13"); + } +} diff --git a/translate/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java b/translate/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java new file mode 100644 index 00000000000..f359edf9bd5 --- /dev/null +++ b/translate/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java @@ -0,0 +1,128 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Glossary sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextWithGlossaryAndModelTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://cloud-samples-data/translation/text_with_custom_model_and_glossary.txt"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + private static final String MODEL_ID = "TRL3645318651705294848"; + private static final String PREFIX = "BATCH_TRANSLATION_MODEL_GLOS_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + + private static final void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + private PrintStream originalPrintStream; + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clear up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateTextWithGlossaryAndModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateTextWithGlossaryAndModel.batchTranslateTextWithGlossaryAndModel( + PROJECT_ID, "en", "ja", INPUT_URI, outputUri, GLOSSARY_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 25"); + } +} diff --git a/translate/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java b/translate/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java new file mode 100644 index 00000000000..7e2702effe2 --- /dev/null +++ b/translate/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java @@ -0,0 +1,127 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Glossary and Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextWithGlossaryTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://cloud-samples-data/translation/text_with_glossary.txt"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + private static final String PREFIX = "BATCH_TRANSLATION_GLOSSARY_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static final void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clear up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + // Clean up + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateTextWithGlossary() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateTextWithGlossary.batchTranslateTextWithGlossary( + PROJECT_ID, "en", "ja", INPUT_URI, outputUri, GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 9"); + } +} diff --git a/translate/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java b/translate/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java new file mode 100644 index 00000000000..efcd65daf0c --- /dev/null +++ b/translate/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java @@ -0,0 +1,123 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateTextWithModelTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://cloud-samples-data/translation/custom_model_text.txt"; + private static final String MODEL_ID = "TRL3645318651705294848"; + private static final String PREFIX = "BATCH_TRANSLATION_WITH_MODEL_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static final void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clear up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testBatchTranslateTextWithModel() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateTextWithModel.batchTranslateTextWithModel( + PROJECT_ID, "en", "ja", INPUT_URI, outputUri, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("Total Characters: 15"); + } +} diff --git a/translate/src/test/java/com/example/translate/CreateGlossaryTests.java b/translate/src/test/java/com/example/translate/CreateGlossaryTests.java new file mode 100644 index 00000000000..3d88ba31548 --- /dev/null +++ b/translate/src/test/java/com/example/translate/CreateGlossaryTests.java @@ -0,0 +1,95 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.cloud.testing.junit4.MultipleAttemptsRule; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class CreateGlossaryTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = + String.format("test_%s", UUID.randomUUID().toString().replace("-", "_").substring(0, 26)); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() throws InterruptedException, ExecutionException, IOException { + // Delete the created glossary + DeleteGlossary.deleteGlossary(PROJECT_ID, GLOSSARY_ID); + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(3); + + @Test + public void testCreateGlossary() throws InterruptedException, ExecutionException, IOException { + List languageCodes = new ArrayList<>(); + languageCodes.add("en"); + languageCodes.add("ja"); + CreateGlossary.createGlossary(PROJECT_ID, GLOSSARY_ID, languageCodes, GLOSSARY_INPUT_URI); + + String got = bout.toString(); + assertThat(got).contains("Created"); + assertThat(got).contains(GLOSSARY_ID); + assertThat(got).contains(GLOSSARY_INPUT_URI); + } +} diff --git a/translate/src/test/java/com/example/translate/DeleteGlossaryTests.java b/translate/src/test/java/com/example/translate/DeleteGlossaryTests.java new file mode 100644 index 00000000000..0a5f4ce0181 --- /dev/null +++ b/translate/src/test/java/com/example/translate/DeleteGlossaryTests.java @@ -0,0 +1,93 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Create and Delete Glossary samples. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DeleteGlossaryTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = + String.format("test_%s", UUID.randomUUID().toString().replace("-", "_").substring(0, 26)); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() throws InterruptedException, ExecutionException, IOException { + // Create a glossary to be deleted + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + List languageCodes = new ArrayList<>(); + languageCodes.add("en"); + languageCodes.add("ja"); + CreateGlossary.createGlossary(PROJECT_ID, GLOSSARY_ID, languageCodes, GLOSSARY_INPUT_URI); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDeleteGlossary() throws InterruptedException, ExecutionException, IOException { + DeleteGlossary.deleteGlossary(PROJECT_ID, GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains("us-central1"); + assertThat(got).contains(GLOSSARY_ID); + } +} diff --git a/translate/src/test/java/com/example/translate/DetectLanguageTests.java b/translate/src/test/java/com/example/translate/DetectLanguageTests.java new file mode 100644 index 00000000000..0f756a4e4f1 --- /dev/null +++ b/translate/src/test/java/com/example/translate/DetectLanguageTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Detect Languages sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectLanguageTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testDetectLanguage() throws IOException { + DetectLanguage.detectLanguage(PROJECT_ID, "Hæ sæta"); + String got = bout.toString(); + assertThat(got).contains("is"); + } +} diff --git a/translate/src/test/java/com/example/translate/GetGlossaryTests.java b/translate/src/test/java/com/example/translate/GetGlossaryTests.java new file mode 100644 index 00000000000..dc58e333127 --- /dev/null +++ b/translate/src/test/java/com/example/translate/GetGlossaryTests.java @@ -0,0 +1,83 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Get Glossary sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class GetGlossaryTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + // Create a glossary that can be used in the test + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetGlossary() throws IOException { + GetGlossary.getGlossary(PROJECT_ID, GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains(GLOSSARY_ID); + assertThat(got).contains(GLOSSARY_INPUT_URI); + } +} diff --git a/translate/src/test/java/com/example/translate/GetSupportedLanguagesForTargetTests.java b/translate/src/test/java/com/example/translate/GetSupportedLanguagesForTargetTests.java new file mode 100644 index 00000000000..238e6af53c3 --- /dev/null +++ b/translate/src/test/java/com/example/translate/GetSupportedLanguagesForTargetTests.java @@ -0,0 +1,76 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Get Supported Languages For Target sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class GetSupportedLanguagesForTargetTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetSupportedLanguages() throws IOException { + GetSupportedLanguagesForTarget.getSupportedLanguagesForTarget(PROJECT_ID, "is"); + String got = bout.toString(); + assertThat(got).contains("Language Code: sq"); + assertThat(got).contains("Display Name: albanska"); + } +} diff --git a/translate/src/test/java/com/example/translate/GetSupportedLanguagesTests.java b/translate/src/test/java/com/example/translate/GetSupportedLanguagesTests.java new file mode 100644 index 00000000000..e2da272b992 --- /dev/null +++ b/translate/src/test/java/com/example/translate/GetSupportedLanguagesTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Get Supported Languages sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class GetSupportedLanguagesTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testGetSupportedLanguages() throws IOException { + GetSupportedLanguages.getSupportedLanguages(PROJECT_ID); + String got = bout.toString(); + assertThat(got).contains("zh-CN"); + } +} diff --git a/translate/src/test/java/com/example/translate/ListGlossariesTests.java b/translate/src/test/java/com/example/translate/ListGlossariesTests.java new file mode 100644 index 00000000000..c50e97d8872 --- /dev/null +++ b/translate/src/test/java/com/example/translate/ListGlossariesTests.java @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for List Glossaries sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class ListGlossariesTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testListGlossaries() throws IOException { + ListGlossaries.listGlossaries(PROJECT_ID); + String got = bout.toString(); + assertThat(got).contains("Glossary name:"); + assertThat(got).contains(GLOSSARY_INPUT_URI); + } +} diff --git a/translate/src/test/java/com/example/translate/QuickstartSampleIT.java b/translate/src/test/java/com/example/translate/QuickstartSampleIT.java new file mode 100644 index 00000000000..1565cb4a3a8 --- /dev/null +++ b/translate/src/test/java/com/example/translate/QuickstartSampleIT.java @@ -0,0 +1,62 @@ +/* + * Copyright 2016 Google Inc. + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for quickstart sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class QuickstartSampleIT { + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testQuickstart() throws Exception { + // Act + QuickstartSample.main(); + + // Assert + String got = bout.toString(); + assertThat(got).contains("Text: Hello, world!"); + assertThat(got).contains("Translation: "); + } +} diff --git a/translate/src/test/java/com/example/translate/TranslateTextTests.java b/translate/src/test/java/com/example/translate/TranslateTextTests.java new file mode 100644 index 00000000000..6d93272fcec --- /dev/null +++ b/translate/src/test/java/com/example/translate/TranslateTextTests.java @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Text sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateText() throws IOException { + TranslateText.translateText(PROJECT_ID, "es", "Hello world"); + String got = bout.toString(); + assertThat(got).contains("Hola Mundo"); + } +} diff --git a/translate/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java b/translate/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java new file mode 100644 index 00000000000..b25d7652717 --- /dev/null +++ b/translate/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java @@ -0,0 +1,84 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Glossary and Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextWithGlossaryAndModelTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String MODEL_ID = "TRL3645318651705294848"; + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateTextWithGlossaryAndModel() throws IOException { + TranslateTextWithGlossaryAndModel.translateTextWithGlossaryAndModel( + PROJECT_ID, "en", "ja", "That' il do it. deception", GLOSSARY_ID, MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("やるよ欺く"); // custom model + assertThat(got).contains("欺く"); // glossary + } +} diff --git a/translate/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java b/translate/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java new file mode 100644 index 00000000000..83a8054f6b3 --- /dev/null +++ b/translate/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Text With Glossary sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextWithGlossaryTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String GLOSSARY_INPUT_URI = + "gs://cloud-samples-data/translation/glossary_ja.csv"; + private static final String GLOSSARY_ID = "DO_NOT_DELETE_TEST_GLOSSARY"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + PrintStream temp = new PrintStream(new ByteArrayOutputStream()); + System.setOut(temp); + + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateTextWithGlossary() throws IOException { + TranslateTextWithGlossary.translateTextWithGlossary( + PROJECT_ID, "en", "ja", "account", GLOSSARY_ID); + String got = bout.toString(); + assertThat(got).contains("アカウント"); + } +} diff --git a/translate/src/test/java/com/example/translate/TranslateTextWithModelTests.java b/translate/src/test/java/com/example/translate/TranslateTextWithModelTests.java new file mode 100644 index 00000000000..6c986c3b0a4 --- /dev/null +++ b/translate/src/test/java/com/example/translate/TranslateTextWithModelTests.java @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Google LLC + * + * 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.example.translate; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Text With Model sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateTextWithModelTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String MODEL_ID = "TRL3645318651705294848"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull( + "Environment variable '%s' is required to perform these tests.".format(varName), + System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateTextWithModel() throws IOException { + TranslateTextWithModel.translateTextWithModel( + PROJECT_ID, "en", "ja", "That' il do it. deception", MODEL_ID); + String got = bout.toString(); + assertThat(got).contains("やるよ欺瞞"); + } +} diff --git a/translate/src/test/java/com/example/translatev3beta1/BatchTranslateDocumentTests.java b/translate/src/test/java/com/example/translatev3beta1/BatchTranslateDocumentTests.java new file mode 100644 index 00000000000..8c68aac45db --- /dev/null +++ b/translate/src/test/java/com/example/translatev3beta1/BatchTranslateDocumentTests.java @@ -0,0 +1,117 @@ +/* + * Copyright 2021 Google LLC + * + * 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.example.translatev3beta1; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import com.google.api.gax.paging.Page; +import com.google.cloud.storage.Blob; +import com.google.cloud.storage.Storage; +import com.google.cloud.storage.StorageOptions; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Batch Translate Document sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class BatchTranslateDocumentTests { + + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static final String INPUT_URI = + "gs://java-docs-samples-testing/translation/invoice2.docx"; + private static final String PREFIX = "BATCH_DOC_TRANSLATION_OUTPUT_"; + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void cleanUpBucket() { + Storage storage = StorageOptions.getDefaultInstance().getService(); + Page blobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(PREFIX)); + + deleteDirectory(storage, blobs); + } + + private static void deleteDirectory(Storage storage, Page blobs) { + for (Blob blob : blobs.iterateAll()) { + System.out.println(blob.getBlobId()); + if (!blob.delete()) { + Page subBlobs = + storage.list( + PROJECT_ID, + Storage.BlobListOption.currentDirectory(), + Storage.BlobListOption.prefix(blob.getName())); + + deleteDirectory(storage, subBlobs); + } + } + } + + private static void requireEnvVar(String varName) { + assertNotNull(String.format(varName), System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + // clean up bucket before the use to prevent concurrency issue. + cleanUpBucket(); + } + + @After + public void tearDown() { + cleanUpBucket(); + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testBatchTranslateDocument() + throws InterruptedException, ExecutionException, IOException, TimeoutException { + String outputUri = String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID()); + BatchTranslateDocument.batchTranslateDocument( + PROJECT_ID, "en-US", "fr-FR", INPUT_URI, outputUri, 1000); + + String got = bout.toString(); + assertThat(got).contains("Total Pages:"); + } +} diff --git a/translate/src/test/java/com/example/translatev3beta1/TranslateDocumentTests.java b/translate/src/test/java/com/example/translatev3beta1/TranslateDocumentTests.java new file mode 100644 index 00000000000..02780eee0d5 --- /dev/null +++ b/translate/src/test/java/com/example/translatev3beta1/TranslateDocumentTests.java @@ -0,0 +1,73 @@ +/* + * Copyright 2021 Google LLC + * + * 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.example.translatev3beta1; + +import static com.google.common.truth.Truth.assertThat; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for Translate Document sample. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class TranslateDocumentTests { + private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + + private ByteArrayOutputStream bout; + private PrintStream out; + private PrintStream originalPrintStream; + + private static void requireEnvVar(String varName) { + assertNotNull(String.format(varName), System.getenv(varName)); + } + + @BeforeClass + public static void checkRequirements() { + requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS"); + requireEnvVar("GOOGLE_CLOUD_PROJECT"); + } + + @Before + public void setUp() { + bout = new ByteArrayOutputStream(); + out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @After + public void tearDown() { + // restores print statements in the original method + System.out.flush(); + System.setOut(originalPrintStream); + } + + @Test + public void testTranslateText() throws IOException { + TranslateDocument.translateDocument(PROJECT_ID, "resources/fake_invoice.pdf"); + String got = bout.toString(); + assertThat(got).contains("Response: Detected Language Code"); + } +}