Skip to content

Commit a1faaeb

Browse files
authored
chore: restore Compute client library examples (revert #7799) (#8590)
This reverts commit cb8c315.
1 parent 4864740 commit a1faaeb

5 files changed

Lines changed: 381 additions & 3 deletions

File tree

google-cloud-examples/src/main/java/com/google/cloud/examples/compute/README.md

Lines changed: 0 additions & 3 deletions
This file was deleted.
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/*
2+
* Copyright 2016 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.google.cloud.examples.compute.snippets;
18+
19+
import com.google.cloud.ServiceOptions;
20+
import com.google.cloud.compute.v1.Address;
21+
import com.google.cloud.compute.v1.AddressesClient;
22+
import com.google.cloud.compute.v1.AttachedDisk;
23+
import com.google.cloud.compute.v1.AttachedDisk.Type;
24+
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
25+
import com.google.cloud.compute.v1.Disk;
26+
import com.google.cloud.compute.v1.DisksClient;
27+
import com.google.cloud.compute.v1.InsertDiskRequest;
28+
import com.google.cloud.compute.v1.Instance;
29+
import com.google.cloud.compute.v1.InstancesClient;
30+
import com.google.cloud.compute.v1.NetworkInterface;
31+
import com.google.cloud.compute.v1.Operation;
32+
import java.io.IOException;
33+
34+
/**
35+
* A snippet for Google Cloud Compute Engine showing how to create a disk and an address. The
36+
* snippet also shows how to create a virtual machine instance using the created disk and address.
37+
*/
38+
public class CreateAddressDiskAndInstance {
39+
private static final String DEFAULT_PROJECT = ServiceOptions.getDefaultProjectId();
40+
private static final String ZONE = "us-central1-a";
41+
private static final String REGION = "us-central1";
42+
private static final String ADDRESS_NAME = "test-address";
43+
44+
// Setting image project and image family available in
45+
// https://cloud.google.com/compute/docs/images/os-details
46+
private static final String IMAGE_PROJECT = "debian-cloud";
47+
private static final String IMAGE_FAMILY = "debian-10";
48+
private static final String DEFAULT_IMAGE =
49+
String.format(
50+
"https://www.googleapis.com/compute/v1/projects/%s/global/images/%s",
51+
IMAGE_PROJECT, IMAGE_FAMILY);
52+
53+
public static void main(String... args) throws IOException {
54+
try (AddressesClient addressClient = AddressesClient.create()) {
55+
Address address = Address.newBuilder().setName(ADDRESS_NAME).build();
56+
Operation operation = addressClient.insert(DEFAULT_PROJECT, REGION, address);
57+
if (operation.getError() == null) {
58+
System.out.println("Address " + ADDRESS_NAME + " was successfully created");
59+
} else {
60+
// inspect operation.getErrors()
61+
throw new RuntimeException("Address creation failed");
62+
}
63+
}
64+
// Create a persistent disk
65+
try (DisksClient diskClient = DisksClient.create()) {
66+
Disk diskResource =
67+
Disk.newBuilder()
68+
.setName("test-disk")
69+
.setSourceImageId("debian-8-jessie-v20160329")
70+
.setSizeGb(10L)
71+
.build();
72+
InsertDiskRequest request =
73+
InsertDiskRequest.newBuilder()
74+
.setProject(DEFAULT_PROJECT)
75+
.setZone(ZONE)
76+
.setDiskResource(diskResource)
77+
.build();
78+
Operation response = diskClient.insert(request);
79+
if (response.getError() == null) {
80+
System.out.println("Disk " + diskResource.getName() + " was successfully created");
81+
} else {
82+
// inspect operation.getErrors()
83+
throw new RuntimeException("Disk creation failed");
84+
}
85+
}
86+
// Create a virtual machine instance
87+
try (InstancesClient instanceClient = InstancesClient.create()) {
88+
String machineType = String.format("zones/%s/machineTypes/%s", ZONE, "n1-standard-1");
89+
90+
AttachedDisk disk =
91+
AttachedDisk.newBuilder()
92+
.setBoot(true)
93+
.setAutoDelete(true)
94+
.setType(Type.PERSISTENT)
95+
.setDiskSizeGb(10L)
96+
.setInitializeParams(
97+
AttachedDiskInitializeParams.newBuilder().setSourceImage(DEFAULT_IMAGE).build())
98+
.build();
99+
NetworkInterface networkInterface = NetworkInterface.newBuilder().setName("default").build();
100+
Instance instanceResource =
101+
Instance.newBuilder()
102+
.setName("test-instance")
103+
.setMachineType(machineType)
104+
.addDisks(disk)
105+
.addNetworkInterfaces(networkInterface)
106+
.build();
107+
Operation response = instanceClient.insert(DEFAULT_PROJECT, ZONE, instanceResource);
108+
if (response.getError() == null) {
109+
System.out.println("Instance " + instanceResource.getName() + " was successfully created");
110+
} else {
111+
// inspect operation.getErrors()
112+
throw new RuntimeException("Instance creation failed");
113+
}
114+
}
115+
}
116+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* Copyright 2016 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.google.cloud.examples.compute.snippets;
18+
19+
import com.google.cloud.ServiceOptions;
20+
import com.google.cloud.compute.v1.AttachedDisk;
21+
import com.google.cloud.compute.v1.AttachedDisk.Type;
22+
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
23+
import com.google.cloud.compute.v1.Instance;
24+
import com.google.cloud.compute.v1.InstancesClient;
25+
import com.google.cloud.compute.v1.NetworkInterface;
26+
import com.google.cloud.compute.v1.Operation;
27+
import java.io.IOException;
28+
29+
/** A snippet for Google Cloud Compute Engine showing how to create a virtual machine instance. */
30+
public class CreateInstance {
31+
private static final String ZONE = "us-central1-a";
32+
private static final String DEFAULT_IMAGE =
33+
"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20150710";
34+
private static final String DEFAULT_PROJECT = ServiceOptions.getDefaultProjectId();
35+
36+
public static void main(String... args) throws IOException {
37+
try (InstancesClient instancesClient = InstancesClient.create()) {
38+
String machineType = String.format("zones/%s/machineTypes/%s", ZONE, "n1-standard-1");
39+
AttachedDisk disk =
40+
AttachedDisk.newBuilder()
41+
.setBoot(true)
42+
.setAutoDelete(true)
43+
.setType(Type.PERSISTENT)
44+
.setInitializeParams(
45+
AttachedDiskInitializeParams.newBuilder().setSourceImage(DEFAULT_IMAGE).build())
46+
.build();
47+
NetworkInterface networkInterface = NetworkInterface.newBuilder().setName("default").build();
48+
Instance instanceResource =
49+
Instance.newBuilder()
50+
.setName("instance-name")
51+
.setMachineType(machineType)
52+
.addDisks(disk)
53+
.addNetworkInterfaces(networkInterface)
54+
.build();
55+
Operation response = instancesClient.insert(DEFAULT_PROJECT, ZONE, instanceResource);
56+
if (response.getError() == null) {
57+
System.out.println("Instance was created successfully");
58+
} else {
59+
// inspect operation.getErrors()
60+
throw new RuntimeException("Instance creation failed");
61+
}
62+
}
63+
}
64+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Copyright 2016 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.google.cloud.examples.compute.snippets;
18+
19+
import com.google.cloud.ServiceOptions;
20+
import com.google.cloud.compute.v1.CreateSnapshotDiskRequest;
21+
import com.google.cloud.compute.v1.DisksClient;
22+
import com.google.cloud.compute.v1.Operation;
23+
import com.google.cloud.compute.v1.Snapshot;
24+
import java.io.IOException;
25+
26+
/**
27+
* A snippet for Google Cloud Compute Engine showing how to create a snapshot of a disk if the disk
28+
* exists.
29+
*/
30+
public class CreateSnapshot {
31+
private static final String DISK_NAME = "test-disk";
32+
private static final String DEFAULT_PROJECT = ServiceOptions.getDefaultProjectId();
33+
private static final String ZONE = "us-central1-a";
34+
35+
public static void main(String... args) throws IOException {
36+
Snapshot snapshotResource = Snapshot.newBuilder().setName("test-snapshot").build();
37+
CreateSnapshotDiskRequest diskRequest =
38+
CreateSnapshotDiskRequest.newBuilder()
39+
.setDisk(DISK_NAME)
40+
.setGuestFlush(Boolean.FALSE)
41+
.setSnapshotResource(snapshotResource)
42+
.build();
43+
try (DisksClient disksClient = DisksClient.create()) {
44+
Operation snapshotDisk = disksClient.createSnapshot(diskRequest);
45+
if (snapshotDisk.getError() == null) {
46+
System.out.println("Snapshot was successfully created");
47+
} else {
48+
// inspect operation.getErrors()
49+
throw new RuntimeException("Snapshot creation failed");
50+
}
51+
}
52+
}
53+
}
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
package com.google.cloud.examples.compute.v1;
2+
3+
import com.google.api.core.ApiFuture;
4+
import com.google.api.gax.core.FixedCredentialsProvider;
5+
import com.google.auth.Credentials;
6+
import com.google.auth.oauth2.GoogleCredentials;
7+
import com.google.cloud.compute.v1.Address;
8+
import com.google.cloud.compute.v1.AddressesClient;
9+
import com.google.cloud.compute.v1.AddressesSettings;
10+
import com.google.cloud.compute.v1.DeleteAddressRequest;
11+
import com.google.cloud.compute.v1.GetAddressRequest;
12+
import com.google.cloud.compute.v1.InsertAddressRequest;
13+
import com.google.cloud.compute.v1.ListAddressesRequest;
14+
import com.google.cloud.compute.v1.Operation;
15+
import java.io.IOException;
16+
import java.util.concurrent.ExecutionException;
17+
import java.util.concurrent.TimeUnit;
18+
19+
/** Working example code to make live calls on Addresses resources in a GCP Compute project. */
20+
public class ComputeExample {
21+
22+
// Replace the following String values with your Project and Region ids.
23+
private static String PROJECT_NAME = "my-project-id";
24+
private static String REGION = "us-central1";
25+
26+
/**
27+
* List addresses, Insert an address, and then delete the address. Use ResourceNames in the
28+
* request objects.
29+
*/
30+
public static void main(String[] args) throws IOException {
31+
AddressesClient client = createCredentialedClient();
32+
33+
System.out.println("Running with Gapic Client.");
34+
AddressesClient.ListPagedResponse listResponse = listAddresses(client);
35+
verifyListAddressWithGets(client, listResponse);
36+
37+
System.out.println("Running with Gapic Client and Resource Name.");
38+
String newAddressName = "new_address_name";
39+
System.out.println("Inserting address:");
40+
41+
insertNewAddressJustClient(client, newAddressName);
42+
43+
listAddresses(client);
44+
45+
System.out.println("Deleting address:");
46+
Operation deleteResponse =
47+
client.delete(
48+
DeleteAddressRequest.newBuilder()
49+
.setProject(PROJECT_NAME)
50+
.setAddress(newAddressName)
51+
.setRegion(REGION)
52+
.build());
53+
System.out.format("Result of delete: %s\n", deleteResponse.toString());
54+
int sleepTimeInSeconds = 3;
55+
System.out.format("Waiting %d seconds for server to update...\n", sleepTimeInSeconds);
56+
// Wait for the delete operation to finish on the server.
57+
try {
58+
TimeUnit.SECONDS.sleep(sleepTimeInSeconds);
59+
} catch (InterruptedException e) {
60+
e.printStackTrace();
61+
}
62+
listAddresses(client);
63+
}
64+
65+
private static AddressesClient createCredentialedClient() throws IOException {
66+
Credentials myCredentials = GoogleCredentials.getApplicationDefault();
67+
String myEndpoint = AddressesSettings.getDefaultEndpoint();
68+
69+
AddressesSettings addressesSettings =
70+
AddressesSettings.newBuilder()
71+
.setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
72+
.setTransportChannelProvider(
73+
AddressesSettings.defaultHttpJsonTransportProviderBuilder()
74+
.setEndpoint(myEndpoint)
75+
.build())
76+
.build();
77+
return AddressesClient.create(addressesSettings);
78+
}
79+
80+
private static void insertNewAddressJustClient(AddressesClient client, String newAddressName) {
81+
// Begin samplegen code for insertAddress().
82+
Address newAddress = Address.newBuilder().setName(newAddressName).build();
83+
Operation response = client.insert(PROJECT_NAME, REGION, newAddress);
84+
// End samplegen code for insertAddress().
85+
System.out.format("Result of insert: %s\n", response.toString());
86+
}
87+
88+
/** Use an InsertAddressRequest object to make an addresses.insert method call. */
89+
private static void insertNewAddressUsingRequest(AddressesClient client, String newAddressName)
90+
throws InterruptedException, ExecutionException {
91+
// Begin samplegen code for insertAddress().
92+
Address address = Address.newBuilder().build();
93+
InsertAddressRequest request =
94+
InsertAddressRequest.newBuilder().setRegion(REGION).setAddressResource(address).build();
95+
// Do something
96+
Operation response = client.insert(request);
97+
98+
// End samplegen code for insertAddress().
99+
System.out.format("Result of insert: %s\n", response.toString());
100+
}
101+
102+
/** Use an callable object to make an addresses.insert method call. */
103+
private static void insertAddressUsingCallable(AddressesClient client, String newAddressName)
104+
throws InterruptedException, ExecutionException {
105+
// Begin samplegen code for insertAddress().
106+
Address address = Address.newBuilder().build();
107+
InsertAddressRequest request =
108+
InsertAddressRequest.newBuilder()
109+
.setProject(PROJECT_NAME)
110+
.setRegion(REGION)
111+
.setAddressResource(address)
112+
.build();
113+
ApiFuture<Operation> future = client.insertCallable().futureCall(request);
114+
// Do something
115+
Operation response = future.get();
116+
117+
// End samplegen code for insertAddress().
118+
System.out.format("Result of insert: %s\n", response.toString());
119+
}
120+
121+
/** List Addresses in the under the project PROJECT_NAME and region REGION. */
122+
private static AddressesClient.ListPagedResponse listAddresses(AddressesClient client) {
123+
System.out.println("Listing addresses:");
124+
ListAddressesRequest listRequest =
125+
ListAddressesRequest.newBuilder().setProject(PROJECT_NAME).setRegion(REGION).build();
126+
AddressesClient.ListPagedResponse response = client.list(listRequest);
127+
for (Address address : response.iterateAll()) {
128+
System.out.println("\t - " + address.toString());
129+
}
130+
return response;
131+
}
132+
133+
private static void verifyListAddressWithGets(
134+
AddressesClient client, AddressesClient.ListPagedResponse listResponse) {
135+
for (Address address : listResponse.iterateAll()) {
136+
System.out.format("Making get request for address \"%s\"...\n", address.getName());
137+
138+
Address fetchedAddress =
139+
client.get(
140+
GetAddressRequest.newBuilder()
141+
.setAddress(address.getName())
142+
.setProject(PROJECT_NAME)
143+
.setRegion(REGION)
144+
.build());
145+
System.out.format("addresses.get returns \n\t%s\n\n", fetchedAddress.toString());
146+
}
147+
}
148+
}

0 commit comments

Comments
 (0)