Skip to content
This repository was archived by the owner on Oct 3, 2023. It is now read-only.

Commit 20d2539

Browse files
authored
docs(samples): Refactoring events package (#481)
1 parent 541e280 commit 20d2539

20 files changed

+265
-333
lines changed

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,8 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-retail/tree/m
8585
| 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) |
8686
| 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) |
8787
| 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) |
88+
| 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) |
8889
| 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) |
89-
| 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) |
90-
| 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) |
9190
| 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) |
9291
| 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) |
9392
| 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) |

samples/interactive-tutorials/src/main/java/events/ImportUserEventsBigQuery.java

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
package events;
2222

23-
import com.google.cloud.ServiceOptions;
23+
import com.google.api.gax.rpc.NotFoundException;
2424
import com.google.cloud.bigquery.BigQueryException;
2525
import com.google.cloud.retail.v2.BigQuerySource;
2626
import com.google.cloud.retail.v2.ImportMetadata;
@@ -31,26 +31,30 @@
3131
import com.google.longrunning.Operation;
3232
import com.google.longrunning.OperationsClient;
3333
import java.io.IOException;
34+
import java.time.Instant;
35+
import java.util.concurrent.TimeUnit;
3436

3537
public class ImportUserEventsBigQuery {
3638

3739
public static void main(String[] args) throws IOException, InterruptedException {
3840
// TODO(developer): Replace these variables before running the sample.
39-
String projectId = ServiceOptions.getDefaultProjectId();
41+
String projectId = "your-project-id";
4042
String defaultCatalog =
4143
String.format("projects/%s/locations/global/catalogs/default_catalog", projectId);
42-
// TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE: defaultCatalog =
43-
// "invalid_catalog_name"
44+
// TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE:
45+
// defaultCatalog = "invalid_catalog_name";
4446
String datasetId = "user_events";
4547
String tableId = "events";
46-
// TO CHECK ERROR HANDLING USE THE TABLE OF INVALID USER EVENTS: tableId = "events_some_invalid"
48+
// TO CHECK ERROR HANDLING USE THE TABLE OF INVALID USER EVENTS:
49+
// tableId = "events_some_invalid";
4750

4851
importUserEventsFromBigQuery(projectId, defaultCatalog, datasetId, tableId);
4952
}
5053

5154
public static void importUserEventsFromBigQuery(
5255
String projectId, String defaultCatalog, String datasetId, String tableId)
5356
throws IOException, InterruptedException {
57+
5458
try {
5559
String dataSchema = "user_event";
5660

@@ -73,30 +77,32 @@ public static void importUserEventsFromBigQuery(
7377

7478
System.out.printf("Import user events from BigQuery source request: %s%n", importRequest);
7579

76-
// Initialize client that will be used to send requests. This client only needs to be created
77-
// once, and can be reused for multiple requests. After completing all of your requests, call
78-
// the "close" method on the client to safely clean up any remaining background resources.
80+
// Initialize client that will be used to send requests. This client only
81+
// needs to be created once, and can be reused for multiple requests. After
82+
// completing all of your requests, call the "close" method on the client to
83+
// safely clean up any remaining background resources.
7984
try (UserEventServiceClient serviceClient = UserEventServiceClient.create()) {
8085
String operationName =
8186
serviceClient.importUserEventsCallable().call(importRequest).getName();
8287

83-
System.out.printf("OperationName = %s\n", operationName);
88+
System.out.printf("OperationName = %s%n", operationName);
8489
OperationsClient operationsClient = serviceClient.getOperationsClient();
8590
Operation operation = operationsClient.getOperation(operationName);
8691

87-
while (!operation.getDone()) {
92+
Instant deadline = Instant.now().plusSeconds(60);
93+
94+
while (!operation.getDone() || Instant.now().isBefore(deadline)) {
8895
// Keep polling the operation periodically until the import task is done.
89-
int awaitDuration = 30000;
90-
Thread.sleep(awaitDuration);
96+
TimeUnit.SECONDS.sleep(30);
9197
operation = operationsClient.getOperation(operationName);
9298
}
9399

94100
if (operation.hasMetadata()) {
95101
ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class);
96102
System.out.printf(
97-
"Number of successfully imported events: %s\n", metadata.getSuccessCount());
103+
"Number of successfully imported events: %s%n", metadata.getSuccessCount());
98104
System.out.printf(
99-
"Number of failures during the importing: %s\n", metadata.getFailureCount());
105+
"Number of failures during the importing: %s%n", metadata.getFailureCount());
100106
}
101107

102108
if (operation.hasResponse()) {
@@ -107,6 +113,8 @@ public static void importUserEventsFromBigQuery(
107113
}
108114
} catch (BigQueryException e) {
109115
System.out.printf("Exception message: %s", e.getMessage());
116+
} catch (NotFoundException e) {
117+
System.out.printf("Catalog name is not found.%n%s%n", e.getMessage());
110118
}
111119
}
112120
}

samples/interactive-tutorials/src/main/java/events/ImportUserEventsGcs.java

Lines changed: 81 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@
2121
package events;
2222

2323
import com.google.api.gax.rpc.InvalidArgumentException;
24-
import com.google.cloud.ServiceOptions;
25-
import com.google.cloud.bigquery.BigQueryException;
24+
import com.google.api.gax.rpc.PermissionDeniedException;
2625
import com.google.cloud.retail.v2.GcsSource;
2726
import com.google.cloud.retail.v2.ImportErrorsConfig;
2827
import com.google.cloud.retail.v2.ImportMetadata;
@@ -32,91 +31,99 @@
3231
import com.google.cloud.retail.v2.UserEventServiceClient;
3332
import com.google.longrunning.Operation;
3433
import com.google.longrunning.OperationsClient;
35-
import events.setup.EventsCreateGcsBucket;
3634
import java.io.IOException;
35+
import java.time.Instant;
36+
import java.util.concurrent.TimeUnit;
3737

3838
public class ImportUserEventsGcs {
3939

4040
public static void main(String[] args) throws IOException, InterruptedException {
4141
// TODO(developer): Replace these variables before running the sample.
42-
String projectId = ServiceOptions.getDefaultProjectId();
42+
String projectId = "your-project-id";
4343
String defaultCatalog =
4444
String.format("projects/%s/locations/global/catalogs/default_catalog", projectId);
45-
// TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE: defaultCatalog =
46-
// "invalid_catalog_name"
47-
String gcsEventsObject = "user_events.json";
48-
// TO CHECK ERROR HANDLING USE THE JSON WITH INVALID USER EVENT: gcsEventsObject =
49-
// "user_events_some_invalid.json"
50-
51-
importUserEventsFromGcs(gcsEventsObject, defaultCatalog);
45+
// TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE:
46+
// defaultCatalog = "invalid_catalog_name";
47+
String bucketName = System.getenv("EVENTS_BUCKET_NAME");
48+
String gcsUserEventsObject = "user_events.json";
49+
// TO CHECK ERROR HANDLING USE THE JSON WITH INVALID USER EVENT:
50+
// gcsUserEventsObject = "user_events_some_invalid.json";
51+
52+
importUserEventsFromGcs(defaultCatalog, bucketName, gcsUserEventsObject);
5253
}
5354

54-
public static void importUserEventsFromGcs(String gcsEventsObject, String defaultCatalog)
55+
public static void importUserEventsFromGcs(
56+
String defaultCatalog, String bucketName, String gcsUserEventsObject)
5557
throws IOException, InterruptedException {
56-
try {
57-
String gcsBucket = String.format("gs://%s", EventsCreateGcsBucket.getBucketName());
58-
String gcsErrorsBucket = String.format("%s/error", gcsBucket);
59-
60-
GcsSource gcsSource =
61-
GcsSource.newBuilder()
62-
.addInputUris(String.format("%s/%s", gcsBucket, gcsEventsObject))
63-
.build();
64-
65-
UserEventInputConfig inputConfig =
66-
UserEventInputConfig.newBuilder().setGcsSource(gcsSource).build();
67-
68-
ImportErrorsConfig errorsConfig =
69-
ImportErrorsConfig.newBuilder().setGcsPrefix(gcsErrorsBucket).build();
70-
71-
ImportUserEventsRequest importRequest =
72-
ImportUserEventsRequest.newBuilder()
73-
.setParent(defaultCatalog)
74-
.setInputConfig(inputConfig)
75-
.setErrorsConfig(errorsConfig)
76-
.build();
77-
78-
System.out.printf("Import user events from google cloud source request: %s%n", importRequest);
79-
80-
// Initialize client that will be used to send requests. This client only needs to be created
81-
// once, and can be reused for multiple requests. After completing all of your requests, call
82-
// the "close" method on the client to safely clean up any remaining background resources.
83-
try (UserEventServiceClient serviceClient = UserEventServiceClient.create()) {
84-
String operationName =
85-
serviceClient.importUserEventsCallable().call(importRequest).getName();
86-
87-
System.out.printf("OperationName = %s\n", operationName);
88-
89-
OperationsClient operationsClient = serviceClient.getOperationsClient();
90-
Operation operation = operationsClient.getOperation(operationName);
91-
92-
while (!operation.getDone()) {
93-
// Keep polling the operation periodically until the import task is done.
94-
int awaitDuration = 30000;
95-
Thread.sleep(awaitDuration);
96-
operation = operationsClient.getOperation(operationName);
97-
}
98-
99-
if (operation.hasMetadata()) {
100-
ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class);
101-
System.out.printf(
102-
"Number of successfully imported events: %s\n", metadata.getSuccessCount());
103-
System.out.printf(
104-
"Number of failures during the importing: %s\n", metadata.getFailureCount());
105-
}
106-
107-
if (operation.hasResponse()) {
108-
ImportUserEventsResponse response =
109-
operation.getResponse().unpack(ImportUserEventsResponse.class);
110-
System.out.printf("Operation result: %s%n", response);
111-
}
112-
} catch (InvalidArgumentException e) {
58+
String gcsBucket = String.format("gs://%s", bucketName);
59+
String gcsErrorsBucket = String.format("%s/error", gcsBucket);
60+
61+
GcsSource gcsSource =
62+
GcsSource.newBuilder()
63+
.addInputUris(String.format("%s/%s", gcsBucket, gcsUserEventsObject))
64+
.build();
65+
66+
UserEventInputConfig inputConfig =
67+
UserEventInputConfig.newBuilder().setGcsSource(gcsSource).build();
68+
69+
System.out.println("GCS source: " + gcsSource.getInputUrisList());
70+
71+
ImportErrorsConfig errorsConfig =
72+
ImportErrorsConfig.newBuilder().setGcsPrefix(gcsErrorsBucket).build();
73+
74+
ImportUserEventsRequest importRequest =
75+
ImportUserEventsRequest.newBuilder()
76+
.setParent(defaultCatalog)
77+
.setInputConfig(inputConfig)
78+
.setErrorsConfig(errorsConfig)
79+
.build();
80+
System.out.printf("Import user events from google cloud source request: %s%n", importRequest);
81+
82+
// Initialize client that will be used to send requests. This client only
83+
// needs to be created once, and can be reused for multiple requests. After
84+
// completing all of your requests, call the "close" method on the client to
85+
// safely clean up any remaining background resources.
86+
try (UserEventServiceClient serviceClient = UserEventServiceClient.create()) {
87+
String operationName = serviceClient.importUserEventsCallable().call(importRequest).getName();
88+
89+
System.out.println("The operation was started.");
90+
System.out.printf("OperationName = %s%n", operationName);
91+
92+
OperationsClient operationsClient = serviceClient.getOperationsClient();
93+
Operation operation = operationsClient.getOperation(operationName);
94+
95+
Instant deadline = Instant.now().plusSeconds(60);
96+
97+
while (!operation.getDone() || Instant.now().isBefore(deadline)) {
98+
System.out.println("Please wait till operation is done.");
99+
TimeUnit.SECONDS.sleep(30);
100+
operation = operationsClient.getOperation(operationName);
101+
}
102+
103+
if (operation.hasMetadata()) {
104+
ImportMetadata metadata = operation.getMetadata().unpack(ImportMetadata.class);
105+
System.out.printf(
106+
"Number of successfully imported events: %s%n", metadata.getSuccessCount());
113107
System.out.printf(
114-
"Given GCS input path was not found. %n%s%n "
115-
+ "Please run CreateTestResources class to create resources.",
116-
e.getMessage());
108+
"Number of failures during the importing: %s%n", metadata.getFailureCount());
109+
} else {
110+
System.out.println("Metadata is empty.");
111+
}
112+
113+
if (operation.hasResponse()) {
114+
ImportUserEventsResponse response =
115+
operation.getResponse().unpack(ImportUserEventsResponse.class);
116+
System.out.printf("Operation result: %s%n", response);
117+
} else {
118+
System.out.println("Operation result is empty.");
117119
}
118-
} catch (BigQueryException e) {
119-
System.out.printf("Exception message: %s", e.getMessage());
120+
} catch (InvalidArgumentException e) {
121+
System.out.printf(
122+
"%s%n'%s' file does not exist in the bucket. Please "
123+
+ "make sure you have followed the setting up instructions.",
124+
e.getMessage(), gcsUserEventsObject);
125+
} catch (PermissionDeniedException e) {
126+
System.out.println(e.getMessage());
120127
}
121128
}
122129
}

samples/interactive-tutorials/src/main/java/events/ImportUserEventsInline.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
package events;
2222

2323
import com.google.api.gax.longrunning.OperationFuture;
24-
import com.google.cloud.ServiceOptions;
2524
import com.google.cloud.bigquery.BigQueryException;
2625
import com.google.cloud.retail.v2.ImportMetadata;
2726
import com.google.cloud.retail.v2.ImportUserEventsRequest;
@@ -44,7 +43,7 @@ public class ImportUserEventsInline {
4443
public static void main(String[] args)
4544
throws IOException, ExecutionException, InterruptedException {
4645
// TODO(developer): Replace these variables before running the sample.
47-
String projectId = ServiceOptions.getDefaultProjectId();
46+
String projectId = "your-project-id";
4847
String defaultCatalog =
4948
String.format("projects/%s/locations/global/catalogs/default_catalog", projectId);
5049

@@ -88,9 +87,10 @@ public static void importUserEventsFromInlineSource(String defaultCatalog)
8887
.build();
8988
System.out.printf("Import user events from inline source request: %s%n", importRequest);
9089

91-
// Initialize client that will be used to send requests. This client only needs to be created
92-
// once, and can be reused for multiple requests. After completing all of your requests, call
93-
// the "close" method on the client to safely clean up any remaining background resources.
90+
// Initialize client that will be used to send requests. This client only
91+
// needs to be created once, and can be reused for multiple requests. After
92+
// completing all of your requests, call the "close" method on the client to
93+
// safely clean up any remaining background resources.
9494
try (UserEventServiceClient userEventServiceClient = UserEventServiceClient.create()) {
9595
OperationFuture<ImportUserEventsResponse, ImportMetadata> importOperation =
9696
userEventServiceClient.importUserEventsAsync(importRequest);

0 commit comments

Comments
 (0)