From 886a8bdf0885edcaf971bd6aca9de715727ae11c Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 2 Mar 2016 10:13:20 -0800 Subject: [PATCH 1/3] Added a DNS example and documentation. --- gcloud-java-examples/README.md | 19 +- .../google/gcloud/examples/DnsExample.java | 516 ++++++++++++++++++ gcloud-java/pom.xml | 5 + 3 files changed, 539 insertions(+), 1 deletion(-) create mode 100644 gcloud-java-examples/src/main/java/com/google/gcloud/examples/DnsExample.java diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md index 59fbca11e219..3807813b3df0 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,23 @@ 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. + 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.DnsExample" -Dexec.args="create some-sample-zone elaborateexample.com. description" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="get some-sample-zone" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="list" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="list some-sample-zone records" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.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.DnsExample" -Dexec.args="get some-sample-zone" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.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.DnsExample" -Dexec.args="list some-sample-zone changes ascending" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="delete some-sample-zone" + $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="quota" + ``` + * 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/DnsExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DnsExample.java new file mode 100644 index 000000000000..071ba59e0f7e --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DnsExample.java @@ -0,0 +1,516 @@ +/* + * 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; + +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.util.Arrays; +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, and creates and deletes DNS records of + * type A. + * + *

Steps needed for running the example:

    + *
  1. login using gcloud SDK - {@code gcloud auth login}.
  2. + *
  3. compile using maven - {@code mvn compile}
  4. + *
  5. 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
  6. + *
+ * + *

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,...) and can be used to + * demonstrate the usage. The remaining arguments are specific to the operation. See each action's + * run method for the specific interaction. + */ +public class DnsExample { + + private static final Map ACTIONS = new HashMap<>(); + + 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.builder(zoneName) + .dnsName(dnsName) + .description(description) + .build(); + 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:"); + System.out.println("Name\tID\tDNS Name\tCreated\tDesription"); + while (zoneIterator.hasNext()) { + Zone zone = zoneIterator.next(); + System.out.printf("%s\t%s\t%s\t%s\t%s%n", zone.name(), zone.id(), zone.dnsName(), + zone.creationTimeMillis(), zone.description()); + } + } 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 { + System.out.printf("Name: %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", zone.creationTimeMillis()); + System.out.printf("Name servers: %s%n", Joiner.on(",").join(zone.nameServers())); + } + } + + @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 probably 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. + */ + @Override + public void run(Dns dns, String... args) { + String zoneName = args[0]; + String recordName = args[1]; + String ip = args[2]; + DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) + .records(ImmutableList.of(ip)) + .build(); + if (args.length > 3) { + Integer ttl = Integer.valueOf(args[3]); + record = record.toBuilder().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()); + while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) { + 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 deletion has been completed.%n"); + } + + @Override + public String params() { + return " []"; + } + + @Override + public boolean check(String... args) { + if (args.length == 4) { + try { + Integer.valueOf(args[3]); + } catch (Exception ex) { + throw new IllegalArgumentException(ex); + } + 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. + */ + @Override + public void run(Dns dns, String... args) { + String zoneName = args[0]; + String recordName = args[1]; + String ip = args[2]; + DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) + .records(ImmutableList.of(ip)) + .build(); + if (args.length > 3) { + Integer ttl = Integer.valueOf(args[3]); + record = record.toBuilder().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()); + while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) { + 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 addition has been completed.%n"); + } + + @Override + public String params() { + return " []"; + } + + @Override + public boolean check(String... args) { + if (args.length == 4) { + try { + Integer.valueOf(args[3]); + } catch (Exception ex) { + throw new IllegalArgumentException(ex); + } + 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); + System.out.printf("Record name\tTTL\tRecords%n"); + while (iterator.hasNext()) { + DnsRecord record = iterator.next(); + System.out.printf("%s\t%s\t%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); + System.out.printf("ID\tStatus\tTimestamp%n"); + while (iterator.hasNext()) { + ChangeRequest change = iterator.next(); + System.out.printf("%s\t%s\t%s%n", change.id(), change.status(), change.startTimeMillis()); + System.out.printf("\tDeletions: %s%n", Joiner.on(",").join(change.deletions())); + System.out.printf("\tAdditions: %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) { + System.err.println(Arrays.asList(args)); + return args.length == 2 + || (args.length == 3 && ImmutableList.of("descending", "ascending").contains(args[2])); + } + } + + 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(); + System.out.printf("Project id: %s%nQuota:%n", dns.options().projectId()); + System.out.printf("\tZones: %d%n", project.quota().zones()); + System.out.printf("\tDNS records per zone: %d%n", project.quota().rrsetsPerZone()); + System.out.printf("\tRecord sets per DNS record: %d%n", + project.quota().resourceRecordsPerRrset()); + System.out.printf("\tAdditions per change: %d%n", project.quota().rrsetAdditionsPerChange()); + System.out.printf("\tDeletions per change: %d%n", project.quota().rrsetDeletionsPerChange()); + System.out.printf("\tTotal data size per change: %d%n", + project.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 printUsage() { + StringBuilder actionAndParams = new StringBuilder(); + for (Map.Entry entry : ACTIONS.entrySet()) { + actionAndParams.append('\t').append(System.lineSeparator()).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; + } + DnsOptions.Builder optionsBuilder = DnsOptions.builder(); + DnsAction action; + String actionName; + if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { + actionName = args[1]; + optionsBuilder.projectId(args[0]); + action = ACTIONS.get(args[1]); + args = Arrays.copyOfRange(args, 2, args.length); + } else { + actionName = args[0]; + action = ACTIONS.get(args[0]); + args = Arrays.copyOfRange(args, 1, args.length); + } + if (action == null) { + System.out.println("Unrecognized action."); + printUsage(); + return; + } + Dns dns = optionsBuilder.build().service(); + 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."); + ex.printStackTrace(); + return; + } + if (valid) { + action.run(dns, args); + } else { + System.out.println("Invalid input for action '" + actionName + "'"); + System.out.println("Expected: " + action.params()); + } + } +} diff --git a/gcloud-java/pom.xml b/gcloud-java/pom.xml index adfa716fe27b..b7dfd3f12e8f 100644 --- a/gcloud-java/pom.xml +++ b/gcloud-java/pom.xml @@ -38,5 +38,10 @@ gcloud-java-storage ${project.version} + + ${project.groupId} + gcloud-java-dns + ${project.version} + From 8e82f351520d9e8768a2818545f99a6f41c7bf2b Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 9 Mar 2016 16:40:56 -0800 Subject: [PATCH 2/3] Fixed based on first round of comments: - moved to correct package - added printouts while waiting for changes - removed tab-based formatting - removed NumberFormatException hiding - some minor code refactoring - extended documentation - switched builder() to of() construct in DNS example --- gcloud-java-examples/README.md | 21 ++- .../gcloud/examples/{ => dns}/DnsExample.java | 132 ++++++++++-------- gcloud-java/pom.xml | 6 +- 3 files changed, 85 insertions(+), 74 deletions(-) rename gcloud-java-examples/src/main/java/com/google/gcloud/examples/{ => dns}/DnsExample.java (78%) diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md index 3807813b3df0..73d613c94e27 100644 --- a/gcloud-java-examples/README.md +++ b/gcloud-java-examples/README.md @@ -74,18 +74,17 @@ 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. - Note that the example creates and deletes dns records of type A only. Operations with other record types are not implemented in the example. + You will need to replace the domain name `elaborateexample.com` with your own domain name with verified ownership. + 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.DnsExample" -Dexec.args="create some-sample-zone elaborateexample.com. description" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="get some-sample-zone" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="list" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="list some-sample-zone records" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.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.DnsExample" -Dexec.args="get some-sample-zone" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.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.DnsExample" -Dexec.args="list some-sample-zone changes ascending" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="delete some-sample-zone" - $mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.DnsExample" -Dexec.args="quota" + 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`. diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DnsExample.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java similarity index 78% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/DnsExample.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java index 071ba59e0f7e..2061f4931cab 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/DnsExample.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.examples; +package com.google.gcloud.examples.dns; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; @@ -26,7 +26,10 @@ 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; @@ -38,7 +41,8 @@ *

This example creates, deletes, gets, and lists zones, and creates and deletes DNS records of * type A. * - *

Steps needed for running the example:

    + *

    Steps needed for running the example: + *

      *
    1. login using gcloud SDK - {@code gcloud auth login}.
    2. *
    3. compile using maven - {@code mvn compile}
    4. *
    5. run using maven - {@code mvn exec:java @@ -50,13 +54,13 @@ * list [ [changes [descending | ascending] | records]] | * add-record | * delete-record [] | - * quota
    6. + * quota} *
    * *

    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,...) and can be used to - * demonstrate the usage. The remaining arguments are specific to the operation. See each action's - * run method for the specific interaction. + * 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. */ public class DnsExample { @@ -80,10 +84,7 @@ public void run(Dns dns, String... args) { String zoneName = args[0]; String dnsName = args[1]; String description = args[2]; - ZoneInfo zoneInfo = ZoneInfo.builder(zoneName) - .dnsName(dnsName) - .description(description) - .build(); + 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()); @@ -110,11 +111,14 @@ public void run(Dns dns, String... args) { Iterator zoneIterator = dns.listZones().iterateAll(); if (zoneIterator.hasNext()) { System.out.println("The project contains the following zones:"); - System.out.println("Name\tID\tDNS Name\tCreated\tDesription"); + DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); while (zoneIterator.hasNext()) { Zone zone = zoneIterator.next(); - System.out.printf("%s\t%s\t%s\t%s\t%s%n", zone.name(), zone.id(), zone.dnsName(), - zone.creationTimeMillis(), zone.description()); + 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())); } } else { System.out.println("Project contains no zones."); @@ -147,8 +151,9 @@ public void run(Dns dns, String... args) { System.out.printf("Name: %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", zone.creationTimeMillis()); - System.out.printf("Name servers: %s%n", Joiner.on(",").join(zone.nameServers())); + 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())); } } @@ -175,7 +180,7 @@ public void run(Dns dns, String... args) { if (deleted) { System.out.printf("Zone %s was deleted.%n", zoneName); } else { - System.out.printf("Zone %s was NOT deleted. It probably does not exist.%n", zoneName); + System.out.printf("Zone %s was NOT deleted. It does not exist.%n", zoneName); } } @@ -195,27 +200,31 @@ 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. + * 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.valueOf(args[3]); + } DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) .records(ImmutableList.of(ip)) + .ttl(ttl, TimeUnit.SECONDS) .build(); - if (args.length > 3) { - Integer ttl = Integer.valueOf(args[3]); - record = record.toBuilder().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..."); while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) { + System.out.print("."); try { Thread.sleep(500); } catch (InterruptedException e) { @@ -223,7 +232,7 @@ record = record.toBuilder().ttl(ttl, TimeUnit.SECONDS).build(); } changeRequest = dns.getChangeRequest(zoneName, changeRequest.id()); } - System.out.printf("The deletion has been completed.%n"); + System.out.printf("%nThe deletion has been completed.%n"); } @Override @@ -234,11 +243,8 @@ public String params() { @Override public boolean check(String... args) { if (args.length == 4) { - try { - Integer.valueOf(args[3]); - } catch (Exception ex) { - throw new IllegalArgumentException(ex); - } + // to check that it can be parsed + Integer.valueOf(args[3]); return true; } else { return args.length == 3; @@ -249,27 +255,31 @@ public boolean check(String... args) { private static class AddDnsRecordAction implements DnsAction { /** - * Adds a DNS record of type A. The last parameter is ttl and is not required. + * 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.valueOf(args[3]); + } DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) .records(ImmutableList.of(ip)) + .ttl(ttl, TimeUnit.SECONDS) .build(); - if (args.length > 3) { - Integer ttl = Integer.valueOf(args[3]); - record = record.toBuilder().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 deletion to happen..."); while (changeRequest.status().equals(ChangeRequest.Status.PENDING)) { + System.out.print("."); try { Thread.sleep(500); } catch (InterruptedException e) { @@ -288,11 +298,8 @@ public String params() { @Override public boolean check(String... args) { if (args.length == 4) { - try { - Integer.valueOf(args[3]); - } catch (Exception ex) { - throw new IllegalArgumentException(ex); - } + // to check that it can be parsed + Integer.valueOf(args[3]); return true; } else { return args.length == 3; @@ -311,11 +318,10 @@ public void run(Dns dns, String... args) { Iterator iterator = dns.listDnsRecords(zoneName).iterateAll(); if (iterator.hasNext()) { System.out.printf("DNS records for zone %s:%n", zoneName); - System.out.printf("Record name\tTTL\tRecords%n"); while (iterator.hasNext()) { DnsRecord record = iterator.next(); - System.out.printf("%s\t%s\t%s%n", record.name(), record.ttl(), - Joiner.on(",").join(record.records())); + 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); @@ -352,12 +358,14 @@ public void run(Dns dns, String... args) { } if (iterator.hasNext()) { System.out.printf("Change requests for zone %s:%n", zoneName); - System.out.printf("ID\tStatus\tTimestamp%n"); + DateFormat formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); while (iterator.hasNext()) { ChangeRequest change = iterator.next(); - System.out.printf("%s\t%s\t%s%n", change.id(), change.status(), change.startTimeMillis()); - System.out.printf("\tDeletions: %s%n", Joiner.on(",").join(change.deletions())); - System.out.printf("\tAdditions: %s%n", Joiner.on(",").join(change.additions())); + 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); @@ -371,9 +379,9 @@ public String params() { @Override public boolean check(String... args) { - System.err.println(Arrays.asList(args)); return args.length == 2 - || (args.length == 3 && ImmutableList.of("descending", "ascending").contains(args[2])); + || (args.length == 3 + && ImmutableList.of("descending", "ascending").contains(args[2].toLowerCase())); } } @@ -400,7 +408,7 @@ public void run(Dns dns, String... args) { @Override public boolean check(String... args) { - if (args.length == 0 || args.length == 1) { + if (args.length == 0) { return true; } if ("records".equals(args[1])) { @@ -423,15 +431,16 @@ 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", project.quota().zones()); - System.out.printf("\tDNS records per zone: %d%n", project.quota().rrsetsPerZone()); + 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", - project.quota().resourceRecordsPerRrset()); - System.out.printf("\tAdditions per change: %d%n", project.quota().rrsetAdditionsPerChange()); - System.out.printf("\tDeletions per change: %d%n", project.quota().rrsetDeletionsPerChange()); + 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", - project.quota().totalRrdataSizePerChange()); + quota.totalRrdataSizePerChange()); } @Override @@ -458,7 +467,7 @@ public boolean check(String... args) { private static void printUsage() { StringBuilder actionAndParams = new StringBuilder(); for (Map.Entry entry : ACTIONS.entrySet()) { - actionAndParams.append('\t').append(System.lineSeparator()).append(entry.getKey()); + actionAndParams.append(System.lineSeparator()).append('\t').append(entry.getKey()); String param = entry.getValue().params(); if (param != null && !param.isEmpty()) { actionAndParams.append(' ').append(param); @@ -474,25 +483,23 @@ public static void main(String... args) throws Exception { printUsage(); return; } - DnsOptions.Builder optionsBuilder = DnsOptions.builder(); + String projectId = null; DnsAction action; String actionName; if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { actionName = args[1]; - optionsBuilder.projectId(args[0]); - action = ACTIONS.get(args[1]); + projectId = args[0]; args = Arrays.copyOfRange(args, 2, args.length); } else { actionName = args[0]; - action = ACTIONS.get(args[0]); args = Arrays.copyOfRange(args, 1, args.length); } + action = ACTIONS.get(actionName); if (action == null) { - System.out.println("Unrecognized action."); + System.out.printf("Unrecognized action %s.%n", actionName); printUsage(); return; } - Dns dns = optionsBuilder.build().service(); boolean valid = false; try { valid = action.check(args); @@ -507,6 +514,11 @@ public static void main(String... args) throws Exception { 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 + "'"); diff --git a/gcloud-java/pom.xml b/gcloud-java/pom.xml index b7dfd3f12e8f..03d2b6600ba3 100644 --- a/gcloud-java/pom.xml +++ b/gcloud-java/pom.xml @@ -30,17 +30,17 @@ ${project.groupId} - gcloud-java-resourcemanager + gcloud-java-dns ${project.version} ${project.groupId} - gcloud-java-storage + gcloud-java-resourcemanager ${project.version} ${project.groupId} - gcloud-java-dns + gcloud-java-storage ${project.version} From da877d86f55a46b93ee2cb5295e38707b65e93c2 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 10 Mar 2016 09:40:03 -0800 Subject: [PATCH 3/3] Added code snippets for DNS. Also extended example doc and added links. Refactored zone print. --- .../com/google/gcloud/dns/DnsOptions.java | 8 ++ gcloud-java-examples/README.md | 2 +- .../gcloud/examples/dns/DnsExample.java | 108 +++++++++--------- .../dns/snippets/CreateAndListDnsRecords.java | 73 ++++++++++++ .../dns/snippets/CreateAndListZones.java | 62 ++++++++++ .../examples/dns/snippets/DeleteZone.java | 88 ++++++++++++++ 6 files changed, 284 insertions(+), 57 deletions(-) create mode 100644 gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java create mode 100644 gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java create mode 100644 gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java 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 73d613c94e27..5e11fd2b0cb7 100644 --- a/gcloud-java-examples/README.md +++ b/gcloud-java-examples/README.md @@ -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" 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 index 2061f4931cab..1b6ba8f179da 100644 --- 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 @@ -38,8 +38,8 @@ /** * An example of using Google Cloud DNS. * - *

    This example creates, deletes, gets, and lists zones, and creates and deletes DNS records of - * type A. + *

    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: *

      @@ -57,14 +57,16 @@ * quota} *
    * - *

    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. + *

    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); @@ -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) { @@ -111,14 +113,8 @@ public void run(Dns dns, String... args) { Iterator 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."); @@ -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); } } @@ -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)) @@ -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"); } @@ -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; @@ -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"); } @@ -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; @@ -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) { @@ -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())); } @@ -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])) { @@ -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 entry : ACTIONS.entrySet()) { @@ -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(); 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."); + } + } +}