Skip to content

Commit da877d8

Browse files
committed
Added code snippets for DNS.
Also extended example doc and added links. Refactored zone print.
1 parent 8e82f35 commit da877d8

File tree

6 files changed

+284
-57
lines changed

6 files changed

+284
-57
lines changed

gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java

+8
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,14 @@ public static Builder builder() {
9696
return new Builder();
9797
}
9898

99+
/**
100+
* Creates a default instance of {@code DnsOptions} with the project ID and credentials inferred
101+
* from the environment.
102+
*/
103+
public static DnsOptions defaultInstance() {
104+
return builder().build();
105+
}
106+
99107
@Override
100108
public boolean equals(Object obj) {
101109
return obj instanceof DnsOptions && baseEquals((DnsOptions) obj);

gcloud-java-examples/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ To run examples from your command line:
7474
* Here's an example run of `DnsExample`.
7575
7676
Note that you have to enable the Google Cloud DNS API on the [Google Developers Console][developers-console] before running the following commands.
77-
You will need to replace the domain name `elaborateexample.com` with your own domain name with verified ownership.
77+
You will need to replace the domain name `elaborateexample.com` with your own domain name with [verified ownership] (https://www.google.com/webmasters/verification/home).
7878
Also, note that the example creates and deletes DNS records of type A only. Operations with other record types are not implemented in the example.
7979
```
8080
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="create some-sample-zone elaborateexample.com. description"

gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java

+52-56
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
/**
3939
* An example of using Google Cloud DNS.
4040
*
41-
* <p>This example creates, deletes, gets, and lists zones, and creates and deletes DNS records of
42-
* type A.
41+
* <p>This example creates, deletes, gets, and lists zones. It also creates and deletes DNS records
42+
* of type A, and lists DNS records.
4343
*
4444
* <p>Steps needed for running the example:
4545
* <ol>
@@ -57,14 +57,16 @@
5757
* quota}</li>
5858
* </ol>
5959
*
60-
* <p>The first parameter is an optional {@code project_id} (logged-in project will be used if not
61-
* supplied). Second parameter is a DNS operation (list, delete, create,...). The remaining
62-
* arguments are specific to the operation. See each action's run method for the specific
63-
* interaction.
60+
* <p>The first parameter is an optional {@code project_id}. The project specified in the Google
61+
* Cloud SDK configuration (see {@code gcloud config list}) will be used if the project ID is not
62+
* supplied. The second parameter is a DNS operation (list, delete, create, ...). The remaining
63+
* arguments are specific to the operation. See each action's {@code run} method for the specific
64+
* arguments.
6465
*/
6566
public class DnsExample {
6667

6768
private static final Map<String, DnsAction> ACTIONS = new HashMap<>();
69+
private static final DateFormat FORMATTER = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
6870

6971
private interface DnsAction {
7072
void run(Dns dns, String... args);
@@ -77,7 +79,7 @@ private interface DnsAction {
7779
private static class CreateZoneAction implements DnsAction {
7880

7981
/**
80-
* Creates a zone with the provided name, dns name and description (in this order).
82+
* Creates a zone with the provided name, DNS name and description (in this order).
8183
*/
8284
@Override
8385
public void run(Dns dns, String... args) {
@@ -111,14 +113,8 @@ public void run(Dns dns, String... args) {
111113
Iterator<Zone> zoneIterator = dns.listZones().iterateAll();
112114
if (zoneIterator.hasNext()) {
113115
System.out.println("The project contains the following zones:");
114-
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
115116
while (zoneIterator.hasNext()) {
116-
Zone zone = zoneIterator.next();
117-
System.out.printf("%nName: %s%n", zone.name());
118-
System.out.printf("ID: %s%n", zone.id());
119-
System.out.printf("Description: %s%n", zone.description());
120-
System.out.printf("Created: %s%n", formatter.format(new Date(zone.creationTimeMillis())));
121-
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers()));
117+
printZone(zoneIterator.next());
122118
}
123119
} else {
124120
System.out.println("Project contains no zones.");
@@ -148,12 +144,7 @@ public void run(Dns dns, String... args) {
148144
if (zone == null) {
149145
System.out.printf("No zone with name '%s' exists.%n", zoneName);
150146
} else {
151-
System.out.printf("Name: %s%n", zone.name());
152-
System.out.printf("ID: %s%n", zone.id());
153-
System.out.printf("Description: %s%n", zone.description());
154-
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
155-
System.out.printf("Created: %s%n", formatter.format(new Date(zone.creationTimeMillis())));
156-
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers()));
147+
printZone(zone);
157148
}
158149
}
159150

@@ -210,7 +201,7 @@ public void run(Dns dns, String... args) {
210201
String ip = args[2];
211202
int ttl = 0;
212203
if (args.length > 3) {
213-
ttl = Integer.valueOf(args[3]);
204+
ttl = Integer.parseInt(args[3]);
214205
}
215206
DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A)
216207
.records(ImmutableList.of(ip))
@@ -220,18 +211,10 @@ public void run(Dns dns, String... args) {
220211
.delete(record)
221212
.build();
222213
changeRequest = dns.applyChangeRequest(zoneName, changeRequest);
223-
System.out.printf("The request for deleting A record %s for zone %s was successfully " +
224-
"submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
214+
System.out.printf("The request for deleting A record %s for zone %s was successfully "
215+
+ "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
225216
System.out.print("Waiting for deletion to happen...");
226-
while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) {
227-
System.out.print(".");
228-
try {
229-
Thread.sleep(500);
230-
} catch (InterruptedException e) {
231-
System.err.println("Thread was interrupted while waiting.");
232-
}
233-
changeRequest = dns.getChangeRequest(zoneName, changeRequest.id());
234-
}
217+
waitForChangeToFinish(dns, zoneName, changeRequest);
235218
System.out.printf("%nThe deletion has been completed.%n");
236219
}
237220

@@ -244,7 +227,7 @@ public String params() {
244227
public boolean check(String... args) {
245228
if (args.length == 4) {
246229
// to check that it can be parsed
247-
Integer.valueOf(args[3]);
230+
Integer.parseInt(args[3]);
248231
return true;
249232
} else {
250233
return args.length == 3;
@@ -265,28 +248,18 @@ public void run(Dns dns, String... args) {
265248
String ip = args[2];
266249
int ttl = 0;
267250
if (args.length > 3) {
268-
ttl = Integer.valueOf(args[3]);
251+
ttl = Integer.parseInt(args[3]);
269252
}
270253
DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A)
271254
.records(ImmutableList.of(ip))
272255
.ttl(ttl, TimeUnit.SECONDS)
273256
.build();
274-
ChangeRequest changeRequest = ChangeRequest.builder()
275-
.add(record)
276-
.build();
257+
ChangeRequest changeRequest = ChangeRequest.builder().add(record).build();
277258
changeRequest = dns.applyChangeRequest(zoneName, changeRequest);
278-
System.out.printf("The request for adding A record %s for zone %s was successfully " +
279-
"submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
280-
System.out.print("Waiting for deletion to happen...");
281-
while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) {
282-
System.out.print(".");
283-
try {
284-
Thread.sleep(500);
285-
} catch (InterruptedException e) {
286-
System.err.println("Thread was interrupted while waiting.");
287-
}
288-
changeRequest = dns.getChangeRequest(zoneName, changeRequest.id());
289-
}
259+
System.out.printf("The request for adding A record %s for zone %s was successfully "
260+
+ "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
261+
System.out.print("Waiting for addition to happen...");
262+
waitForChangeToFinish(dns, zoneName, changeRequest);
290263
System.out.printf("The addition has been completed.%n");
291264
}
292265

@@ -299,7 +272,7 @@ public String params() {
299272
public boolean check(String... args) {
300273
if (args.length == 4) {
301274
// to check that it can be parsed
302-
Integer.valueOf(args[3]);
275+
Integer.parseInt(args[3]);
303276
return true;
304277
} else {
305278
return args.length == 3;
@@ -342,8 +315,8 @@ public boolean check(String... args) {
342315
private static class ListChangesAction implements DnsAction {
343316

344317
/**
345-
* Lists all the changes for a given zone. Optionally, an order, "descending" or "ascending" can
346-
* be specified using the last parameter.
318+
* Lists all the changes for a given zone. Optionally, an order ("descending" or "ascending")
319+
* can be specified using the last parameter.
347320
*/
348321
@Override
349322
public void run(Dns dns, String... args) {
@@ -358,12 +331,11 @@ public void run(Dns dns, String... args) {
358331
}
359332
if (iterator.hasNext()) {
360333
System.out.printf("Change requests for zone %s:%n", zoneName);
361-
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
362334
while (iterator.hasNext()) {
363335
ChangeRequest change = iterator.next();
364336
System.out.printf("%nID: %s%n", change.id());
365337
System.out.printf("Status: %s%n", change.status());
366-
System.out.printf("Started: %s%n", formatter.format(change.startTimeMillis()));
338+
System.out.printf("Started: %s%n", FORMATTER.format(change.startTimeMillis()));
367339
System.out.printf("Deletions: %s%n", Joiner.on(", ").join(change.deletions()));
368340
System.out.printf("Additions: %s%n", Joiner.on(", ").join(change.additions()));
369341
}
@@ -408,7 +380,7 @@ public void run(Dns dns, String... args) {
408380

409381
@Override
410382
public boolean check(String... args) {
411-
if (args.length == 0) {
383+
if (args.length == 0 || args.length == 1) {
412384
return true;
413385
}
414386
if ("records".equals(args[1])) {
@@ -464,6 +436,29 @@ public boolean check(String... args) {
464436
ACTIONS.put("quota", new GetProjectAction());
465437
}
466438

439+
private static void printZone(Zone zone) {
440+
System.out.printf("%nName: %s%n", zone.name());
441+
System.out.printf("ID: %s%n", zone.id());
442+
System.out.printf("Description: %s%n", zone.description());
443+
System.out.printf("Created: %s%n", FORMATTER.format(new Date(zone.creationTimeMillis())));
444+
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers()));
445+
}
446+
447+
private static ChangeRequest waitForChangeToFinish(Dns dns, String zoneName,
448+
ChangeRequest request) {
449+
ChangeRequest current = request;
450+
while (current.status().equals(ChangeRequest.Status.PENDING)) {
451+
System.out.print(".");
452+
try {
453+
Thread.sleep(500);
454+
} catch (InterruptedException e) {
455+
System.err.println("Thread was interrupted while waiting.");
456+
}
457+
current = dns.getChangeRequest(zoneName, current.id());
458+
}
459+
return current;
460+
}
461+
467462
private static void printUsage() {
468463
StringBuilder actionAndParams = new StringBuilder();
469464
for (Map.Entry<String, DnsAction> entry : ACTIONS.entrySet()) {
@@ -510,12 +505,13 @@ public static void main(String... args) throws Exception {
510505
return;
511506
} catch (Exception ex) {
512507
System.out.println("Failed to parse request.");
508+
System.out.println("Expected: " + action.params());
513509
ex.printStackTrace();
514510
return;
515511
}
516512
if (valid) {
517513
DnsOptions.Builder optionsBuilder = DnsOptions.builder();
518-
if(projectId != null) {
514+
if (projectId != null) {
519515
optionsBuilder.projectId(projectId);
520516
}
521517
Dns dns = optionsBuilder.build().service();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
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+
/*
18+
* EDITING INSTRUCTIONS
19+
* This file is referenced in README's and javadoc. Any change to this file should be reflected in
20+
* the project's README's and package-info.java.
21+
*/
22+
23+
package com.google.gcloud.examples.dns.snippets;
24+
25+
import com.google.gcloud.dns.ChangeRequest;
26+
import com.google.gcloud.dns.Dns;
27+
import com.google.gcloud.dns.DnsOptions;
28+
import com.google.gcloud.dns.DnsRecord;
29+
import com.google.gcloud.dns.Zone;
30+
31+
import java.util.Iterator;
32+
import java.util.concurrent.TimeUnit;
33+
34+
/**
35+
* A snippet for Google Cloud DNS showing how to create a DNS records.
36+
*/
37+
public class CreateAndListDnsRecords {
38+
39+
public static void main(String... args) {
40+
// Create a service object.
41+
// The project ID and credentials will be inferred from the environment.
42+
Dns dns = DnsOptions.defaultInstance().service();
43+
44+
// Change this to a zone name that exists within your project
45+
String zoneName = "some-sample-zone";
46+
47+
// Get zone from the service
48+
Zone zone = dns.getZone(zoneName);
49+
50+
// Prepare a <i>www.<zone-domain>.</i> type A record with ttl of 24 hours
51+
String ip = "12.13.14.15";
52+
DnsRecord toCreate = DnsRecord.builder("www." + zone.dnsName(), DnsRecord.Type.A)
53+
.ttl(24, TimeUnit.HOURS)
54+
.addRecord(ip)
55+
.build();
56+
57+
// Make a change
58+
ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate);
59+
60+
// Verify a www.<zone-domain>. type A record does not exist yet.
61+
// If it does exist, we will overwrite it with our prepared record.
62+
Iterator<DnsRecord> recordIterator = zone.listDnsRecords().iterateAll();
63+
while (recordIterator.hasNext()) {
64+
DnsRecord current = recordIterator.next();
65+
if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) {
66+
changeBuilder.delete(current);
67+
}
68+
}
69+
70+
// Build and apply the change request to our zone
71+
zone.applyChangeRequest(changeBuilder.build());
72+
}
73+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* Copyright 2016 Google Inc. All Rights Reserved.
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+
/*
18+
* EDITING INSTRUCTIONS
19+
* This file is referenced in README's and javadoc. Any change to this file should be reflected in
20+
* the project's README's and package-info.java.
21+
*/
22+
23+
package com.google.gcloud.examples.dns.snippets;
24+
25+
import com.google.gcloud.dns.Dns;
26+
import com.google.gcloud.dns.DnsOptions;
27+
import com.google.gcloud.dns.Zone;
28+
import com.google.gcloud.dns.ZoneInfo;
29+
30+
import java.util.Iterator;
31+
32+
/**
33+
* A snippet for Google Cloud DNS showing how to create a zone and list all zones in the project.
34+
* You will need to change the {@code domainName} to a domain name, the ownership of which you
35+
* should verify with Google.
36+
*/
37+
public class CreateAndListZones {
38+
39+
public static void main(String... args) {
40+
// Create a service object
41+
// The project ID and credentials will be inferred from the environment.
42+
Dns dns = DnsOptions.defaultInstance().service();
43+
44+
// Create a zone metadata object
45+
String zoneName = "my_unique_zone"; // Change this zone name which is unique within your project
46+
String domainName = "someexampledomain.com."; // Change this to a domain which you own
47+
String description = "This is a gcloud-java-dns sample zone.";
48+
ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description);
49+
50+
// Create zone in Google Cloud DNS
51+
Zone createdZone = dns.create(zoneInfo);
52+
System.out.printf("Zone was created and assigned ID %s.%n", createdZone.id());
53+
54+
// Now list all the zones within this project
55+
Iterator<Zone> zoneIterator = dns.listZones().iterateAll();
56+
int counter = 1;
57+
while (zoneIterator.hasNext()) {
58+
System.out.printf("#%d.: %s%n%n", counter, zoneIterator.next().toString());
59+
counter++;
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)