Skip to content

Commit 715bbb3

Browse files
docs: add async api code snippet (#25)
* docs: add async api code snippet * fix lint * fix lint * use dataformat * fix import order * rename to inputUri * add pom * update gitignore * add pom in snapshot and install-without-bom * add indentation * reduce buckeet name length * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * rm region tag in test Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 4ada54b commit 715bbb3

File tree

3 files changed

+203
-6
lines changed

3 files changed

+203
-6
lines changed

optimization/snippets/pom.xml

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@
22
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
33
<modelVersion>4.0.0</modelVersion>
44
<groupId>com.google.cloud</groupId>
5-
<artifactId>-snippets</artifactId>
6-
<packaging>jar</packaging>
7-
<name>Google Cloud Fleet Routing Snippets</name>
5+
<artifactId>optimization-ai-snippets</artifactId>
6+
<packaging>pom</packaging>
7+
<name>Google Cloud Fleet Routing Samples Parent</name>
88
<url>https://github.com/googleapis/java-optimization</url>
9+
<description>
10+
Java idiomatic client for Google Cloud Platform services.
11+
</description>
912

1013
<!--
1114
The parent pom defines common style checks and testing strategies for our samples.
@@ -23,14 +26,30 @@
2326
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
2427
</properties>
2528

29+
<!-- [START optimizationai_install_with_bom] -->
30+
<dependencyManagement>
31+
<dependencies>
32+
<dependency>
33+
<groupId>com.google.cloud</groupId>
34+
<artifactId>libraries-bom</artifactId>
35+
<version>25.1.0</version>
36+
<type>pom</type>
37+
<scope>import</scope>
38+
</dependency>
39+
</dependencies>
40+
</dependencyManagement>
41+
2642
<dependencies>
27-
<!-- TODO: switch to libraries-bom after this artifact is included -->
2843
<dependency>
2944
<groupId>com.google.cloud</groupId>
3045
<artifactId>google-cloud-optimization</artifactId>
3146
<version>0.1.1</version>
3247
</dependency>
33-
48+
<!-- [END optimizationai_install_with_bom] -->
49+
<dependency>
50+
<groupId>com.google.cloud</groupId>
51+
<artifactId>google-cloud-storage</artifactId>
52+
</dependency>
3453
<dependency>
3554
<groupId>junit</groupId>
3655
<artifactId>junit</artifactId>
@@ -44,4 +63,4 @@
4463
<scope>test</scope>
4564
</dependency>
4665
</dependencies>
47-
</project>
66+
</project>
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.optimizationai;
18+
19+
// [START cloudoptimization_async_api]
20+
import com.google.api.gax.longrunning.OperationFuture;
21+
import com.google.cloud.optimization.v1.AsyncModelMetadata;
22+
import com.google.cloud.optimization.v1.BatchOptimizeToursRequest;
23+
import com.google.cloud.optimization.v1.BatchOptimizeToursRequest.AsyncModelConfig;
24+
import com.google.cloud.optimization.v1.BatchOptimizeToursResponse;
25+
import com.google.cloud.optimization.v1.DataFormat;
26+
import com.google.cloud.optimization.v1.FleetRoutingClient;
27+
import com.google.cloud.optimization.v1.GcsDestination;
28+
import com.google.cloud.optimization.v1.GcsSource;
29+
import com.google.cloud.optimization.v1.InputConfig;
30+
import com.google.cloud.optimization.v1.OutputConfig;
31+
32+
/**
33+
* This is an example to send a request to Cloud Fleet Routing asynchronous API via Java API Client.
34+
* A sample async_request_java.textproto file and a sample request_model_java.json file can be found
35+
* in the resources folder.
36+
*/
37+
public class AsyncApi {
38+
public static void callAsyncApi() throws Exception {
39+
// TODO(developer): Replace these variables before running the sample.
40+
String projectParent = "projects/{YOUR_GCP_PROJECT_ID}";
41+
String inputUri = "gs://YOUR_GCS_PATH";
42+
String outputUri = "gs://YOUR_SOLUTION_PATH";
43+
callAsyncApi(projectParent, inputUri, outputUri);
44+
}
45+
46+
public static void callAsyncApi(String projectParent, String inputUri, String outputUri)
47+
throws Exception {
48+
GcsSource gcsSource = GcsSource.newBuilder().setUri(inputUri).build();
49+
InputConfig inputConfig =
50+
InputConfig.newBuilder().setGcsSource(gcsSource).setDataFormat(DataFormat.JSON).build();
51+
GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputUri).build();
52+
OutputConfig outputConfig =
53+
OutputConfig.newBuilder()
54+
.setGcsDestination(gcsDestination)
55+
.setDataFormat(DataFormat.JSON)
56+
.build();
57+
58+
AsyncModelConfig asyncModelConfig =
59+
AsyncModelConfig.newBuilder()
60+
.setInputConfig(inputConfig)
61+
.setOutputConfig(outputConfig)
62+
.build();
63+
BatchOptimizeToursRequest request =
64+
BatchOptimizeToursRequest.newBuilder()
65+
.setParent(projectParent)
66+
.addModelConfigs(asyncModelConfig)
67+
.build();
68+
69+
FleetRoutingClient fleetRoutingClient = FleetRoutingClient.create();
70+
OperationFuture<BatchOptimizeToursResponse, AsyncModelMetadata> response =
71+
fleetRoutingClient.batchOptimizeToursAsync(request);
72+
System.out.format("the response name: %s\n", response.getInitialFuture().get().getName());
73+
74+
// Block to wait for the job to finish.
75+
response.getPollingFuture().get();
76+
if (response.getMetadata().get().getState() == AsyncModelMetadata.State.SUCCEEDED) {
77+
// Code to do your stuff
78+
System.out.println("Job finished successfully.");
79+
} else {
80+
System.out.println(
81+
"Job failed with message:" + response.getPollingFuture().get().getErrorMessage());
82+
}
83+
}
84+
}
85+
// [END cloudoptimization_async_api]
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.optimizationai;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
21+
import com.google.api.gax.paging.Page;
22+
import com.google.cloud.storage.Blob;
23+
import com.google.cloud.storage.BucketInfo;
24+
import com.google.cloud.storage.Storage;
25+
import com.google.cloud.storage.StorageOptions;
26+
import java.io.ByteArrayOutputStream;
27+
import java.io.PrintStream;
28+
import java.util.UUID;
29+
import org.junit.After;
30+
import org.junit.Before;
31+
import org.junit.Test;
32+
33+
/** Tests for AsyncApi sample. */
34+
public class AsyncApiTest {
35+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
36+
private static final String PROJECT_PARENT = String.format("projects/%s", PROJECT_ID);
37+
private static final String BUCKET_NAME =
38+
String.format("optimizationai-test-%s", UUID.randomUUID());
39+
private static final String INPUT_URI =
40+
"gs://cloud-samples-data/optimization-ai/async_request_model.json";
41+
private static final String BATCH_OUTPUT_URI =
42+
String.format("gs://%s/code_snippets_test_output.json", BUCKET_NAME);
43+
44+
private ByteArrayOutputStream bout;
45+
private PrintStream out;
46+
private PrintStream originalPrintStream;
47+
48+
private static void cleanUpBucket() {
49+
Storage storage = StorageOptions.getDefaultInstance().getService();
50+
Page<Blob> blobs = storage.list(BUCKET_NAME, Storage.BlobListOption.currentDirectory());
51+
52+
deleteDirectory(storage, blobs);
53+
}
54+
55+
private static void deleteDirectory(Storage storage, Page<Blob> blobs) {
56+
for (Blob blob : blobs.iterateAll()) {
57+
if (!blob.delete()) {
58+
Page<Blob> subBlobs =
59+
storage.list(
60+
BUCKET_NAME,
61+
Storage.BlobListOption.currentDirectory(),
62+
Storage.BlobListOption.prefix(blob.getName()));
63+
64+
deleteDirectory(storage, subBlobs);
65+
}
66+
}
67+
}
68+
69+
@Before
70+
public void setUp() {
71+
bout = new ByteArrayOutputStream();
72+
out = new PrintStream(bout);
73+
originalPrintStream = System.out;
74+
System.setOut(out);
75+
76+
Storage storage = StorageOptions.getDefaultInstance().getService();
77+
storage.create(BucketInfo.of(BUCKET_NAME));
78+
}
79+
80+
@After
81+
public void tearDown() {
82+
cleanUpBucket();
83+
System.out.flush();
84+
System.setOut(originalPrintStream);
85+
}
86+
87+
@Test
88+
public void testAsyncApi() throws Exception {
89+
AsyncApi.callAsyncApi(PROJECT_PARENT, INPUT_URI, BATCH_OUTPUT_URI);
90+
String got = bout.toString();
91+
assertThat(got).contains("Job");
92+
}
93+
}

0 commit comments

Comments
 (0)