diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java
index db922b42a3cb..541e7a6c6ea7 100644
--- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java
+++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java
@@ -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);
diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md
index 59fbca11e219..5e11fd2b0cb7 100644
--- a/gcloud-java-examples/README.md
+++ b/gcloud-java-examples/README.md
@@ -63,7 +63,7 @@ To run examples from your command line:
```
* Here's an example run of `DatastoreExample`.
-
+
Be sure to change the placeholder project ID "your-project-id" with your own project ID. Also note that you have to enable the Google Cloud Datastore API on the [Google Developers Console][developers-console] before running the following commands.
```
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.datastore.DatastoreExample" -Dexec.args="your-project-id my_name add my\ comment"
@@ -71,6 +71,22 @@ To run examples from your command line:
mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.datastore.DatastoreExample" -Dexec.args="your-project-id my_name delete"
```
+ * 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] (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"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="list"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="list some-sample-zone records"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="add-record some-sample-zone www.elaborateexample.com. 12.13.14.15 69"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="get some-sample-zone"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="delete-record some-sample-zone www.elaborateexample.com. 12.13.14.15 69"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="list some-sample-zone changes ascending"
+ mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample" -Dexec.args="delete some-sample-zone"
+ ```
+
* Here's an example run of `ResourceManagerExample`.
Be sure to change the placeholder project ID "your-project-id" with your own globally unique project ID.
diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java
new file mode 100644
index 000000000000..1b6ba8f179da
--- /dev/null
+++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java
@@ -0,0 +1,524 @@
+/*
+ * 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.
+ */
+
+package com.google.gcloud.examples.dns;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+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.ProjectInfo;
+import com.google.gcloud.dns.Zone;
+import com.google.gcloud.dns.ZoneInfo;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * An example of using Google Cloud DNS.
+ *
+ *
This example creates, deletes, gets, and lists zones. It also creates and deletes DNS records
+ * of type A, and lists DNS records.
+ *
+ *
Steps needed for running the example:
+ *
+ * - login using gcloud SDK - {@code gcloud auth login}.
+ * - compile using maven - {@code mvn compile}
+ * - run using maven - {@code mvn exec:java
+ * -Dexec.mainClass="com.google.gcloud.examples.dns.DnsExample"
+ * -Dexec.args="[]
+ * create |
+ * get |
+ * delete |
+ * list [ [changes [descending | ascending] | records]] |
+ * add-record |
+ * delete-record [] |
+ * quota}
+ *
+ *
+ * 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 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);
+
+ String params();
+
+ boolean check(String... args);
+ }
+
+ private static class CreateZoneAction implements DnsAction {
+
+ /**
+ * Creates a zone with the provided name, DNS name and description (in this order).
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ String dnsName = args[1];
+ String description = args[2];
+ ZoneInfo zoneInfo = ZoneInfo.of(zoneName, dnsName, description);
+ Zone zone = dns.create(zoneInfo);
+ System.out.printf("Successfully created zone with name %s which was assigned ID %s.%n",
+ zone.name(), zone.id());
+ }
+
+ @Override
+ public String params() {
+ return " ";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 3;
+ }
+ }
+
+ private static class ListZonesAction implements DnsAction {
+
+ /**
+ * Lists all zones within the project.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ Iterator zoneIterator = dns.listZones().iterateAll();
+ if (zoneIterator.hasNext()) {
+ System.out.println("The project contains the following zones:");
+ while (zoneIterator.hasNext()) {
+ printZone(zoneIterator.next());
+ }
+ } else {
+ System.out.println("Project contains no zones.");
+ }
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 0;
+ }
+ }
+
+ private static class GetZoneAction implements DnsAction {
+
+ /**
+ * Gets details about a zone with the given name.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ Zone zone = dns.getZone(zoneName);
+ if (zone == null) {
+ System.out.printf("No zone with name '%s' exists.%n", zoneName);
+ } else {
+ printZone(zone);
+ }
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 1;
+ }
+ }
+
+ private static class DeleteZoneAction implements DnsAction {
+
+ /**
+ * Deletes a zone with the given name.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ boolean deleted = dns.delete(zoneName);
+ if (deleted) {
+ System.out.printf("Zone %s was deleted.%n", zoneName);
+ } else {
+ System.out.printf("Zone %s was NOT deleted. It does not exist.%n", zoneName);
+ }
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 1;
+ }
+
+ }
+
+ private static class DeleteDnsRecordAction implements DnsAction {
+
+ /**
+ * Deletes a DNS record of type A from the given zone. The last parameter is ttl and it is not
+ * required. If ttl is not provided, a default value of 0 is used. The service requires a
+ * precise match (including ttl) for deleting a record.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ String recordName = args[1];
+ String ip = args[2];
+ int ttl = 0;
+ if (args.length > 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()
+ .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.print("Waiting for deletion to happen...");
+ waitForChangeToFinish(dns, zoneName, changeRequest);
+ System.out.printf("%nThe deletion has been completed.%n");
+ }
+
+ @Override
+ public String params() {
+ return " []";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ if (args.length == 4) {
+ // to check that it can be parsed
+ Integer.parseInt(args[3]);
+ return true;
+ } else {
+ return args.length == 3;
+ }
+ }
+ }
+
+ private static class AddDnsRecordAction implements DnsAction {
+
+ /**
+ * Adds a DNS record of type A. The last parameter is ttl and is not required. If ttl is not
+ * provided, a default value of 0 will be used.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ String recordName = args[1];
+ String ip = args[2];
+ int ttl = 0;
+ if (args.length > 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 = 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 addition to happen...");
+ waitForChangeToFinish(dns, zoneName, changeRequest);
+ System.out.printf("The addition has been completed.%n");
+ }
+
+ @Override
+ public String params() {
+ return " []";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ if (args.length == 4) {
+ // to check that it can be parsed
+ Integer.parseInt(args[3]);
+ return true;
+ } else {
+ return args.length == 3;
+ }
+ }
+ }
+
+ private static class ListDnsRecordsAction implements DnsAction {
+
+ /**
+ * Lists all the DNS records in the given zone.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ Iterator iterator = dns.listDnsRecords(zoneName).iterateAll();
+ if (iterator.hasNext()) {
+ System.out.printf("DNS records for zone %s:%n", zoneName);
+ while (iterator.hasNext()) {
+ DnsRecord record = iterator.next();
+ System.out.printf("%nRecord name: %s%nTTL: %s%nRecords: %s%n", record.name(),
+ record.ttl(), Joiner.on(", ").join(record.records()));
+ }
+ } else {
+ System.out.printf("Zone %s has no DNS records.%n", zoneName);
+ }
+ }
+
+ @Override
+ public String params() {
+ return " records";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 2;
+ }
+ }
+
+ 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.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ String zoneName = args[0];
+ Iterator iterator;
+ if (args.length > 2) {
+ Dns.SortingOrder sortOrder = Dns.SortingOrder.valueOf(args[2].toUpperCase());
+ iterator = dns.listChangeRequests(zoneName,
+ Dns.ChangeRequestListOption.sortOrder(sortOrder)).iterateAll();
+ } else {
+ iterator = dns.listChangeRequests(zoneName).iterateAll();
+ }
+ if (iterator.hasNext()) {
+ System.out.printf("Change requests for zone %s:%n", zoneName);
+ 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("Deletions: %s%n", Joiner.on(", ").join(change.deletions()));
+ System.out.printf("Additions: %s%n", Joiner.on(", ").join(change.additions()));
+ }
+ } else {
+ System.out.printf("Zone %s has no change requests.%n", zoneName);
+ }
+ }
+
+ @Override
+ public String params() {
+ return " changes [descending | ascending]";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 2
+ || (args.length == 3
+ && ImmutableList.of("descending", "ascending").contains(args[2].toLowerCase()));
+ }
+ }
+
+ private static class ListAction implements DnsAction {
+
+ /**
+ * Invokes a list action. If no parameter is provided, lists all zones. If zone name is the only
+ * parameter provided, lists both DNS records and changes. Otherwise, invokes listing changes or
+ * zones based on the parameter provided.
+ */
+ @Override
+ public void run(Dns dns, String... args) {
+ if (args.length == 0) {
+ new ListZonesAction().run(dns);
+ } else {
+ if (args.length == 1 || "records".equals(args[1])) {
+ new ListDnsRecordsAction().run(dns, args);
+ }
+ if (args.length == 1 || "changes".equals(args[1])) {
+ new ListChangesAction().run(dns, args);
+ }
+ }
+ }
+
+ @Override
+ public boolean check(String... args) {
+ if (args.length == 0 || args.length == 1) {
+ return true;
+ }
+ if ("records".equals(args[1])) {
+ return new ListDnsRecordsAction().check(args);
+ }
+ if ("changes".equals(args[1])) {
+ return new ListChangesAction().check(args);
+ }
+ return false;
+ }
+
+ @Override
+ public String params() {
+ return "[ [changes [descending | ascending] | records]]";
+ }
+ }
+
+ private static class GetProjectAction implements DnsAction {
+
+ @Override
+ public void run(Dns dns, String... args) {
+ ProjectInfo project = dns.getProject();
+ ProjectInfo.Quota quota = project.quota();
+ System.out.printf("Project id: %s%nQuota:%n", dns.options().projectId());
+ System.out.printf("\tZones: %d%n", quota.zones());
+ System.out.printf("\tDNS records per zone: %d%n", quota.rrsetsPerZone());
+ System.out.printf("\tRecord sets per DNS record: %d%n",
+ quota.resourceRecordsPerRrset());
+ System.out.printf("\tAdditions per change: %d%n", quota.rrsetAdditionsPerChange());
+ System.out.printf("\tDeletions per change: %d%n", quota.rrsetDeletionsPerChange());
+ System.out.printf("\tTotal data size per change: %d%n",
+ quota.totalRrdataSizePerChange());
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+
+ @Override
+ public boolean check(String... args) {
+ return args.length == 0;
+ }
+ }
+
+ static {
+ ACTIONS.put("create", new CreateZoneAction());
+ ACTIONS.put("delete", new DeleteZoneAction());
+ ACTIONS.put("get", new GetZoneAction());
+ ACTIONS.put("list", new ListAction());
+ ACTIONS.put("add-record", new AddDnsRecordAction());
+ ACTIONS.put("delete-record", new DeleteDnsRecordAction());
+ 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 entry : ACTIONS.entrySet()) {
+ actionAndParams.append(System.lineSeparator()).append('\t').append(entry.getKey());
+ String param = entry.getValue().params();
+ if (param != null && !param.isEmpty()) {
+ actionAndParams.append(' ').append(param);
+ }
+ }
+ System.out.printf("Usage: %s [] operation *%s%n",
+ DnsExample.class.getSimpleName(), actionAndParams);
+ }
+
+ public static void main(String... args) throws Exception {
+ if (args.length < 1) {
+ System.out.println("Missing required action");
+ printUsage();
+ return;
+ }
+ String projectId = null;
+ DnsAction action;
+ String actionName;
+ if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
+ actionName = args[1];
+ projectId = args[0];
+ args = Arrays.copyOfRange(args, 2, args.length);
+ } else {
+ actionName = args[0];
+ args = Arrays.copyOfRange(args, 1, args.length);
+ }
+ action = ACTIONS.get(actionName);
+ if (action == null) {
+ System.out.printf("Unrecognized action %s.%n", actionName);
+ printUsage();
+ return;
+ }
+ boolean valid = false;
+ try {
+ valid = action.check(args);
+ } catch (NumberFormatException ex) {
+ System.out.println("Invalid input for action '" + actionName + "'.");
+ System.out.println("Ttl must be an integer.");
+ System.out.println("Expected: " + action.params());
+ 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) {
+ optionsBuilder.projectId(projectId);
+ }
+ Dns dns = optionsBuilder.build().service();
+ action.run(dns, args);
+ } else {
+ System.out.println("Invalid input for action '" + actionName + "'");
+ System.out.println("Expected: " + action.params());
+ }
+ }
+}
diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java
new file mode 100644
index 000000000000..1e47a12fed02
--- /dev/null
+++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java
@@ -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 www.. 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.. type A record does not exist yet.
+ // If it does exist, we will overwrite it with our prepared record.
+ Iterator 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());
+ }
+}
diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java
new file mode 100644
index 000000000000..21fdba2b7449
--- /dev/null
+++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java
@@ -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 zoneIterator = dns.listZones().iterateAll();
+ int counter = 1;
+ while (zoneIterator.hasNext()) {
+ System.out.printf("#%d.: %s%n%n", counter, zoneIterator.next().toString());
+ counter++;
+ }
+ }
+}
diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java
new file mode 100644
index 000000000000..667a0d89e6ab
--- /dev/null
+++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java
@@ -0,0 +1,88 @@
+/*
+ * 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 java.util.Iterator;
+
+/**
+ * A snippet for Google Cloud DNS showing how to delete a zone. It also shows how to list and delete
+ * DNS records.
+ */
+public class DeleteZone {
+
+ 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 and that you want to delete.
+ String zoneName = "some-sample-zone";
+
+ // Get iterator for the existing records which have to be deleted before deleting the zone
+ Iterator recordIterator = dns.listDnsRecords(zoneName).iterateAll();
+
+ // Make a change for deleting the records
+ ChangeRequest.Builder changeBuilder = ChangeRequest.builder();
+ while (recordIterator.hasNext()) {
+ DnsRecord current = recordIterator.next();
+ // SOA and NS records cannot be deleted
+ if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) {
+ changeBuilder.delete(current);
+ }
+ }
+
+ // Build and apply the change request to our zone if it contains records to delete
+ ChangeRequest changeRequest = changeBuilder.build();
+ if (!changeRequest.deletions().isEmpty()) {
+ changeRequest = dns.applyChangeRequest(zoneName, changeRequest);
+
+ // Wait for change to finish, but save data traffic by transferring only ID and status
+ Dns.ChangeRequestOption option =
+ Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS);
+ while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) {
+ System.out.println("Waiting for change to complete. Going to sleep for 500ms...");
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ System.err.println("The thread was interrupted while waiting for change request to be "
+ + "processed.");
+ }
+ // Update the change, but fetch only change ID and status
+ changeRequest = dns.getChangeRequest(zoneName, changeRequest.id(), option);
+ }
+ }
+
+ // Delete the zone
+ boolean result = dns.delete(zoneName);
+ if (result) {
+ System.out.println("Zone was deleted.");
+ } else {
+ System.out.println("Zone was not deleted because it does not exist.");
+ }
+ }
+}
diff --git a/gcloud-java/pom.xml b/gcloud-java/pom.xml
index adfa716fe27b..03d2b6600ba3 100644
--- a/gcloud-java/pom.xml
+++ b/gcloud-java/pom.xml
@@ -28,6 +28,11 @@
gcloud-java-datastore
${project.version}
+
+ ${project.groupId}
+ gcloud-java-dns
+ ${project.version}
+
${project.groupId}
gcloud-java-resourcemanager