Skip to content

Commit

Permalink
Added code snippets for DNS.
Browse files Browse the repository at this point in the history
Also extended example doc and added links.
Refactored zone print.
  • Loading branch information
mderka committed Mar 15, 2016
1 parent 8e82f35 commit da877d8
Show file tree
Hide file tree
Showing 6 changed files with 284 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ public static Builder builder() {
return new Builder();
}

/**
* Creates a default instance of {@code DnsOptions} with the project ID and credentials inferred
* from the environment.
*/
public static DnsOptions defaultInstance() {
return builder().build();
}

@Override
public boolean equals(Object obj) {
return obj instanceof DnsOptions && baseEquals((DnsOptions) obj);
Expand Down
2 changes: 1 addition & 1 deletion gcloud-java-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ To run examples from your command line:
* Here's an example run of `DnsExample`.
Note that you have to enable the Google Cloud DNS API on the [Google Developers Console][developers-console] before running the following commands.
You will need to replace the domain name `elaborateexample.com` with your own domain name with verified ownership.
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).
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.
```
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="create some-sample-zone elaborateexample.com. description"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
/**
* An example of using Google Cloud DNS.
*
* <p>This example creates, deletes, gets, and lists zones, and creates and deletes DNS records of
* type A.
* <p>This example creates, deletes, gets, and lists zones. It also creates and deletes DNS records
* of type A, and lists DNS records.
*
* <p>Steps needed for running the example:
* <ol>
Expand All @@ -57,14 +57,16 @@
* quota}</li>
* </ol>
*
* <p>The first parameter is an optional {@code project_id} (logged-in project will be used if not
* supplied). Second parameter is a DNS operation (list, delete, create,...). The remaining
* arguments are specific to the operation. See each action's run method for the specific
* interaction.
* <p>The first parameter is an optional {@code project_id}. The project specified in the Google
* Cloud SDK configuration (see {@code gcloud config list}) will be used if the project ID is not
* supplied. The second parameter is a DNS operation (list, delete, create, ...). The remaining
* arguments are specific to the operation. See each action's {@code run} method for the specific
* arguments.
*/
public class DnsExample {

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

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

/**
* Creates a zone with the provided name, dns name and description (in this order).
* Creates a zone with the provided name, DNS name and description (in this order).
*/
@Override
public void run(Dns dns, String... args) {
Expand Down Expand Up @@ -111,14 +113,8 @@ public void run(Dns dns, String... args) {
Iterator<Zone> zoneIterator = dns.listZones().iterateAll();
if (zoneIterator.hasNext()) {
System.out.println("The project contains the following zones:");
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
while (zoneIterator.hasNext()) {
Zone zone = zoneIterator.next();
System.out.printf("%nName: %s%n", zone.name());
System.out.printf("ID: %s%n", zone.id());
System.out.printf("Description: %s%n", zone.description());
System.out.printf("Created: %s%n", formatter.format(new Date(zone.creationTimeMillis())));
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers()));
printZone(zoneIterator.next());
}
} else {
System.out.println("Project contains no zones.");
Expand Down Expand Up @@ -148,12 +144,7 @@ public void run(Dns dns, String... args) {
if (zone == null) {
System.out.printf("No zone with name '%s' exists.%n", zoneName);
} else {
System.out.printf("Name: %s%n", zone.name());
System.out.printf("ID: %s%n", zone.id());
System.out.printf("Description: %s%n", zone.description());
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
System.out.printf("Created: %s%n", formatter.format(new Date(zone.creationTimeMillis())));
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers()));
printZone(zone);
}
}

Expand Down Expand Up @@ -210,7 +201,7 @@ public void run(Dns dns, String... args) {
String ip = args[2];
int ttl = 0;
if (args.length > 3) {
ttl = Integer.valueOf(args[3]);
ttl = Integer.parseInt(args[3]);
}
DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A)
.records(ImmutableList.of(ip))
Expand All @@ -220,18 +211,10 @@ public void run(Dns dns, String... args) {
.delete(record)
.build();
changeRequest = dns.applyChangeRequest(zoneName, changeRequest);
System.out.printf("The request for deleting A record %s for zone %s was successfully " +
"submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
System.out.printf("The request for deleting A record %s for zone %s was successfully "
+ "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
System.out.print("Waiting for deletion to happen...");
while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) {
System.out.print(".");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.err.println("Thread was interrupted while waiting.");
}
changeRequest = dns.getChangeRequest(zoneName, changeRequest.id());
}
waitForChangeToFinish(dns, zoneName, changeRequest);
System.out.printf("%nThe deletion has been completed.%n");
}

Expand All @@ -244,7 +227,7 @@ public String params() {
public boolean check(String... args) {
if (args.length == 4) {
// to check that it can be parsed
Integer.valueOf(args[3]);
Integer.parseInt(args[3]);
return true;
} else {
return args.length == 3;
Expand All @@ -265,28 +248,18 @@ public void run(Dns dns, String... args) {
String ip = args[2];
int ttl = 0;
if (args.length > 3) {
ttl = Integer.valueOf(args[3]);
ttl = Integer.parseInt(args[3]);
}
DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A)
.records(ImmutableList.of(ip))
.ttl(ttl, TimeUnit.SECONDS)
.build();
ChangeRequest changeRequest = ChangeRequest.builder()
.add(record)
.build();
ChangeRequest changeRequest = ChangeRequest.builder().add(record).build();
changeRequest = dns.applyChangeRequest(zoneName, changeRequest);
System.out.printf("The request for adding A record %s for zone %s was successfully " +
"submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
System.out.print("Waiting for deletion to happen...");
while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) {
System.out.print(".");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.err.println("Thread was interrupted while waiting.");
}
changeRequest = dns.getChangeRequest(zoneName, changeRequest.id());
}
System.out.printf("The request for adding A record %s for zone %s was successfully "
+ "submitted and assigned ID %s.%n", recordName, zoneName, changeRequest.id());
System.out.print("Waiting for addition to happen...");
waitForChangeToFinish(dns, zoneName, changeRequest);
System.out.printf("The addition has been completed.%n");
}

Expand All @@ -299,7 +272,7 @@ public String params() {
public boolean check(String... args) {
if (args.length == 4) {
// to check that it can be parsed
Integer.valueOf(args[3]);
Integer.parseInt(args[3]);
return true;
} else {
return args.length == 3;
Expand Down Expand Up @@ -342,8 +315,8 @@ public boolean check(String... args) {
private static class ListChangesAction implements DnsAction {

/**
* Lists all the changes for a given zone. Optionally, an order, "descending" or "ascending" can
* be specified using the last parameter.
* Lists all the changes for a given zone. Optionally, an order ("descending" or "ascending")
* can be specified using the last parameter.
*/
@Override
public void run(Dns dns, String... args) {
Expand All @@ -358,12 +331,11 @@ public void run(Dns dns, String... args) {
}
if (iterator.hasNext()) {
System.out.printf("Change requests for zone %s:%n", zoneName);
DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
while (iterator.hasNext()) {
ChangeRequest change = iterator.next();
System.out.printf("%nID: %s%n", change.id());
System.out.printf("Status: %s%n", change.status());
System.out.printf("Started: %s%n", formatter.format(change.startTimeMillis()));
System.out.printf("Started: %s%n", FORMATTER.format(change.startTimeMillis()));
System.out.printf("Deletions: %s%n", Joiner.on(", ").join(change.deletions()));
System.out.printf("Additions: %s%n", Joiner.on(", ").join(change.additions()));
}
Expand Down Expand Up @@ -408,7 +380,7 @@ public void run(Dns dns, String... args) {

@Override
public boolean check(String... args) {
if (args.length == 0) {
if (args.length == 0 || args.length == 1) {
return true;
}
if ("records".equals(args[1])) {
Expand Down Expand Up @@ -464,6 +436,29 @@ public boolean check(String... args) {
ACTIONS.put("quota", new GetProjectAction());
}

private static void printZone(Zone zone) {
System.out.printf("%nName: %s%n", zone.name());
System.out.printf("ID: %s%n", zone.id());
System.out.printf("Description: %s%n", zone.description());
System.out.printf("Created: %s%n", FORMATTER.format(new Date(zone.creationTimeMillis())));
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers()));
}

private static ChangeRequest waitForChangeToFinish(Dns dns, String zoneName,
ChangeRequest request) {
ChangeRequest current = request;
while (current.status().equals(ChangeRequest.Status.PENDING)) {
System.out.print(".");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.err.println("Thread was interrupted while waiting.");
}
current = dns.getChangeRequest(zoneName, current.id());
}
return current;
}

private static void printUsage() {
StringBuilder actionAndParams = new StringBuilder();
for (Map.Entry<String, DnsAction> entry : ACTIONS.entrySet()) {
Expand Down Expand Up @@ -510,12 +505,13 @@ public static void main(String... args) throws Exception {
return;
} catch (Exception ex) {
System.out.println("Failed to parse request.");
System.out.println("Expected: " + action.params());
ex.printStackTrace();
return;
}
if (valid) {
DnsOptions.Builder optionsBuilder = DnsOptions.builder();
if(projectId != null) {
if (projectId != null) {
optionsBuilder.projectId(projectId);
}
Dns dns = optionsBuilder.build().service();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/

/*
* EDITING INSTRUCTIONS
* This file is referenced in README's and javadoc. Any change to this file should be reflected in
* the project's README's and package-info.java.
*/

package com.google.gcloud.examples.dns.snippets;

import com.google.gcloud.dns.ChangeRequest;
import com.google.gcloud.dns.Dns;
import com.google.gcloud.dns.DnsOptions;
import com.google.gcloud.dns.DnsRecord;
import com.google.gcloud.dns.Zone;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
* A snippet for Google Cloud DNS showing how to create a DNS records.
*/
public class CreateAndListDnsRecords {

public static void main(String... args) {
// Create a service object.
// The project ID and credentials will be inferred from the environment.
Dns dns = DnsOptions.defaultInstance().service();

// Change this to a zone name that exists within your project
String zoneName = "some-sample-zone";

// Get zone from the service
Zone zone = dns.getZone(zoneName);

// Prepare a <i>www.<zone-domain>.</i> type A record with ttl of 24 hours
String ip = "12.13.14.15";
DnsRecord toCreate = DnsRecord.builder("www." + zone.dnsName(), DnsRecord.Type.A)
.ttl(24, TimeUnit.HOURS)
.addRecord(ip)
.build();

// Make a change
ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate);

// Verify a www.<zone-domain>. type A record does not exist yet.
// If it does exist, we will overwrite it with our prepared record.
Iterator<DnsRecord> recordIterator = zone.listDnsRecords().iterateAll();
while (recordIterator.hasNext()) {
DnsRecord current = recordIterator.next();
if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) {
changeBuilder.delete(current);
}
}

// Build and apply the change request to our zone
zone.applyChangeRequest(changeBuilder.build());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/

/*
* EDITING INSTRUCTIONS
* This file is referenced in README's and javadoc. Any change to this file should be reflected in
* the project's README's and package-info.java.
*/

package com.google.gcloud.examples.dns.snippets;

import com.google.gcloud.dns.Dns;
import com.google.gcloud.dns.DnsOptions;
import com.google.gcloud.dns.Zone;
import com.google.gcloud.dns.ZoneInfo;

import java.util.Iterator;

/**
* A snippet for Google Cloud DNS showing how to create a zone and list all zones in the project.
* You will need to change the {@code domainName} to a domain name, the ownership of which you
* should verify with Google.
*/
public class CreateAndListZones {

public static void main(String... args) {
// Create a service object
// The project ID and credentials will be inferred from the environment.
Dns dns = DnsOptions.defaultInstance().service();

// Create a zone metadata object
String zoneName = "my_unique_zone"; // Change this zone name which is unique within your project
String domainName = "someexampledomain.com."; // Change this to a domain which you own
String description = "This is a gcloud-java-dns sample zone.";
ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description);

// Create zone in Google Cloud DNS
Zone createdZone = dns.create(zoneInfo);
System.out.printf("Zone was created and assigned ID %s.%n", createdZone.id());

// Now list all the zones within this project
Iterator<Zone> zoneIterator = dns.listZones().iterateAll();
int counter = 1;
while (zoneIterator.hasNext()) {
System.out.printf("#%d.: %s%n%n", counter, zoneIterator.next().toString());
counter++;
}
}
}
Loading

0 comments on commit da877d8

Please # to comment.