diff --git a/README.md b/README.md index f5b045cc..595cb393 100644 --- a/README.md +++ b/README.md @@ -27,13 +27,13 @@ If you are using Maven, add this to your pom.xml file: If you are using Gradle without BOM, add this to your dependencies ```Groovy -implementation 'com.google.cloud:google-cloud-retail:2.0.19' +implementation 'com.google.cloud:google-cloud-retail:2.4.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-retail" % "2.0.19" +libraryDependencies += "com.google.cloud" % "google-cloud-retail" % "2.4.0" ``` ## Authentication @@ -85,8 +85,8 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-retail/tree/m | Write User Event | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/events/WriteUserEvent.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/events/WriteUserEvent.java) | | Events Create Big Query Table | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateBigQueryTable.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/events/setup/EventsCreateBigQueryTable.java) | | Events Create Gcs Bucket | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateGcsBucket.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/events/setup/EventsCreateGcsBucket.java) | -| Create Test Resources | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/init/CreateTestResources.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/init/CreateTestResources.java) | -| Remove Test Resources | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/init/RemoveTestResources.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/init/RemoveTestResources.java) | +| Remove Events Resources | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/events/setup/RemoveEventsResources.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/events/setup/RemoveEventsResources.java) | +| Update User Events Json | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/events/setup/UpdateUserEventsJson.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/events/setup/UpdateUserEventsJson.java) | | Add Fulfillment Places | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/AddFulfillmentPlaces.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/AddFulfillmentPlaces.java) | | Create Product | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/CreateProduct.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/CreateProduct.java) | | Crud Product | [source code](https://github.com/googleapis/java-retail/blob/main/samples/interactive-tutorials/src/main/java/product/CrudProduct.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/CrudProduct.java) | diff --git a/samples/interactive-tutorials/src/main/java/events/ImportUserEventsBigQuery.java b/samples/interactive-tutorials/src/main/java/events/ImportUserEventsBigQuery.java index 40d24e9f..16c91225 100644 --- a/samples/interactive-tutorials/src/main/java/events/ImportUserEventsBigQuery.java +++ b/samples/interactive-tutorials/src/main/java/events/ImportUserEventsBigQuery.java @@ -22,6 +22,7 @@ package events; +import com.google.api.gax.rpc.NotFoundException; import com.google.cloud.ServiceOptions; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.retail.v2.BigQuerySource; @@ -33,19 +34,20 @@ import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; import java.io.IOException; +import java.util.concurrent.TimeUnit; public class ImportUserEventsBigQuery { public static void main(String[] args) throws IOException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); - // TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE: defaultCatalog = - // "invalid_catalog_name" + // TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE: + // defaultCatalog = "invalid_catalog_name" String datasetId = "user_events"; String tableId = "events"; - // TO CHECK ERROR HANDLING USE THE TABLE OF INVALID USER EVENTS: tableId = "events_some_invalid" + // TO CHECK ERROR HANDLING USE THE TABLE OF INVALID USER EVENTS: + // tableId = "events_some_invalid" importUserEventsFromBigQuery(projectId, defaultCatalog, datasetId, tableId); } @@ -53,6 +55,7 @@ public static void main(String[] args) throws IOException, InterruptedException public static void importUserEventsFromBigQuery( String projectId, String defaultCatalog, String datasetId, String tableId) throws IOException, InterruptedException { + try { String dataSchema = "user_event"; @@ -75,30 +78,32 @@ public static void importUserEventsFromBigQuery( System.out.printf("Import user events from BigQuery source request: %s%n", 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. + // 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 (UserEventServiceClient serviceClient = UserEventServiceClient.create()) { String operationName = serviceClient.importUserEventsCallable().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()) { + 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. - int awaitDuration = 30000; - Thread.sleep(awaitDuration); + 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 events: %s\n", metadata.getSuccessCount()); + "Number of successfully imported events: %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()) { @@ -109,6 +114,8 @@ public static void importUserEventsFromBigQuery( } } catch (BigQueryException e) { System.out.printf("Exception message: %s", e.getMessage()); + } catch (NotFoundException e) { + System.out.printf("Catalog name is not found.%n%s%n", e.getMessage()); } } } diff --git a/samples/interactive-tutorials/src/main/java/events/ImportUserEventsGcs.java b/samples/interactive-tutorials/src/main/java/events/ImportUserEventsGcs.java index 5e64eb1d..3d514d72 100644 --- a/samples/interactive-tutorials/src/main/java/events/ImportUserEventsGcs.java +++ b/samples/interactive-tutorials/src/main/java/events/ImportUserEventsGcs.java @@ -23,8 +23,8 @@ package events; import com.google.api.gax.rpc.InvalidArgumentException; +import com.google.api.gax.rpc.PermissionDeniedException; import com.google.cloud.ServiceOptions; -import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.retail.v2.GcsSource; import com.google.cloud.retail.v2.ImportErrorsConfig; import com.google.cloud.retail.v2.ImportMetadata; @@ -34,91 +34,95 @@ import com.google.cloud.retail.v2.UserEventServiceClient; import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; -import events.setup.EventsCreateGcsBucket; import java.io.IOException; +import java.util.concurrent.TimeUnit; public class ImportUserEventsGcs { public static void main(String[] args) throws IOException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); - // TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE: defaultCatalog = - // "invalid_catalog_name" - String gcsEventsObject = "user_events.json"; - // TO CHECK ERROR HANDLING USE THE JSON WITH INVALID USER EVENT: gcsEventsObject = - // "user_events_some_invalid.json" + String bucketName = System.getenv("EVENTS_BUCKET_NAME"); + String gcsUserEventsObject = "user_events.json"; + // TO CHECK ERROR HANDLING USE THE JSON WITH INVALID USER EVENT: + // gcsEventsObject = "user_events_some_invalid.json" - importUserEventsFromGcs(gcsEventsObject, defaultCatalog); + importUserEventsFromGcs(defaultCatalog, bucketName, gcsUserEventsObject); } - public static void importUserEventsFromGcs(String gcsEventsObject, String defaultCatalog) + public static void importUserEventsFromGcs( + String defaultCatalog, String bucketName, String gcsUserEventsObject) throws IOException, InterruptedException { - try { - String gcsBucket = String.format("gs://%s", EventsCreateGcsBucket.getBucketName()); - String gcsErrorsBucket = String.format("%s/error", gcsBucket); - - GcsSource gcsSource = - GcsSource.newBuilder() - .addInputUris(String.format("%s/%s", gcsBucket, gcsEventsObject)) - .build(); - - UserEventInputConfig inputConfig = - UserEventInputConfig.newBuilder().setGcsSource(gcsSource).build(); - - ImportErrorsConfig errorsConfig = - ImportErrorsConfig.newBuilder().setGcsPrefix(gcsErrorsBucket).build(); - - ImportUserEventsRequest importRequest = - ImportUserEventsRequest.newBuilder() - .setParent(defaultCatalog) - .setInputConfig(inputConfig) - .setErrorsConfig(errorsConfig) - .build(); - - System.out.printf("Import user events from google cloud source request: %s%n", 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 (UserEventServiceClient serviceClient = UserEventServiceClient.create()) { - String operationName = - serviceClient.importUserEventsCallable().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. - int awaitDuration = 30000; - Thread.sleep(awaitDuration); - operation = operationsClient.getOperation(operationName); - } - - if (operation.hasMetadata()) { - ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class); - System.out.printf( - "Number of successfully imported events: %s\n", metadata.getSuccessCount()); - System.out.printf( - "Number of failures during the importing: %s\n", metadata.getFailureCount()); - } - - if (operation.hasResponse()) { - ImportUserEventsResponse response = - operation.getResponse().unpack(ImportUserEventsResponse.class); - System.out.printf("Operation result: %s%n", response); - } - } catch (InvalidArgumentException e) { + String gcsBucket = String.format("gs://%s", bucketName); + String gcsErrorsBucket = String.format("%s/error", gcsBucket); + + GcsSource gcsSource = + GcsSource.newBuilder() + .addInputUris(String.format("%s/%s", gcsBucket, gcsUserEventsObject)) + .build(); + + UserEventInputConfig inputConfig = + UserEventInputConfig.newBuilder().setGcsSource(gcsSource).build(); + + System.out.println("GRS source: " + gcsSource.getInputUrisList()); + + ImportErrorsConfig errorsConfig = + ImportErrorsConfig.newBuilder().setGcsPrefix(gcsErrorsBucket).build(); + + ImportUserEventsRequest importRequest = + ImportUserEventsRequest.newBuilder() + .setParent(defaultCatalog) + .setInputConfig(inputConfig) + .setErrorsConfig(errorsConfig) + .build(); + System.out.printf("Import user events from google cloud source request: %s%n", 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 (UserEventServiceClient serviceClient = UserEventServiceClient.create()) { + String operationName = serviceClient.importUserEventsCallable().call(importRequest).getName(); + + System.out.println("The operation was started."); + 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) { + 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( - "Given GCS input path was not found. %n%s%n " - + "Please run CreateTestResources class to create resources.", - e.getMessage()); + "Number of successfully imported events: %s%n", metadata.getSuccessCount()); + System.out.printf( + "Number of failures during the importing: %s%n", metadata.getFailureCount()); + } else { + System.out.println("Metadata is empty."); + } + + if (operation.hasResponse()) { + ImportUserEventsResponse response = + operation.getResponse().unpack(ImportUserEventsResponse.class); + System.out.printf("Operation result: %s%n", response); + } else { + System.out.println("Operation result is empty."); } - } catch (BigQueryException e) { - System.out.printf("Exception message: %s", e.getMessage()); + } 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(), gcsUserEventsObject); + } catch (PermissionDeniedException e) { + System.out.println(e.getMessage()); } } } diff --git a/samples/interactive-tutorials/src/main/java/events/ImportUserEventsInline.java b/samples/interactive-tutorials/src/main/java/events/ImportUserEventsInline.java index 2a5124ab..8ef7118c 100644 --- a/samples/interactive-tutorials/src/main/java/events/ImportUserEventsInline.java +++ b/samples/interactive-tutorials/src/main/java/events/ImportUserEventsInline.java @@ -45,7 +45,6 @@ public class ImportUserEventsInline { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); @@ -90,9 +89,10 @@ public static void importUserEventsFromInlineSource(String defaultCatalog) .build(); System.out.printf("Import user events from inline source request: %s%n", 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. + // 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 (UserEventServiceClient userEventServiceClient = UserEventServiceClient.create()) { OperationFuture importOperation = userEventServiceClient.importUserEventsAsync(importRequest); diff --git a/samples/interactive-tutorials/src/main/java/events/PurgeUserEvent.java b/samples/interactive-tutorials/src/main/java/events/PurgeUserEvent.java index e55c4a66..fb34fe20 100644 --- a/samples/interactive-tutorials/src/main/java/events/PurgeUserEvent.java +++ b/samples/interactive-tutorials/src/main/java/events/PurgeUserEvent.java @@ -38,7 +38,6 @@ public class PurgeUserEvent { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); @@ -52,9 +51,10 @@ public static void callPurgeUserEvents(String defaultCatalog, String visitorId) throws IOException, ExecutionException, InterruptedException { writeUserEvent(visitorId); - // 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. + // 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 (UserEventServiceClient userEventServiceClient = UserEventServiceClient.create()) { PurgeUserEventsRequest purgeUserEventsRequest = PurgeUserEventsRequest.newBuilder() diff --git a/samples/interactive-tutorials/src/main/java/events/RejoinUserEvent.java b/samples/interactive-tutorials/src/main/java/events/RejoinUserEvent.java index 90284f6e..776c443a 100644 --- a/samples/interactive-tutorials/src/main/java/events/RejoinUserEvent.java +++ b/samples/interactive-tutorials/src/main/java/events/RejoinUserEvent.java @@ -40,7 +40,6 @@ public class RejoinUserEvent { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); @@ -54,9 +53,10 @@ public static void callRejoinUserEvents(String defaultCatalog, String visitorId) throws IOException, ExecutionException, InterruptedException { writeUserEvent(visitorId); - // 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. + // 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 (UserEventServiceClient userEventServiceClient = UserEventServiceClient.create()) { RejoinUserEventsRequest rejoinUserEventsRequest = RejoinUserEventsRequest.newBuilder() diff --git a/samples/interactive-tutorials/src/main/java/events/WriteUserEvent.java b/samples/interactive-tutorials/src/main/java/events/WriteUserEvent.java index 0f78fcf5..18379938 100644 --- a/samples/interactive-tutorials/src/main/java/events/WriteUserEvent.java +++ b/samples/interactive-tutorials/src/main/java/events/WriteUserEvent.java @@ -38,7 +38,6 @@ public class WriteUserEvent { public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); @@ -50,9 +49,10 @@ public static void main(String[] args) public static void writeUserEvent(String defaultCatalog, String visitorId) 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. + // 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 (UserEventServiceClient userEventServiceClient = UserEventServiceClient.create()) { Timestamp timestamp = Timestamp.newBuilder().setSeconds(Instant.now().getEpochSecond()).build(); diff --git a/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateBigQueryTable.java b/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateBigQueryTable.java index 5b0cce2f..3bedc9f1 100644 --- a/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateBigQueryTable.java +++ b/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateBigQueryTable.java @@ -30,16 +30,15 @@ public class EventsCreateBigQueryTable { - public static void main(String... args) throws IOException { + public static void main(String[] args) throws IOException { String dataset = "user_events"; String validEventsTable = "events"; String invalidEventsTable = "events_some_invalid"; String eventsSchemaFilePath = "src/main/resources/events_schema.json"; String validEventsSourceFile = - String.format("gs://%s/user_events.json", EventsCreateGcsBucket.getBucketName()); + String.format("gs://%s/user_events.json", System.getenv("EVENTS_BUCKET_NAME")); String invalidEventsSourceFile = - String.format( - "gs://%s/user_events_some_invalid.json", EventsCreateGcsBucket.getBucketName()); + String.format("gs://%s/user_events_some_invalid.json", System.getenv("EVENTS_BUCKET_NAME")); BufferedReader bufferedReader = new BufferedReader(new FileReader(eventsSchemaFilePath)); String jsonToString = bufferedReader.lines().collect(Collectors.joining()); diff --git a/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateGcsBucket.java b/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateGcsBucket.java index 33a2351e..0134b1eb 100644 --- a/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateGcsBucket.java +++ b/samples/interactive-tutorials/src/main/java/events/setup/EventsCreateGcsBucket.java @@ -25,34 +25,30 @@ import java.time.Instant; public class EventsCreateGcsBucket { + public static void main(String[] args) throws IOException { + String projectId = ServiceOptions.getDefaultProjectId(); + Timestamp currentDate = + Timestamp.newBuilder() + .setSeconds(Instant.now().getEpochSecond()) + .setNanos(Instant.now().getNano()) + .build(); + String eventsBucketName = String.format("%s_events_%s", projectId, currentDate.getSeconds()); + + createGcsBucketAndUploadData(eventsBucketName); + } - private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId(); - - private static final Timestamp CURRENT_DATE = - Timestamp.newBuilder() - .setSeconds(Instant.now().getEpochSecond()) - .setNanos(Instant.now().getNano()) - .build(); - - private static final String BUCKET_NAME = - String.format("%s_events_%s", PROJECT_ID, CURRENT_DATE.getSeconds()); - - public static void main(String... args) throws IOException { - createBucket(BUCKET_NAME); - System.out.printf("Events gcs bucket %s was created.", BUCKET_NAME); + public static void createGcsBucketAndUploadData(String bucketName) throws IOException { + createBucket(bucketName); + System.out.printf("Events gcs bucket %s was created.%n", bucketName); - uploadObject(BUCKET_NAME, "user_events.json", "src/main/resources/user_events.json"); - System.out.printf("File 'user_events.json' was uploaded into bucket '%s'.", BUCKET_NAME); + uploadObject(bucketName, "user_events.json", "src/main/resources/user_events.json"); + System.out.printf("File 'user_events.json' was uploaded into bucket '%s'.%n", bucketName); uploadObject( - BUCKET_NAME, + bucketName, "user_events_some_invalid.json", "src/main/resources/user_events_some_invalid.json"); System.out.printf( - "File 'user_events_some_invalid.json' was uploaded into bucket '%s'.", BUCKET_NAME); - } - - public static String getBucketName() { - return BUCKET_NAME; + "File 'user_events_some_invalid.json' was uploaded into bucket '%s'.%n", bucketName); } } diff --git a/samples/interactive-tutorials/src/main/java/init/RemoveTestResources.java b/samples/interactive-tutorials/src/main/java/events/setup/RemoveEventsResources.java similarity index 89% rename from samples/interactive-tutorials/src/main/java/init/RemoveTestResources.java rename to samples/interactive-tutorials/src/main/java/events/setup/RemoveEventsResources.java index c48ceff2..fb2c4f7e 100644 --- a/samples/interactive-tutorials/src/main/java/init/RemoveTestResources.java +++ b/samples/interactive-tutorials/src/main/java/events/setup/RemoveEventsResources.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package init; +package events.setup; import static setup.SetupCleanup.deleteBucket; import static setup.SetupCleanup.deleteDataset; @@ -28,19 +28,17 @@ import com.google.cloud.retail.v2.ProductServiceClient.ListProductsPagedResponse; import java.io.IOException; -public class RemoveTestResources { +public class RemoveEventsResources { - public static void main(String... args) throws IOException { - // TODO(developer): Replace these variables before running the sample. + public static void main(String[] args) throws IOException { String projectId = ServiceOptions.getDefaultProjectId(); - String bucketName = System.getenv("BUCKET_NAME"); + String bucketName = System.getenv("EVENTS_BUCKET_NAME"); String branchName = String.format( "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); deleteBucket(bucketName); deleteAllProducts(branchName); - deleteDataset(projectId, "products"); deleteDataset(projectId, "user_events"); } diff --git a/samples/interactive-tutorials/src/main/java/events/setup/UpdateUserEventsJson.java b/samples/interactive-tutorials/src/main/java/events/setup/UpdateUserEventsJson.java new file mode 100644 index 00000000..0651fa02 --- /dev/null +++ b/samples/interactive-tutorials/src/main/java/events/setup/UpdateUserEventsJson.java @@ -0,0 +1,54 @@ +/* + * 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 events.setup; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +public class UpdateUserEventsJson { + + public static void main(String[] args) throws IOException { + String filePath = "src/main/resources/user_events.json"; + String invalidFilePath = "src/main/resources/user_events_some_invalid.json"; + + updateEventsTimestamp(filePath); + updateEventsTimestamp(invalidFilePath); + } + + public static void updateEventsTimestamp(String jsonFile) throws IOException { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + Timestamp yesterdayDate = Timestamp.from(Instant.now().minus(1, ChronoUnit.DAYS)); + + String json = new String(Files.readAllBytes(Paths.get(jsonFile))); + json = + json.replaceAll( + "(\"eventTime\"\\s*:\\s*\"(\\d{4}-\\d{2}-\\d{2}(T.*Z)?))", + "\"eventTime\":\"" + dateFormat.format(yesterdayDate) + ""); + + BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile)); + writer.write(json); + System.out.printf("User events file '%s' updated.%n", jsonFile); + writer.close(); + } +} diff --git a/samples/interactive-tutorials/src/main/java/init/CreateTestResources.java b/samples/interactive-tutorials/src/main/java/init/CreateTestResources.java deleted file mode 100644 index 5a0f6cc6..00000000 --- a/samples/interactive-tutorials/src/main/java/init/CreateTestResources.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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 init; - -import com.google.cloud.ServiceOptions; -import com.google.cloud.retail.v2.GcsSource; -import com.google.cloud.retail.v2.ImportErrorsConfig; -import com.google.cloud.retail.v2.ImportMetadata; -import com.google.cloud.retail.v2.ImportProductsRequest; -import com.google.cloud.retail.v2.ImportProductsRequest.ReconciliationMode; -import com.google.cloud.retail.v2.ImportProductsResponse; -import com.google.cloud.retail.v2.ProductInputConfig; -import com.google.cloud.retail.v2.ProductServiceClient; -import com.google.longrunning.Operation; -import com.google.longrunning.OperationsClient; -import events.setup.EventsCreateBigQueryTable; -import events.setup.EventsCreateGcsBucket; -import java.io.IOException; -import java.util.Collections; -import product.setup.ProductsCreateBigqueryTable; -import product.setup.ProductsCreateGcsBucket; - -public class CreateTestResources { - - public static void main(String... args) throws IOException, InterruptedException { - // TODO(developer): Replace these variables before running the sample. - String projectId = ServiceOptions.getDefaultProjectId(); - String bucketName = System.getenv("BUCKET_NAME"); - String gcsBucket = String.format("gs://%s", System.getenv("BUCKET_NAME")); - String gcsErrorBucket = String.format("%s/errors", gcsBucket); - String branchName = - String.format( - "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); - - ProductsCreateGcsBucket.main(); - EventsCreateGcsBucket.main(); - importProductsFromGcs(bucketName, gcsErrorBucket, branchName); - ProductsCreateBigqueryTable.main(); - EventsCreateBigQueryTable.main(); - } - - public static void importProductsFromGcs( - String bucketName, String gcsErrorBucket, String branchName) - throws IOException, InterruptedException { - GcsSource gcsSource = - GcsSource.newBuilder() - .addAllInputUris( - Collections.singleton(String.format("gs://%s/%s", bucketName, "products.json"))) - .build(); - ProductInputConfig inputConfig = - ProductInputConfig.newBuilder().setGcsSource(gcsSource).build(); - System.out.println("GRS source: " + gcsSource.getInputUrisList()); - - ImportErrorsConfig errorsConfig = - ImportErrorsConfig.newBuilder().setGcsPrefix(gcsErrorBucket).build(); - ImportProductsRequest importRequest = - ImportProductsRequest.newBuilder() - .setParent(branchName) - .setReconciliationMode(ReconciliationMode.INCREMENTAL) - .setInputConfig(inputConfig) - .setErrorsConfig(errorsConfig) - .build(); - System.out.println("Import products from google cloud source request: " + importRequest); - - 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()) { - System.out.println("Please wait till operation is completed."); - // Keep polling the operation periodically until the import task is done. - Thread.sleep(30_000); - operation = operationsClient.getOperation(operationName); - } - - System.out.println("Import products operation is completed."); - - 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", response); - } - } - } -} diff --git a/samples/interactive-tutorials/src/main/java/init/TEST_RESOURCES_SETUP_CLEANUP.md b/samples/interactive-tutorials/src/main/java/init/TEST_RESOURCES_SETUP_CLEANUP.md deleted file mode 100644 index 0b9df6d1..00000000 --- a/samples/interactive-tutorials/src/main/java/init/TEST_RESOURCES_SETUP_CLEANUP.md +++ /dev/null @@ -1,49 +0,0 @@ -# How to set up/ tear down the test resources - -## Required environment variables - -To successfully import the catalog data for tests, the following environment variables should be -set: - -- PROJECT_ID -- PROJECT_NUMBER -- BUCKET_NAME - -The Secret Manager name is set in .kokoro/presubmit/common.cfg file, SECRET_MANAGER_KEYS variable. - -## Import catalog data - -There is a JSON file with valid products prepared in the `product` directory: -`resources/products.json`. - -Run the `CreateTestResources` to perform the following actions: - -- create the GCS bucket ; -- upload the product data from `resources/products.json` file to the bucket; -- import products to the default branch of the Retail catalog; -- upload the product data from `resources/user_events.json` file to the bucket; -- create a BigQuery dataset and table `products`; -- insert products from resources/products.json to the created products table; -- create a BigQuery dataset and table `events`; -- insert user events from resources/user_events.json to the created events table; - -``` -mvn compile exec:java -Dexec.mainClass="init.CreateTestResources" -``` - -In the result 316 products should be created in the test project catalog. - -## Remove catalog data - -Run the `RemoveTestResources` to perform the following actions: - -- remove all objects from the GCS bucket ; -- remove the bucket; -- delete all products from the Retail catalog; -- remove all objects from the GCS bucket ; -- remove dataset `products` along with tables; -- remove dataset `user_events` along with tables; - -``` -mvn compile exec:java -Dexec.mainClass="init.RemoveTestResources" -``` \ No newline at end of file diff --git a/samples/interactive-tutorials/src/test/java/events/ImportUserEventsBigQueryTest.java b/samples/interactive-tutorials/src/test/java/events/ImportUserEventsBigQueryTest.java index 2f465467..82afd5ae 100644 --- a/samples/interactive-tutorials/src/test/java/events/ImportUserEventsBigQueryTest.java +++ b/samples/interactive-tutorials/src/test/java/events/ImportUserEventsBigQueryTest.java @@ -19,7 +19,6 @@ import static com.google.common.truth.Truth.assertThat; import com.google.cloud.ServiceOptions; -import events.setup.EventsCreateBigQueryTable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; @@ -27,7 +26,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 ImportUserEventsBigQueryTest { private ByteArrayOutputStream bout; @@ -35,28 +37,46 @@ public class ImportUserEventsBigQueryTest { @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 testValidImportUserEventsBigQuery() throws IOException, InterruptedException { String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); String datasetId = "user_events"; String tableId = "events"; - bout = new ByteArrayOutputStream(); - PrintStream out = new PrintStream(bout); - originalPrintStream = System.out; - System.setOut(out); - EventsCreateBigQueryTable.main(); ImportUserEventsBigQuery.importUserEventsFromBigQuery( projectId, defaultCatalog, datasetId, tableId); + + String outputResult = bout.toString(); + + assertThat(outputResult).contains("Import user events from BigQuery source request"); + assertThat(outputResult).contains("table_id: \"events\""); + assertThat(outputResult).contains("Number of successfully imported events:"); + assertThat(outputResult).contains("Number of failures during the importing: 0"); } @Test - public void testImportUserEventsBigQuery() { + public void testInvalidImportUserEventsBigQuery() throws IOException, InterruptedException { + String projectId = ServiceOptions.getDefaultProjectId(); + String defaultCatalog = + String.format("projects/%s/locations/global/catalogs/invalid_catalog_name", projectId); + String datasetId = "user_events"; + String tableId = "events_some_invalid"; + + ImportUserEventsBigQuery.importUserEventsFromBigQuery( + projectId, defaultCatalog, datasetId, tableId); + String outputResult = bout.toString(); - assertThat(outputResult).contains("Import user events from BigQuery source request"); - assertThat(outputResult).contains("Number of successfully imported events"); - assertThat(outputResult).contains("Number of failures during the importing"); + assertThat(outputResult).contains("table_id: \"events_some_invalid\""); + assertThat(outputResult).contains("Catalog name is not found."); } @After diff --git a/samples/interactive-tutorials/src/test/java/events/ImportUserEventsGcsTest.java b/samples/interactive-tutorials/src/test/java/events/ImportUserEventsGcsTest.java index 78db5ff9..fd55f5db 100644 --- a/samples/interactive-tutorials/src/test/java/events/ImportUserEventsGcsTest.java +++ b/samples/interactive-tutorials/src/test/java/events/ImportUserEventsGcsTest.java @@ -17,16 +17,20 @@ package events; import static com.google.common.truth.Truth.assertThat; +import static events.ImportUserEventsGcs.importUserEventsFromGcs; +import static events.setup.EventsCreateGcsBucket.createGcsBucketAndUploadData; import com.google.cloud.ServiceOptions; -import events.setup.EventsCreateGcsBucket; import java.io.ByteArrayOutputStream; import java.io.IOException; 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; +@RunWith(JUnit4.class) public class ImportUserEventsGcsTest { private ByteArrayOutputStream bout; @@ -34,27 +38,46 @@ public class ImportUserEventsGcsTest { @Before public void setUp() throws IOException, InterruptedException { - EventsCreateGcsBucket.main(); + bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + } + @Test + public void testValidImportUserEventsGcs() throws IOException, InterruptedException { String projectId = ServiceOptions.getDefaultProjectId(); String defaultCatalog = String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); + String bucketName = "events_tests_bucket"; String gcsEventsObject = "user_events.json"; - bout = new ByteArrayOutputStream(); - PrintStream out = new PrintStream(bout); - originalPrintStream = System.out; - System.setOut(out); - ImportUserEventsGcs.importUserEventsFromGcs(gcsEventsObject, defaultCatalog); + createGcsBucketAndUploadData(bucketName); + importUserEventsFromGcs(defaultCatalog, bucketName, gcsEventsObject); + + String outputResult = bout.toString(); + + assertThat(outputResult).contains("Import user events from google cloud source request"); + assertThat(outputResult).contains("Number of successfully imported events:"); + assertThat(outputResult).contains("Number of failures during the importing: 0"); } @Test - public void testImportUserEventsGcs() { + public void testInvalidImportUserEventsGcs() throws IOException, InterruptedException { + String projectId = ServiceOptions.getDefaultProjectId(); + String defaultCatalog = + String.format("projects/%s/locations/global/catalogs/default_catalog", projectId); + String bucketName = "invalid_events_tests_bucket"; + String gcsEventsObject = "user_events_some_invalid.json"; + + createGcsBucketAndUploadData(bucketName); + importUserEventsFromGcs(defaultCatalog, bucketName, gcsEventsObject); + String outputResult = bout.toString(); assertThat(outputResult).contains("Import user events from google cloud source request"); - assertThat(outputResult).contains("Number of successfully imported events"); - assertThat(outputResult).contains("Number of failures during the importing"); + assertThat(outputResult).contains("Number of successfully imported events:"); + assertThat(outputResult).contains("Number of failures during the importing:"); } @After diff --git a/samples/interactive-tutorials/src/test/java/events/ImportUserEventsInlineTest.java b/samples/interactive-tutorials/src/test/java/events/ImportUserEventsInlineTest.java index f6db8372..f182a5ad 100644 --- a/samples/interactive-tutorials/src/test/java/events/ImportUserEventsInlineTest.java +++ b/samples/interactive-tutorials/src/test/java/events/ImportUserEventsInlineTest.java @@ -26,7 +26,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 ImportUserEventsInlineTest { private ByteArrayOutputStream bout; diff --git a/samples/interactive-tutorials/src/test/java/events/PurgeUserEventTest.java b/samples/interactive-tutorials/src/test/java/events/PurgeUserEventTest.java index 7c4eb446..13e68970 100644 --- a/samples/interactive-tutorials/src/test/java/events/PurgeUserEventTest.java +++ b/samples/interactive-tutorials/src/test/java/events/PurgeUserEventTest.java @@ -27,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 PurgeUserEventTest { private ByteArrayOutputStream bout; diff --git a/samples/interactive-tutorials/src/test/java/events/RejoinUserEventTest.java b/samples/interactive-tutorials/src/test/java/events/RejoinUserEventTest.java index fd478dff..446ab2d9 100644 --- a/samples/interactive-tutorials/src/test/java/events/RejoinUserEventTest.java +++ b/samples/interactive-tutorials/src/test/java/events/RejoinUserEventTest.java @@ -27,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 RejoinUserEventTest { private ByteArrayOutputStream bout; diff --git a/samples/interactive-tutorials/src/test/java/events/WriteUserEventTest.java b/samples/interactive-tutorials/src/test/java/events/WriteUserEventTest.java index ebff18ca..46f5a652 100644 --- a/samples/interactive-tutorials/src/test/java/events/WriteUserEventTest.java +++ b/samples/interactive-tutorials/src/test/java/events/WriteUserEventTest.java @@ -27,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 WriteUserEventTest { private ByteArrayOutputStream bout; diff --git a/samples/interactive-tutorials/src/test/java/events/setup/EventsCreateBigQueryTableTest.java b/samples/interactive-tutorials/src/test/java/events/setup/EventsCreateBigQueryTableTest.java new file mode 100644 index 00000000..33727613 --- /dev/null +++ b/samples/interactive-tutorials/src/test/java/events/setup/EventsCreateBigQueryTableTest.java @@ -0,0 +1,91 @@ +/* + * 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 events.setup; + +import static com.google.common.truth.Truth.assertThat; +import static events.setup.EventsCreateGcsBucket.createGcsBucketAndUploadData; +import static setup.SetupCleanup.createBqDataset; +import static setup.SetupCleanup.createBqTable; +import static setup.SetupCleanup.getGson; +import static setup.SetupCleanup.uploadDataToBqTable; + +import com.google.cloud.bigquery.Field; +import com.google.cloud.bigquery.Schema; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; +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 EventsCreateBigQueryTableTest { + + private ByteArrayOutputStream bout; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException, InterruptedException, ExecutionException { + String dataset = "user_events"; + String validEventsTable = "events"; + String invalidEventsTable = "events_some_invalid"; + String bucketName = "events_tests_bucket"; + String eventsSchemaFilePath = "src/main/resources/events_schema.json"; + String validEventsSourceFile = String.format("gs://%s/user_events.json", bucketName); + String invalidEventsSourceFile = + String.format("gs://%s/user_events_some_invalid.json", bucketName); + + BufferedReader bufferedReader = new BufferedReader(new FileReader(eventsSchemaFilePath)); + String jsonToString = bufferedReader.lines().collect(Collectors.joining()); + jsonToString = jsonToString.replace("\"fields\"", "\"subFields\""); + Field[] fields = getGson().fromJson(jsonToString, Field[].class); + Schema eventsSchema = Schema.of(fields); + + bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + createGcsBucketAndUploadData(bucketName); + createBqDataset(dataset); + createBqTable(dataset, validEventsTable, eventsSchema); + uploadDataToBqTable(dataset, validEventsTable, validEventsSourceFile, eventsSchema); + createBqTable(dataset, invalidEventsTable, eventsSchema); + uploadDataToBqTable(dataset, invalidEventsTable, invalidEventsSourceFile, eventsSchema); + } + + @Test + public void testEventsCreateBigQueryTable() { + String outputResult = bout.toString(); + + assertThat(outputResult).contains("Json from GCS successfully loaded in a table 'events'."); + assertThat(outputResult) + .contains("Json from GCS successfully loaded in a table 'events_some_invalid'."); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } +} diff --git a/samples/interactive-tutorials/src/test/java/events/setup/EventsCreateGcsBucketTest.java b/samples/interactive-tutorials/src/test/java/events/setup/EventsCreateGcsBucketTest.java new file mode 100644 index 00000000..10d31f1a --- /dev/null +++ b/samples/interactive-tutorials/src/test/java/events/setup/EventsCreateGcsBucketTest.java @@ -0,0 +1,68 @@ +/* + * 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 events.setup; + +import static com.google.common.truth.Truth.assertThat; +import static events.setup.EventsCreateGcsBucket.createGcsBucketAndUploadData; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +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 EventsCreateGcsBucketTest { + + private ByteArrayOutputStream bout; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException, InterruptedException, ExecutionException { + + String bucketName = "events_tests_bucket"; + + bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + createGcsBucketAndUploadData(bucketName); + } + + @Test + public void testEventsCreateGcsBucket() { + String outputResult = bout.toString(); + + assertThat(outputResult).contains("Events gcs bucket events_tests_bucket was created."); + assertThat(outputResult) + .contains("File 'user_events.json' was uploaded into bucket 'events_tests_bucket'."); + assertThat(outputResult) + .contains( + "File 'user_events_some_invalid.json' was uploaded into bucket 'events_tests_bucket'."); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } +} diff --git a/samples/interactive-tutorials/src/test/java/events/setup/RemoveEventsResourcesTest.java b/samples/interactive-tutorials/src/test/java/events/setup/RemoveEventsResourcesTest.java new file mode 100644 index 00000000..8614483d --- /dev/null +++ b/samples/interactive-tutorials/src/test/java/events/setup/RemoveEventsResourcesTest.java @@ -0,0 +1,56 @@ +package events.setup; + +import static com.google.common.truth.Truth.assertThat; +import static events.setup.RemoveEventsResources.deleteAllProducts; +import static setup.SetupCleanup.deleteBucket; +import static setup.SetupCleanup.deleteDataset; + +import com.google.cloud.ServiceOptions; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +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 RemoveEventsResourcesTest { + + private ByteArrayOutputStream bout; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException, InterruptedException, ExecutionException { + String projectId = ServiceOptions.getDefaultProjectId(); + String bucketName = "events_tests_bucket"; + String branchName = + String.format( + "projects/%s/locations/global/catalogs/default_catalog/branches/0", projectId); + + bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + deleteBucket(bucketName); + deleteAllProducts(branchName); + deleteDataset(projectId, "user_events"); + } + + @Test + public void testRemoveEventsResources() { + String outputResult = bout.toString(); + + assertThat(outputResult).contains("Deleting products in process, please wait..."); + assertThat(outputResult).contains("products were deleted from"); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } +} diff --git a/samples/interactive-tutorials/src/test/java/events/setup/UpdateUserEventsJsonTest.java b/samples/interactive-tutorials/src/test/java/events/setup/UpdateUserEventsJsonTest.java new file mode 100644 index 00000000..21623889 --- /dev/null +++ b/samples/interactive-tutorials/src/test/java/events/setup/UpdateUserEventsJsonTest.java @@ -0,0 +1,67 @@ +/* + * 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 events.setup; + +import static com.google.common.truth.Truth.assertThat; +import static events.setup.UpdateUserEventsJson.updateEventsTimestamp; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.concurrent.ExecutionException; +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 UpdateUserEventsJsonTest { + + private ByteArrayOutputStream bout; + private PrintStream originalPrintStream; + + @Before + public void setUp() throws IOException, InterruptedException, ExecutionException { + String filePath = "src/test/java/resources/user_events.json"; + String invalidFilePath = "src/test/java/resources/user_events_some_invalid.json"; + bout = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + originalPrintStream = System.out; + System.setOut(out); + + updateEventsTimestamp(filePath); + updateEventsTimestamp(invalidFilePath); + } + + @Test + public void testUpdateUserEventsJson() { + String outputResult = bout.toString(); + + assertThat(outputResult) + .contains("User events file 'src/test/java/resources/user_events.json' updated."); + assertThat(outputResult) + .contains( + "User events file 'src/test/java/resources/user_events_some_invalid.json' updated."); + } + + @After + public void tearDown() { + System.out.flush(); + System.setOut(originalPrintStream); + } +} diff --git a/samples/interactive-tutorials/src/test/java/resources/user_events.json b/samples/interactive-tutorials/src/test/java/resources/user_events.json new file mode 100644 index 00000000..76d7c0df --- /dev/null +++ b/samples/interactive-tutorials/src/test/java/resources/user_events.json @@ -0,0 +1,4 @@ +{"eventType":"home-page-view","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00"} +{"eventType":"search","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00","searchQuery":"RockerJeans teenagers blue jeans"} +{"eventType":"search","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00","searchQuery":"SocksUnlimited teenagers black socks"} +{"eventType":"detail-page-view","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00","productDetails":{"product":{"id":"GGCOGAEC100616"},"quantity":3}} \ No newline at end of file diff --git a/samples/interactive-tutorials/src/test/java/resources/user_events_some_invalid.json b/samples/interactive-tutorials/src/test/java/resources/user_events_some_invalid.json new file mode 100644 index 00000000..27e00a0c --- /dev/null +++ b/samples/interactive-tutorials/src/test/java/resources/user_events_some_invalid.json @@ -0,0 +1,4 @@ +{"eventType":"home-page-view","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00"} +{"eventType":"invalid","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00","searchQuery":"RockerJeans teenagers blue jeans"} +{"eventType":"search","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00","searchQuery":"SocksUnlimited teenagers black socks"} +{"eventType":"detail-page-view","visitorId":"bjbs_group1_visitor1","eventTime":"2022-04-13T10:27:42+00:00","productDetails":{"product":{"id":"GGCOGAEC100616"},"quantity":3}}