Skip to content

Commit

Permalink
Reorganized snippets and fixed doc.
Browse files Browse the repository at this point in the history
  • Loading branch information
mderka committed Mar 15, 2016
1 parent cfdca14 commit 0ff712f
Show file tree
Hide file tree
Showing 7 changed files with 240 additions and 97 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ Example Applications
- Read more about using this application on the [`BigQueryExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/bigquery/BigQueryExample.html).
- [`Bookshelf`](https://github.com/GoogleCloudPlatform/getting-started-java/tree/master/bookshelf) - An App Engine app that manages a virtual bookshelf.
- This app uses `gcloud-java` to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service.
- [`DatastoreExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) - A simple command line interface for the Cloud Datastore
- [`DatastoreExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/datastore/DatastoreExample.java) - A simple command line interface for Cloud Datastore
- Read more about using this application on the [`DatastoreExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/datastore/DatastoreExample.html).
- [`DnsExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java) - A simple command line interface for the Cloud DNS
- [`DnsExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java) - A simple command line interface for Cloud DNS
- Read more about using this application on the [`DnsExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/dns/DnsExample.html).
- [`ResourceManagerExample`](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/resourcemanager/ResourceManagerExample.java) - A simple command line interface providing some of Cloud Resource Manager's functionality
- Read more about using this application on the [`ResourceManagerExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/resourcemanager/ResourceManagerExample.html).
Expand Down Expand Up @@ -233,7 +233,7 @@ Google Cloud DNS (Alpha)
Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
The first snippet shows how to create a zone resource. Complete source code can be found on
[CreateAndListZones.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java).
[CreateZone.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java).
```java
import com.google.gcloud.dns.Dns;
Expand All @@ -249,7 +249,7 @@ ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description);
Zone createdZone = dns.create(zoneInfo);
```
The second snippet shows how to create records inside a zone. The complete code can be found on [CreateAndListDnsRecords.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java).
The second snippet shows how to create records inside a zone. The complete code can be found on [CreateOrUpdateDnsRecords.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java).
```java
import com.google.gcloud.dns.ChangeRequest;
Expand Down Expand Up @@ -416,7 +416,7 @@ Apache 2.0 - See [LICENSE] for more information.
[dns-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/dns/package-summary.html
[cloud-dns-docs]: https://cloud.google.com/dns/docs
[cloud-dns-activation]: https://console.cloud.google.com/start/api?id=dns&_ga=1.63051695.1811492016.1457580760
[cloud-dns-activation]: https://console.cloud.google.com/start/api?id=dns
[cloud-pubsub]: https://cloud.google.com/pubsub/
[cloud-pubsub-docs]: https://cloud.google.com/pubsub/docs
Expand Down
197 changes: 123 additions & 74 deletions gcloud-java-dns/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ If you are using Maven, add this to your pom.xml file
<dependency>
<groupId>com.google.gcloud</groupId>
<artifactId>gcloud-java-dns</artifactId>
<version>0.1.4</version>
<version>0.1.5</version>
</dependency>
```
If you are using Gradle, add this to your dependencies
Expand Down Expand Up @@ -53,10 +53,7 @@ About Google Cloud DNS

[Google Cloud DNS][cloud-dns] is a scalable, reliable and managed authoritative Domain Name System
(DNS) service running on the same infrastructure as Google. It has low latency, high availability
and is a cost-effective way to make your applications and services available to your users. Cloud
DNS translates requests for domain names like www.google.com into IP addresses like 74.125.29.101.
Cloud DNS is programmable. You can easily publish and manage millions of DNS zones and records using
our simple user interface, command-line interface or API.
and is a cost-effective way to make your applications and services available to your users.

See the [Google Cloud DNS docs][dns-activate] for more details on how to activate
Cloud DNS for your project.
Expand All @@ -68,7 +65,7 @@ Getting Started
---------------
#### Prerequisites
For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/)
project with the DNS JSON API enabled. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en)
project with the DNS API enabled. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en)
to use Google Cloud DNS. [Follow these instructions](https://cloud.google.com/docs/authentication#preparation)
to get your project set up. You will also need to set up the local development environment by
[installing the Google Cloud SDK](https://cloud.google.com/sdk/) and running the following commands
Expand Down Expand Up @@ -96,47 +93,53 @@ For other authentication options, see the [Authentication](https://github.com/Go

#### Managing Zones
DNS records in `gcloud-java-dns` are managed inside containers called "zones". `ZoneInfo` is a class
which encapsulates metadata that describe a zone in Google Cloud DNS, but it cannot interact with
the Cloud DNS service on its own. `Zone`, a subclass of `ZoneInfo`, adds service-related
functionality over `ZoneInfo`. In this code snippet, we create a new zone in which we intend to
which encapsulates metadata that describe a zone in Google Cloud DNS. `Zone`, a subclass of `ZoneInfo`, adds service-related
functionality over `ZoneInfo`.

*Important: Zone must be unique to the project. If you choose a zone name that already
exists within your project, you'll get a helpful error message telling you to choose another name. In the code below,
replace "my_unique_zone" with a unique zone name. See more about naming rules [here](https://cloud.google.com/dns/api/v1/managedZones#name).*

In this code snippet, we create a new zone in which we intend to
manage DNS record for domain `someexampledomain.com.`

*Important: The service may require that you verify ownership of the domain for which you are creating a zone.
Hence, we recommend that you do so beforehand. You can verify ownership of
a domain name [here](https://www.google.com/webmasters/verification/home). Note that Cloud DNS
requires fully qualified domain names which must end with a period.*

Add the following imports at the top of your file:

```java
import com.google.gcloud.storage.Zone;
import com.google.gcloud.storage.ZoneInfo;
import com.google.gcloud.dns.Zone;
import com.google.gcloud.dns.ZoneInfo;
```

Then add the following code to create a zone.

*Important: Zone names within each project have to be unique. If you choose a zone name that already
exists, you'll get a helpful error message telling you to choose another name. In the code below,
replace "my_unique_zone" with a unique zone name. See more about naming rules [here](https://cloud.google.com/dns/api/v1/managedZones).*

*Important: The service may require that you verify ownership of the domain name that you are
creating a zone for. Hence, we recommend that you do so beforehand. You can verify ownership of
a domain name [here](https://www.google.com/webmasters/verification/home). Note that `gcloud-java`
works with fully qualified domain names which must end with a period.*

```java
// Create a zone metadata
// 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 zone = dns.create(zoneInfo);
Zone createdZone = dns.create(zoneInfo);
System.out.printf("Zone was created and assigned ID %s.%n", createdZone.id());
```

You now have an empty zone hosted in Google Cloud DNS which is ready to be populated with DNS
records for domain name `someexampledomain.com.` Upon creating the zone, the cloud service
automatically assigned a set of DNS servers to this zone which will be hosting the records, and
created the default required SOA and NS records for the domain inside this zone. You can read the
list of assigned DNS servers using accessor method `zone.nameServers()` and for instance print them
on the screen as follows. You will need to add `import com.google.gcloud.dns.DnsRecord` to your
source code.
automatically assigned a set of DNS servers to host records for this zone, and
created the required SOA and NS records for the domain. The following snippet reads and prints the list of assigned servers.
You will need to add the following import to your code:

```java
import com.google.gcloud.dns.DnsRecord
```

and proceed with:

```java
// Print assigned name servers
Expand All @@ -146,34 +149,63 @@ for(DnsRecord record : records) {
}
```

You can now instruct your domain registrar to [update the domain name servers] (https://cloud.google.com/dns/update-name-servers)
to these. As soon as this happens and the change propagates through cached values in DNS resolvers,
all the DNS queries will be directed and answered by the Google Cloud DNS service.
You can now instruct your domain registrar to [update your domain name servers] (https://cloud.google.com/dns/update-name-servers).
As soon as this happens and the change propagates through cached values in DNS resolvers,
all the DNS queries will be directed to and answered by the Google Cloud DNS service.

#### Creating DNS Records
Now that we have an zone, we should add some DNS records. The DNS records held within zones are
modified by so-called "change requests". In this example, we create and apply a change request to
Now that we have a zone, we can add some DNS records. The DNS records held within zones are
modified by "change requests". In this example, we create and apply a change request to
our zone that creates a DNS record of type A and points URL www.someexampledomain.com to
IP address 12.13.14.15. Start by adding `import com.google.gcloud.dns.ChangeRequest` and proceed
with:
IP address 12.13.14.15. Start by adding

```java
import com.google.gcloud.dns.ChangeRequest
```

and proceed with:

```java
// Prepare a www.someexampledomain.com. type A record with ttl of 24 hours
String ip = "12.13.14.15";
DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A)
.ttl(24, TimeUnit.HOURS)
.addRecord(ip)
.build();
.ttl(24, TimeUnit.HOURS)
.addRecord(ip)
.build();

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

// Build and apply the change request to our zone
ChangeRequest changeRequest = zone.applyChangeRequest(changeBuilder.build());
changeRequest = zone.applyChangeRequest();
```

The `addRecord` (and also `records`) function of `DnsRecord.Builder` accepts records in the form of
strings (and a list of strings respectively). The format of the strings (and the number of strings
in the list respectively) depends on the type of the DNS record to be added. More information on the
supported DNS record types and record formats can be found [here](https://cloud.google.com/dns/what-is-cloud-dns#supported_record_types).
The `addRecord` function of `DnsRecord.Builder` accepts records in the form of
strings. The format of the strings depends on the type of the DNS record to be added.
More information on the supported DNS record types and record formats can be found [here](https://cloud.google.com/dns/what-is-cloud-dns#supported_record_types).

If you already have a DNS record, Cloud DNS will return an error upon an attempt to create a duplicate of it.
You can modify the code above to create a DNS record or update it if it already exists by making the
following adjustment:

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

// Verify the 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());
```
You can find more information about changes in the [Cloud DNS documentation] (https://cloud.google.com/dns/what-is-cloud-dns#cloud_dns_api_concepts).

When the change request is applied, it is registered with the Cloud DNS service for processing. We
can wait for its completion as follows:
Expand All @@ -187,12 +219,12 @@ System.out.println("The change request has been applied.");
```

Change requests are applied atomically to all the assigned DNS servers at once. Note that when this
happens, it may still take a while for the change to be registered by the DNS cache resolvers in the
Internet. See more on this topic [here](https://cloud.google.com/dns/monitoring).
happens, it may still take a while for the change to be registered by the DNS cache resolvers.
See more on this topic [here](https://cloud.google.com/dns/monitoring).

#### Listing Zones and DNS Records
Suppose that you've added more zones and DNS records in them, and now you want to see what they are.
First, import the following class for easy iteration:
Suppose that you have added more zones and DNS records, and now you want to list them.
First, import the following:

```java
import java.util.Iterator;
Expand All @@ -203,9 +235,10 @@ Then add the following code to list all your zones and DNS records.
```java
// List all your zones
Iterator<Zone> projectZones = dns.listZones().iterateAll();
System.out.println("My zones:");
while (projectZones.hasNext()) {
System.out.println(projectZones.next());
int counter = 1;
while (zoneIterator.hasNext()) {
System.out.printf("#%d.: %s%n%n", counter, zoneIterator.next());
counter++;
}

// List the DNS records in a particular zone
Expand All @@ -229,44 +262,60 @@ while (changeIterator.hasNext()) {

#### Deleting Zones

If you no longer want to host a zone in Cloud DNS, you can delete it. However, you need to empty it
first by creating a change that deletes all such records. The only thing you should be careful about
is not to delete the default SOA and NS records for the zone.
If you no longer want to host a zone in Cloud DNS, you can delete it.
First, you need to empty the zone by deleting all its records except for the default SOA and NS records.

```java
// prepare change for deleting all records
List<DnsRecord.Type> defaultTypes = ImmutableList.of(DnsRecord.Type.SOA, DnsRecord.Type.NS);
Iterator<DnsRecord> recordIterator = zone.list().iterateAll();
List<DnsRecord> toDelete = new ArrayList<>();
// Make a change for deleting the records
ChangeRequest.Builder changeBuilder = ChangeRequest.builder();
while (recordIterator.hasNext()) {
DnsRecord record = recordIterator.next();
if(!defaultTypes.contains(record.type())) {
toDelete.add(record);
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);
}
}

if(!toDelete.isEmpty()) {
ChangeRequest deletion = Change.builder().deletions(toDelete).build();
deletion = zone.applyChangeRequest(deletion);

// wait for completion
while(!ChangeRequest.DONE.equals(deletion.status())) {
Thread.sleep(50L);
deletion = zone.getChangeRequest(deletion.id()); // get an update
// 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);
}
}

// now delete the zone
zone.delete();
// 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.");
}
```

#### Complete source code
#### Complete Source Code

We composed some of the aforementioned snippets into complete executable code samples. In
[CreateAndListZones.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java)
we create a zone and list all the zones in the project. In [CreateAndListDnsRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java)
[CreateZones.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java)
we create a zone. In [CreateOrUpdateDnsRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java)
we create a type A record for a zone, or update an existing type A record to a new IP address. We
also demonstrate how to list DNS records within a zone. Finally, in [DeleteZone.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java)
demonstrate how to list all zones in your project in [ListZones.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ListZones.java)
and how to list DNS records within a zone in [ListDnsRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ListDnsRecords.java).
Finally, in [DeleteZone.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java)
we list and delete all the records within a zone, and then delete the zone itself. The applications
assume that they are running on Compute Engine or from your own desktop. To run the example on App
Engine, simply move the code from the main method to your application's servlet class and change the
Expand Down
Loading

0 comments on commit 0ff712f

Please sign in to comment.