From 0c39897a694bc2c5c253276a035147f7e19c7596 Mon Sep 17 00:00:00 2001 From: dfirova <93149631+dfirova@users.noreply.github.com> Date: Tue, 13 Sep 2022 18:03:59 +0300 Subject: [PATCH] docs(samples): Refactoring product package (#480) --- README.md | 1 + .../product/ImportProductsBigQueryTable.java | 43 +++++----- .../main/java/product/ImportProductsGcs.java | 65 +++++++++------ .../product/ImportProductsInlineSource.java | 79 ++++++++++--------- .../setup/ProductsCreateBigqueryTable.java | 7 +- .../setup/ProductsCreateGcsBucket.java | 16 ++-- .../setup/RemoveProductsResources.java | 76 ++++++++++++++++++ .../ImportProductsBigQueryTableTest.java | 50 +++++++----- .../java/product/ImportProductsGcsTest.java | 22 +++--- .../ImportProductsInlineSourceTest.java | 11 ++- 10 files changed, 238 insertions(+), 132 deletions(-) create mode 100644 samples/interactive-tutorials/src/main/java/product/setup/RemoveProductsResources.java diff --git a/README.md b/README.md index 6263dc61..37bf83d1 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-retail/tree/m | Update Product | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/UpdateProduct.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/product/UpdateProduct.java) | | Products Create Bigquery Table | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateBigqueryTable.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateBigqueryTable.java) | | Products Create Gcs Bucket | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateGcsBucket.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateGcsBucket.java) | +| Remove Products Resources | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/setup/RemoveProductsResources.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/product/setup/RemoveProductsResources.java) | | Search Simple Query | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/search/SearchSimpleQuery.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/search/SearchSimpleQuery.java) | | Search With Boost Spec | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/search/SearchWithBoostSpec.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/search/SearchWithBoostSpec.java) | | Search With Facet Spec | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/search/SearchWithFacetSpec.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-retail&page=editor&open_in_editor=samples/interactive-tutorials/src/main/java/search/SearchWithFacetSpec.java) | diff --git a/samples/interactive-tutorials/src/main/java/product/ImportProductsBigQueryTable.java b/samples/interactive-tutorials/src/main/java/product/ImportProductsBigQueryTable.java index 2f6b9e3a..552751cf 100644 --- a/samples/interactive-tutorials/src/main/java/product/ImportProductsBigQueryTable.java +++ b/samples/interactive-tutorials/src/main/java/product/ImportProductsBigQueryTable.java @@ -31,11 +31,11 @@ import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; import java.io.IOException; +import java.util.concurrent.TimeUnit; public class ImportProductsBigQueryTable { public static void main(String[] args) throws IOException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String branchName = String.format( @@ -43,24 +43,18 @@ public static void main(String[] args) throws IOException, InterruptedException String datasetId = "products"; String tableId = "products"; // TO CHECK ERROR HANDLING USE THE TABLE WITH INVALID PRODUCTS: - // TABLE_ID = "products_some_invalid" - String dataSchema = "product"; - // TRY THE FULL RECONCILIATION MODE HERE: - ReconciliationMode reconciliationMode = ReconciliationMode.INCREMENTAL; + // tableId = "products_some_invalid" - ImportProductsRequest importBigQueryRequest = - getImportProductsBigQueryRequest( - reconciliationMode, projectId, datasetId, tableId, dataSchema, branchName); - waitForOperationCompletion(importBigQueryRequest); + importProductsFromBigQuery(projectId, branchName, datasetId, tableId); } - public static ImportProductsRequest getImportProductsBigQueryRequest( - ReconciliationMode reconciliationMode, - String projectId, - String datasetId, - String tableId, - String dataSchema, - String branchName) { + public static void importProductsFromBigQuery( + String projectId, String branchName, String datasetId, String tableId) + throws IOException, InterruptedException { + // TRY THE FULL RECONCILIATION MODE HERE: + ReconciliationMode reconciliationMode = ReconciliationMode.INCREMENTAL; + String dataSchema = "product"; + BigQuerySource bigQuerySource = BigQuerySource.newBuilder() .setProjectId(projectId) @@ -80,30 +74,29 @@ public static ImportProductsRequest getImportProductsBigQueryRequest( .build(); System.out.printf("Import products from big query table request: %s%n", importRequest); - return importRequest; - } - - public static void waitForOperationCompletion(ImportProductsRequest importRequest) - throws IOException, 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 (ProductServiceClient serviceClient = ProductServiceClient.create()) { String operationName = serviceClient.importProductsCallable().call(importRequest).getName(); - System.out.printf("OperationName = %s\n", operationName); + System.out.printf("OperationName = %s%n", operationName); OperationsClient operationsClient = serviceClient.getOperationsClient(); Operation operation = operationsClient.getOperation(operationName); while (!operation.getDone()) { // Keep polling the operation periodically until the import task is done. - Thread.sleep(30_000); + TimeUnit.SECONDS.sleep(30); operation = operationsClient.getOperation(operationName); } if (operation.hasMetadata()) { ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class); System.out.printf( - "Number of successfully imported products: %s\n", metadata.getSuccessCount()); + "Number of successfully imported products: %s%n", metadata.getSuccessCount()); System.out.printf( - "Number of failures during the importing: %s\n", metadata.getFailureCount()); + "Number of failures during the importing: %s%n", metadata.getFailureCount()); } if (operation.hasResponse()) { diff --git a/samples/interactive-tutorials/src/main/java/product/ImportProductsGcs.java b/samples/interactive-tutorials/src/main/java/product/ImportProductsGcs.java index 15291a0c..1ae9502a 100644 --- a/samples/interactive-tutorials/src/main/java/product/ImportProductsGcs.java +++ b/samples/interactive-tutorials/src/main/java/product/ImportProductsGcs.java @@ -20,6 +20,8 @@ package product; +import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.api.gax.rpc.PermissionDeniedException; import com.google.cloud.ServiceOptions; import com.google.cloud.retail.v2.GcsSource; import com.google.cloud.retail.v2.ImportErrorsConfig; @@ -32,37 +34,42 @@ import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; import java.io.IOException; +import java.time.Instant; import java.util.Collections; +import java.util.concurrent.TimeUnit; public class ImportProductsGcs { public static void main(String[] args) throws IOException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String branchName = String.format( "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); + + String bucketName = System.getenv("BUCKET_NAME"); + String gcsBucket = String.format("gs://%s", bucketName); + String gcsErrorBucket = String.format("%s/errors", gcsBucket); + // To check error handling, use an invalid catalog in request // branchName = // String.format("projects/%s/locations/global/catalogs/invalid_catalog/branches/default_branch", projectId); - String gcsBucket = String.format("gs://%s", System.getenv("BUCKET_NAME")); - String gcsErrorBucket = String.format("%s/errors", gcsBucket); String gcsProductsObject = "products.json"; // To check error handling, use an invalid product JSON. - // gcsProductsObject = "products_some_invalid.json"; + // gcsProductsObject = "products_some_invalid.json" - ImportProductsRequest importGcsRequest = - getImportProductsGcsRequest(gcsProductsObject, gcsBucket, gcsErrorBucket, branchName); - waitForOperationCompletion(importGcsRequest); + importProductsFromGcs(branchName, gcsBucket, gcsProductsObject); } - public static ImportProductsRequest getImportProductsGcsRequest( - String gcsObjectName, String gcsBucket, String gcsErrorBucket, String branchName) { + public static void importProductsFromGcs( + String branchName, String gcsBucket, String gcsProductsObject) + throws IOException, InterruptedException { + String gcsErrorBucket = String.format("%s/errors", gcsBucket); + GcsSource gcsSource = GcsSource.newBuilder() .addAllInputUris( - Collections.singleton(String.format("%s/%s", gcsBucket, gcsObjectName))) + Collections.singleton(String.format("%s/%s", gcsBucket, gcsProductsObject))) .build(); ProductInputConfig inputConfig = @@ -81,39 +88,53 @@ public static ImportProductsRequest getImportProductsGcsRequest( .setErrorsConfig(errorsConfig) .build(); - System.out.println("Import products from google cloud source request: " + importRequest); - - return importRequest; - } + System.out.printf("Import products from google cloud source request: %s%n", importRequest); - public static void waitForOperationCompletion(ImportProductsRequest importRequest) - throws IOException, 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 (ProductServiceClient serviceClient = ProductServiceClient.create()) { String operationName = serviceClient.importProductsCallable().call(importRequest).getName(); - System.out.printf("OperationName = %s\n", operationName); + + System.out.println("The operation was started."); + System.out.printf("OperationName = %s%n", operationName); OperationsClient operationsClient = serviceClient.getOperationsClient(); Operation operation = operationsClient.getOperation(operationName); - while (!operation.getDone()) { - // Keep polling the operation periodically until the import task is done. - Thread.sleep(30_000); + Instant deadline = Instant.now().plusSeconds(60); + + while (!operation.getDone() || Instant.now().isBefore(deadline)) { + System.out.println("Please wait till operation is done."); + TimeUnit.SECONDS.sleep(30); operation = operationsClient.getOperation(operationName); } if (operation.hasMetadata()) { ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class); System.out.printf( - "Number of successfully imported products: %s\n", metadata.getSuccessCount()); + "Number of successfully imported products: %s%n", metadata.getSuccessCount()); System.out.printf( - "Number of failures during the importing: %s\n", metadata.getFailureCount()); + "Number of failures during the importing: %s%n", metadata.getFailureCount()); + } else { + System.out.println("Metadata is empty."); } if (operation.hasResponse()) { ImportProductsResponse response = operation.getResponse().unpack(ImportProductsResponse.class); System.out.printf("Operation result: %s%n", response); + } else { + System.out.println("Operation result is empty."); } + } catch (InvalidArgumentException e) { + System.out.printf( + "%s%n'%s' file does not exist in the bucket. Please " + + "make sure you have followed the setting up instructions.", + e.getMessage(), gcsProductsObject); + } catch (PermissionDeniedException e) { + System.out.println(e.getMessage()); } } } diff --git a/samples/interactive-tutorials/src/main/java/product/ImportProductsInlineSource.java b/samples/interactive-tutorials/src/main/java/product/ImportProductsInlineSource.java index 278721f4..c16fc821 100644 --- a/samples/interactive-tutorials/src/main/java/product/ImportProductsInlineSource.java +++ b/samples/interactive-tutorials/src/main/java/product/ImportProductsInlineSource.java @@ -20,6 +20,7 @@ package product; +import com.google.api.gax.rpc.InvalidArgumentException; import com.google.cloud.ServiceOptions; import com.google.cloud.retail.v2.ColorInfo; import com.google.cloud.retail.v2.FulfillmentInfo; @@ -40,24 +41,23 @@ import java.util.Collections; import java.util.List; import java.util.UUID; +import java.util.concurrent.TimeUnit; public class ImportProductsInlineSource { public static void main(String[] args) throws IOException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String branchName = String.format( "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); - ImportProductsRequest importRequest = getImportProductsInlineRequest(getProducts(), branchName); - waitForOperationCompletion(importRequest); + importProductsInlineSource(branchName); } - public static ImportProductsRequest getImportProductsInlineRequest( - List productsToImport, String branchName) { + public static void importProductsInlineSource(String branchName) + throws IOException, InterruptedException { ProductInlineSource inlineSource = - ProductInlineSource.newBuilder().addAllProducts(productsToImport).build(); + ProductInlineSource.newBuilder().addAllProducts(getProducts()).build(); ProductInputConfig inputConfig = ProductInputConfig.newBuilder().setProductInlineSource(inlineSource).build(); @@ -70,7 +70,41 @@ public static ImportProductsRequest getImportProductsInlineRequest( System.out.printf("Import products from inline source request: %s%n", importRequest); - return importRequest; + // 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 (ProductServiceClient serviceClient = ProductServiceClient.create()) { + String operationName = serviceClient.importProductsCallable().call(importRequest).getName(); + System.out.printf("OperationName = %s%n", operationName); + + OperationsClient operationsClient = serviceClient.getOperationsClient(); + Operation operation = operationsClient.getOperation(operationName); + + long assuredBreak = System.currentTimeMillis() + 60000; // 60 seconds delay + + while (!operation.getDone() || System.currentTimeMillis() < assuredBreak) { + // Keep polling the operation periodically until the import task is done. + TimeUnit.SECONDS.sleep(30); + operation = operationsClient.getOperation(operationName); + } + + if (operation.hasMetadata()) { + ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class); + System.out.printf( + "Number of successfully imported products: %s%n", metadata.getSuccessCount()); + System.out.printf( + "Number of failures during the importing: %s%n", metadata.getFailureCount()); + } + + if (operation.hasResponse()) { + ImportProductsResponse response = + operation.getResponse().unpack(ImportProductsResponse.class); + System.out.printf("Operation result: %s%n", response); + } + } catch (InvalidArgumentException e) { + System.out.println(e.getMessage()); + } } public static List getProducts() { @@ -173,35 +207,4 @@ public static List getProducts() { return products; } - - public static void waitForOperationCompletion(ImportProductsRequest importRequest) - throws IOException, InterruptedException { - try (ProductServiceClient serviceClient = ProductServiceClient.create()) { - String operationName = serviceClient.importProductsCallable().call(importRequest).getName(); - System.out.printf("OperationName = %s\n", operationName); - - OperationsClient operationsClient = serviceClient.getOperationsClient(); - Operation operation = operationsClient.getOperation(operationName); - - while (!operation.getDone()) { - // Keep polling the operation periodically until the import task is done. - Thread.sleep(30_000); - operation = operationsClient.getOperation(operationName); - } - - if (operation.hasMetadata()) { - ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class); - System.out.printf( - "Number of successfully imported products: %s\n", metadata.getSuccessCount()); - System.out.printf( - "Number of failures during the importing: %s\n", metadata.getFailureCount()); - } - - if (operation.hasResponse()) { - ImportProductsResponse response = - operation.getResponse().unpack(ImportProductsResponse.class); - System.out.printf("Operation result: %s%n", response); - } - } - } } diff --git a/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateBigqueryTable.java b/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateBigqueryTable.java index 361144a8..f5244b78 100644 --- a/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateBigqueryTable.java +++ b/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateBigqueryTable.java @@ -30,16 +30,15 @@ public class ProductsCreateBigqueryTable { - public static void main(String... args) throws IOException { + public static void main(String[] args) throws IOException { String dataset = "products"; String validProductsTable = "products"; String invalidProductsTable = "products_some_invalid"; String productSchemaFilePath = "src/main/resources/product_schema.json"; String validProductsSourceFile = - String.format("gs://%s/products.json", ProductsCreateGcsBucket.getBucketName()); + String.format("gs://%s/products.json", System.getenv("BUCKET_NAME")); String invalidProductsSourceFile = - String.format( - "gs://%s/products_some_invalid.json", ProductsCreateGcsBucket.getBucketName()); + String.format("gs://%s/products_some_invalid.json", System.getenv("BUCKET_NAME")); BufferedReader bufferedReader = new BufferedReader(new FileReader(productSchemaFilePath)); String jsonToString = bufferedReader.lines().collect(Collectors.joining()); diff --git a/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateGcsBucket.java b/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateGcsBucket.java index 1e5caad4..80ed6285 100644 --- a/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateGcsBucket.java +++ b/samples/interactive-tutorials/src/main/java/product/setup/ProductsCreateGcsBucket.java @@ -38,16 +38,20 @@ public class ProductsCreateGcsBucket { String.format("%s_products_%s", PROJECT_ID, CURRENT_DATE.getSeconds()); public static void main(String... args) throws IOException { - createBucket(BUCKET_NAME); - System.out.printf("Products gcs bucket %s was created.", BUCKET_NAME); + createGcsBucketAndUploadData(BUCKET_NAME); + } + + public static void createGcsBucketAndUploadData(String bucketName) throws IOException { + createBucket(bucketName); + System.out.printf("Products gcs bucket %s was created.%n", bucketName); - uploadObject(BUCKET_NAME, "products.json", "src/main/resources/products.json"); - System.out.printf("File 'products.json' was uploaded into bucket '%s'.", BUCKET_NAME); + uploadObject(bucketName, "products.json", "src/main/resources/products.json"); + System.out.printf("File 'products.json' was uploaded into bucket '%s'.%n", bucketName); uploadObject( - BUCKET_NAME, "products_some_invalid.json", "src/main/resources/products_some_invalid.json"); + bucketName, "products_some_invalid.json", "src/main/resources/products_some_invalid.json"); System.out.printf( - "File 'products_some_invalid.json' was uploaded into bucket '%s'.", BUCKET_NAME); + "File 'products_some_invalid.json' was uploaded into bucket '%s'.%n", bucketName); } public static String getBucketName() { diff --git a/samples/interactive-tutorials/src/main/java/product/setup/RemoveProductsResources.java b/samples/interactive-tutorials/src/main/java/product/setup/RemoveProductsResources.java new file mode 100644 index 00000000..de7aea24 --- /dev/null +++ b/samples/interactive-tutorials/src/main/java/product/setup/RemoveProductsResources.java @@ -0,0 +1,76 @@ +/* + * Copyright 2022 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 product.setup; + +import static setup.SetupCleanup.deleteBucket; +import static setup.SetupCleanup.deleteDataset; + +import com.google.api.gax.rpc.PermissionDeniedException; +import com.google.cloud.ServiceOptions; +import com.google.cloud.retail.v2.DeleteProductRequest; +import com.google.cloud.retail.v2.ListProductsRequest; +import com.google.cloud.retail.v2.Product; +import com.google.cloud.retail.v2.ProductServiceClient; +import com.google.cloud.retail.v2.ProductServiceClient.ListProductsPagedResponse; +import java.io.IOException; + +public class RemoveProductsResources { + + public static void main(String[] args) throws IOException { + String projectId = ServiceOptions.getDefaultProjectId(); + String bucketName = System.getenv("BUCKET_NAME"); + String branchName = + String.format( + "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); + + deleteBucket(bucketName); + deleteAllProducts(branchName); + deleteDataset(projectId, "products"); + } + + public static void deleteAllProducts(String branchName) throws IOException { + System.out.println("Deleting products in process, please wait..."); + + // 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 (ProductServiceClient productServiceClient = ProductServiceClient.create()) { + ListProductsRequest listRequest = + ListProductsRequest.newBuilder().setParent(branchName).build(); + ListProductsPagedResponse products = productServiceClient.listProducts(listRequest); + + int deleteCount = 0; + + for (Product product : products.iterateAll()) { + DeleteProductRequest deleteRequest = + DeleteProductRequest.newBuilder().setName(product.getName()).build(); + + try { + productServiceClient.deleteProduct(deleteRequest); + deleteCount++; + } catch (PermissionDeniedException e) { + System.out.println( + "Ignore PermissionDenied in case the product does not exist " + + "at time of deletion."); + } + } + + System.out.printf("%s products were deleted from %s%n", deleteCount, branchName); + } + } +} diff --git a/samples/interactive-tutorials/src/test/java/product/ImportProductsBigQueryTableTest.java b/samples/interactive-tutorials/src/test/java/product/ImportProductsBigQueryTableTest.java index 58191f37..fce668a3 100644 --- a/samples/interactive-tutorials/src/test/java/product/ImportProductsBigQueryTableTest.java +++ b/samples/interactive-tutorials/src/test/java/product/ImportProductsBigQueryTableTest.java @@ -17,12 +17,9 @@ package product; import static com.google.common.truth.Truth.assertThat; -import static product.ImportProductsBigQueryTable.getImportProductsBigQueryRequest; -import static product.ImportProductsBigQueryTable.waitForOperationCompletion; +import static product.ImportProductsBigQueryTable.importProductsFromBigQuery; import com.google.cloud.ServiceOptions; -import com.google.cloud.retail.v2.ImportProductsRequest; -import com.google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -30,8 +27,10 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import product.setup.ProductsCreateBigqueryTable; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class ImportProductsBigQueryTableTest { private ByteArrayOutputStream bout; @@ -39,33 +38,46 @@ public class ImportProductsBigQueryTableTest { @Before public void setUp() throws IOException, InterruptedException, ExecutionException { + bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + + @Test + public void testValidImportProductsBigQueryTable() throws IOException, InterruptedException { String projectId = ServiceOptions.getDefaultProjectId(); String branchName = String.format( "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); String datasetId = "products"; String tableId = "products"; - String dataSchema = "product"; - ReconciliationMode reconciliationMode = ReconciliationMode.INCREMENTAL; - bout = new ByteArrayOutputStream(); - PrintStream out = new PrintStream(bout); - originalPrintStream = System.out; - System.setOut(out); - ProductsCreateBigqueryTable.main(); - ImportProductsRequest importBigQueryRequest = - getImportProductsBigQueryRequest( - reconciliationMode, projectId, datasetId, tableId, dataSchema, branchName); - waitForOperationCompletion(importBigQueryRequest); + importProductsFromBigQuery(projectId, branchName, datasetId, tableId); + + String outputResult = bout.toString(); + + assertThat(outputResult).contains("Import products from big query table request"); + assertThat(outputResult).contains("Number of successfully imported products:"); + assertThat(outputResult).contains("Number of failures during the importing: 0"); } @Test - public void testImportProductsBigQueryTable() { + public void testInvalidImportProductsBigQueryTable() throws IOException, InterruptedException { + String projectId = ServiceOptions.getDefaultProjectId(); + String branchName = + String.format( + "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); + String datasetId = "products"; + String tableId = "products_some_invalid"; + + importProductsFromBigQuery(projectId, branchName, datasetId, tableId); + String outputResult = bout.toString(); assertThat(outputResult).contains("Import products from big query table request"); - assertThat(outputResult).contains("Number of successfully imported products"); - assertThat(outputResult).contains("Number of failures during the importing"); + assertThat(outputResult).contains("Number of successfully imported products:"); + assertThat(outputResult).contains("Number of failures during the importing:"); } @After diff --git a/samples/interactive-tutorials/src/test/java/product/ImportProductsGcsTest.java b/samples/interactive-tutorials/src/test/java/product/ImportProductsGcsTest.java index 7ae805aa..22594f6b 100644 --- a/samples/interactive-tutorials/src/test/java/product/ImportProductsGcsTest.java +++ b/samples/interactive-tutorials/src/test/java/product/ImportProductsGcsTest.java @@ -17,11 +17,9 @@ package product; import static com.google.common.truth.Truth.assertThat; -import static product.ImportProductsGcs.getImportProductsGcsRequest; -import static product.ImportProductsGcs.waitForOperationCompletion; +import static product.ImportProductsGcs.importProductsFromGcs; import com.google.cloud.ServiceOptions; -import com.google.cloud.retail.v2.ImportProductsRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -29,8 +27,11 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; import product.setup.ProductsCreateGcsBucket; +@RunWith(JUnit4.class) public class ImportProductsGcsTest { private ByteArrayOutputStream bout; @@ -39,31 +40,28 @@ public class ImportProductsGcsTest { @Before public void setUp() throws IOException, InterruptedException, ExecutionException { ProductsCreateGcsBucket.main(); - String projectId = ServiceOptions.getDefaultProjectId(); String branchName = String.format( "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); - String gcsBucket = String.format("gs://%s", ProductsCreateGcsBucket.getBucketName()); - String gcsErrorBucket = String.format("%s/errors", gcsBucket); + String bucketName = ProductsCreateGcsBucket.getBucketName(); + String gcsBucket = String.format("gs://%s", bucketName); String gscProductsObject = "products.json"; bout = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bout); originalPrintStream = System.out; System.setOut(out); - ImportProductsRequest importGcsRequest = - getImportProductsGcsRequest(gscProductsObject, gcsBucket, gcsErrorBucket, branchName); - waitForOperationCompletion(importGcsRequest); + importProductsFromGcs(branchName, gcsBucket, gscProductsObject); } @Test - public void testImportProductsGcs() { + public void testValidImportProductsGcs() { String outputResult = bout.toString(); assertThat(outputResult).contains("Import products from google cloud source request"); - assertThat(outputResult).contains("Number of successfully imported products"); - assertThat(outputResult).contains("Number of failures during the importing"); + assertThat(outputResult).contains("Number of successfully imported products:"); + assertThat(outputResult).contains("Number of failures during the importing: 0"); } @After diff --git a/samples/interactive-tutorials/src/test/java/product/ImportProductsInlineSourceTest.java b/samples/interactive-tutorials/src/test/java/product/ImportProductsInlineSourceTest.java index eb4678a9..b5a424dc 100644 --- a/samples/interactive-tutorials/src/test/java/product/ImportProductsInlineSourceTest.java +++ b/samples/interactive-tutorials/src/test/java/product/ImportProductsInlineSourceTest.java @@ -17,12 +17,9 @@ package product; import static com.google.common.truth.Truth.assertThat; -import static product.ImportProductsInlineSource.getImportProductsInlineRequest; -import static product.ImportProductsInlineSource.getProducts; -import static product.ImportProductsInlineSource.waitForOperationCompletion; +import static product.ImportProductsInlineSource.importProductsInlineSource; import com.google.cloud.ServiceOptions; -import com.google.cloud.retail.v2.ImportProductsRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -30,7 +27,10 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +@RunWith(JUnit4.class) public class ImportProductsInlineSourceTest { private ByteArrayOutputStream bout; @@ -47,8 +47,7 @@ public void setUp() throws IOException, InterruptedException, ExecutionException originalPrintStream = System.out; System.setOut(out); - ImportProductsRequest importRequest = getImportProductsInlineRequest(getProducts(), branchName); - waitForOperationCompletion(importRequest); + importProductsInlineSource(branchName); } @Test