From 2bf4925cb3fa8fa782b78de164e3a841bf5fdf4f Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 15 Jan 2016 17:54:12 -0800 Subject: [PATCH 01/74] Initial project for Google Cloud DNS in gcloud-java --- gcloud-java-dns/pom.xml | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 gcloud-java-dns/pom.xml diff --git a/gcloud-java-dns/pom.xml b/gcloud-java-dns/pom.xml new file mode 100644 index 000000000000..55d720bc0a36 --- /dev/null +++ b/gcloud-java-dns/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + com.google.gcloud + gcloud-java-dns + jar + GCloud Java DNS + + Java idiomatic client for Google Cloud DNS. + + + com.google.gcloud + gcloud-java-pom + 0.1.3-SNAPSHOT + + + gcloud-java-dns + + + + ${project.groupId} + gcloud-java-core + ${project.version} + + + com.google.apis + google-api-services-dns + v1-rev7-1.21.0 + compile + + + com.google.guava + guava-jdk5 + + + com.google.api-client + google-api-client + + + + + junit + junit + 4.12 + test + + + org.easymock + easymock + 3.3 + test + + + From fe4e137fce65882465ca0e092761e080f366fece Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 15 Jan 2016 17:56:24 -0800 Subject: [PATCH 02/74] Added DnsRecord as a part of the basic data model. ManagedZoneInfo is to be completed and it is included only as it is required as a builder parameter. This class will change in the near future. --- .../java/com/google/gcloud/dns/DnsRecord.java | 254 ++++++++++++++++++ .../google/gcloud/dns/ManagedZoneInfo.java | 44 +++ .../com/google/gcloud/dns/DnsRecordTest.java | 94 +++++++ 3 files changed, 392 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java new file mode 100644 index 000000000000..8abf335969f8 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -0,0 +1,254 @@ +/* + * 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.dns; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.collect.ImmutableList; + +import java.util.LinkedList; +import java.util.List; + +/** + * A class that represents Google Cloud DNS record set. + * + *

+ * A unit of data that will be returned by the DNS servers. + * + * @see Google + * Cloud DNS documentation + */ +public class DnsRecord { + + private String name; + private List rrdatas = new LinkedList<>(); + private Integer ttl = 86400; // the default ttl of 24 hours + private DnsRecordType type; + private String parentName; + private Long parentId; + + /** + * A private constructor. Obtain an instance using {@link DnsRecord#Builder}. + */ + private DnsRecord() { + } + + DnsRecord(Builder builder) { + this.name = builder.name; + this.rrdatas = ImmutableList.copyOf(builder.rrdatas); + this.ttl = builder.ttl; + this.type = builder.type; + this.parentName = builder.parentName; + this.parentId = builder.parentId; + } + + /** + * Enum for the DNS record types supported by Cloud DNS. + * + *

+ * Google Cloud DNS currently supports records of type A, AAAA, CNAME, MX + * NAPTR, NS, PTR, SOA, SPF, SRV, TXT. + * + * @see + * Cloud + * DNS supported record types + */ + public enum DnsRecordType { + A("A"), + AAAA("AAAA"), + CNAME("CNAME"), + MX("MX"), + NAPTR("NAPTR"), + NS("NS"), + PTR("PTR"), + SOA("SOA"), + SPF("SPF"), + SRV("SRV"), + TXT("TXT"); + + private final String type; + + private DnsRecordType(String type) { + this.type = type; + } + } + + public static class Builder { + + private List rrdatas = new LinkedList<>(); + private String name; + private Integer ttl = 86400; // default ttl of 24 hours + private DnsRecordType type; + private String parentName; + private Long parentId; + + private Builder() { + } + + /** + * Creates a builder and pre-populates attributes with the values from the + * provided DnsRecord instance. + */ + public Builder(DnsRecord record) { + this.name = record.name; + this.ttl = record.ttl; + this.type = record.type; + this.parentId = record.parentId; + this.parentName = record.parentName; + this.rrdatas.addAll(record.rrdatas); + } + + /** + * Adds a record to the record set. + * + *

+ * The records should be as defined in RFC 1035 (section 5) and RFC 1034 + * (section 3.6.1). Examples of records are available in + * Cloud + * DNS documentation. + */ + public Builder add(String record) { + this.rrdatas.add(checkNotNull(record)); + return this; + } + + /** + * Sets name for this DNS record set. For example, www.example.com. + */ + public Builder name(String name) { + this.name = checkNotNull(name); + return this; + } + + /** + * Sets the number of seconds that this record can be cached by resolvers. + * This number must be non-negative. + * + * @param ttl A non-negative number of seconds + */ + public Builder ttl(int ttl) { + // change only if + if (ttl < 0) { + throw new IllegalArgumentException( + "TTL cannot be negative. The supplied value was " + ttl + "." + ); + } + this.ttl = ttl; + return this; + } + + /** + * The identifier of a supported record type, for example, A, AAAA, MX, TXT, + * and so on. + */ + public Builder type(DnsRecordType type) { + this.type = checkNotNull(type); + return this; + } + + /** + * Builds the DNS record. + */ + public DnsRecord build() { + return new DnsRecord(this); + } + + /** + * Sets references to the managed zone that this DNS record belongs to. + */ + public Builder managedZone(ManagedZoneInfo parent) { + checkNotNull(parent); + this.parentId = parent.id(); + this.parentName = parent.name(); + return this; + } + } + + /** + * Creates a builder pre-populated with the attribute values of this instance. + */ + public Builder toBuilder() { + return new Builder(this); + } + + /** + * Creates an empty builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Get user assigned name of this DNS record. + * + * TODO: is this field mandatory? + */ + public String name() { + return name; + } + + /** + * Returns a list of DNS record stored in this record set. + */ + public List rrdatas() { + return rrdatas; + } + + /** + * Returns the number of seconds that this ResourceRecordSet can be cached by + * resolvers. + * + *

+ * This number is provided by the user. If this values is not set, we use + * default of 86400. + */ + public Integer ttl() { + return ttl; + } + + /** + * Returns the type of this DNS record. + */ + public DnsRecordType type() { + return type; + } + + /** + * Returns name of the managed zone that this record belongs to. + * + *

+ * The name of the managed zone is provided by the user when the managed zone + * is created. It is unique within a project. If this DNS record is not + * associated with a managed zone, this returns null. + */ + public String parentName() { + return parentName; + } + + /** + * Returns name of the managed zone that this record belongs to. + * + *

+ * The id of the managed zone is determined by the server when the managed + * zone is created. It is a read only value. If this DNS record is not + * associated with a managed zone, or if the id of the managed zone was not + * loaded from the cloud service, this returns null. + */ + public Long parentId() { + return parentId; + } + +} diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java new file mode 100644 index 000000000000..003854a91918 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java @@ -0,0 +1,44 @@ +/* + * 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.dns; + +/** + * TODO: Implement. + * TODO: Add documentation. + */ +public class ManagedZoneInfo { + + private final String name; + private final Long id; + + public String name() { + throw new UnsupportedOperationException("Not implemented yet."); + // TODO: Implement + } + + public Long id() { + return id; + // TODO: Implement + } + + private ManagedZoneInfo() { + name = null; + id = null; + throw new UnsupportedOperationException("Not implemented yet"); + // TODO: Implement + } + +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java new file mode 100644 index 000000000000..0709ca3bf0e4 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -0,0 +1,94 @@ +/* + * 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.dns; + +import org.easymock.EasyMock; + +import org.junit.Test; +import org.junit.Before; + +import static org.junit.Assert.*; + +public class DnsRecordTest { + + private static final String NAME = "example.com."; + private static final Integer TTL = 3600; + private static final DnsRecord.DnsRecordType TYPE = DnsRecord.DnsRecordType.AAAA; + private static final ManagedZoneInfo MANAGED_ZONE_INFO_MOCK + = EasyMock.createMock(ManagedZoneInfo.class); + private static final Long PARENT_ID = 12L; + private static final String PARENT_NAME = "name"; + static { + EasyMock.expect(MANAGED_ZONE_INFO_MOCK.id()).andReturn(PARENT_ID); + EasyMock.expect(MANAGED_ZONE_INFO_MOCK.name()).andReturn(PARENT_NAME); + EasyMock.replay(MANAGED_ZONE_INFO_MOCK); + } + private static final DnsRecord RECORD = DnsRecord.builder() + .name(NAME) + .ttl(TTL) + .managedZone(MANAGED_ZONE_INFO_MOCK) + .build(); + private static final Integer DEFAULT_TTL = 86400; + + @Test + public void testDefaultDnsRecord() { + DnsRecord record = DnsRecord.builder().build(); + assertEquals(DEFAULT_TTL, record.ttl()); + assertEquals(0, record.rrdatas().size()); + } + + @Test + public void testBuilder() { + + assertEquals(NAME, RECORD.name()); + assertEquals(TTL, RECORD.ttl()); + + assertEquals(PARENT_ID, RECORD.parentId()); // this was never assigned + assertEquals(PARENT_NAME, RECORD.parentName()); + assertEquals(0, RECORD.rrdatas().size()); + // verify that one can add records to the record set + String testingRecord = "Testing record"; + String anotherTestingRecord = "Another record 123"; + DnsRecord anotherRecord = RECORD.toBuilder() + .add(testingRecord) + .add(anotherTestingRecord) + .build(); + assertEquals(2, anotherRecord.rrdatas().size()); + assertTrue(anotherRecord.rrdatas().contains(testingRecord)); + assertTrue(anotherRecord.rrdatas().contains(anotherTestingRecord)); + } + + @Test + public void testValidTtl() { + try { + DnsRecord.builder().ttl(-1); + fail("A negative value is not acceptable for ttl."); + } catch (IllegalArgumentException e) { + // ok + } + try { + DnsRecord.builder().ttl(0); + } catch (IllegalArgumentException e) { + fail("0 is a valid value."); + } + try { + DnsRecord.builder().ttl(Integer.MAX_VALUE); + } catch (Exception e) { + fail("Large numbers should be ok too."); + } + } + +} From f652277e166b7d3cb3f248e0dafd92ea063c0caf Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 19 Jan 2016 15:37:51 -0800 Subject: [PATCH 03/74] Implemented comments by @mziccard --- .../java/com/google/gcloud/dns/DnsRecord.java | 188 ++++++++++-------- .../google/gcloud/dns/ManagedZoneInfo.java | 10 +- .../com/google/gcloud/dns/DnsRecordTest.java | 82 +++++--- 3 files changed, 165 insertions(+), 115 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 8abf335969f8..56da63dc5fe3 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -15,35 +15,45 @@ */ package com.google.gcloud.dns; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; +import java.io.Serializable; + import java.util.LinkedList; import java.util.List; +import java.util.Objects; /** * A class that represents Google Cloud DNS record set. * - *

- * A unit of data that will be returned by the DNS servers. + *

A unit of data that will be returned by the DNS servers. * - * @see Google - * Cloud DNS documentation + * @see Google Cloud DNS + * documentation */ -public class DnsRecord { +public class DnsRecord implements Serializable { - private String name; - private List rrdatas = new LinkedList<>(); - private Integer ttl = 86400; // the default ttl of 24 hours - private DnsRecordType type; - private String parentName; - private Long parentId; + private static final long serialVersionUID = 2016011914302204L; + private final String name; + private final List rrdatas; + private final Integer ttl; + private final DnsRecordType type; + private final String zoneName; + private final Long zoneId; /** * A private constructor. Obtain an instance using {@link DnsRecord#Builder}. */ private DnsRecord() { + this.name = null; + this.rrdatas = null; + this.ttl = null; + this.type = null; + this.zoneName = null; + this.zoneId = null; } DnsRecord(Builder builder) { @@ -51,74 +61,64 @@ private DnsRecord() { this.rrdatas = ImmutableList.copyOf(builder.rrdatas); this.ttl = builder.ttl; this.type = builder.type; - this.parentName = builder.parentName; - this.parentId = builder.parentId; + this.zoneName = builder.zoneName; + this.zoneId = builder.zoneId; } /** * Enum for the DNS record types supported by Cloud DNS. * - *

- * Google Cloud DNS currently supports records of type A, AAAA, CNAME, MX - * NAPTR, NS, PTR, SOA, SPF, SRV, TXT. + *

Google Cloud DNS currently supports records of type A, AAAA, CNAME, MX NAPTR, NS, PTR, SOA, + * SPF, SRV, TXT. * - * @see - * Cloud - * DNS supported record types + * @see Cloud DNS + * supported record types */ public enum DnsRecordType { - A("A"), - AAAA("AAAA"), - CNAME("CNAME"), - MX("MX"), - NAPTR("NAPTR"), - NS("NS"), - PTR("PTR"), - SOA("SOA"), - SPF("SPF"), - SRV("SRV"), - TXT("TXT"); - - private final String type; - - private DnsRecordType(String type) { - this.type = type; - } + A, + AAAA, + CNAME, + MX, + NAPTR, + NS, + PTR, + SOA, + SPF, + SRV, + TXT; } public static class Builder { private List rrdatas = new LinkedList<>(); private String name; - private Integer ttl = 86400; // default ttl of 24 hours + private Integer ttl; private DnsRecordType type; - private String parentName; - private Long parentId; + private String zoneName; + private Long zoneId; private Builder() { } /** - * Creates a builder and pre-populates attributes with the values from the - * provided DnsRecord instance. + * Creates a builder and pre-populates attributes with the values from the provided DnsRecord + * instance. */ public Builder(DnsRecord record) { this.name = record.name; this.ttl = record.ttl; this.type = record.type; - this.parentId = record.parentId; - this.parentName = record.parentName; + this.zoneId = record.zoneId; + this.zoneName = record.zoneName; this.rrdatas.addAll(record.rrdatas); } /** - * Adds a record to the record set. + * Adds a record to the record set. The records should be as defined in RFC 1035 (section 5) and + * RFC 1034 (section 3.6.1). Examples of records are available in Google DNS documentation. * - *

- * The records should be as defined in RFC 1035 (section 5) and RFC 1034 - * (section 3.6.1). Examples of records are available in - * Cloud - * DNS documentation. + * @see Google + * DNS documentation . */ public Builder add(String record) { this.rrdatas.add(checkNotNull(record)); @@ -134,25 +134,19 @@ public Builder name(String name) { } /** - * Sets the number of seconds that this record can be cached by resolvers. - * This number must be non-negative. + * Sets the number of seconds that this record can be cached by resolvers. This number must be + * non-negative. * * @param ttl A non-negative number of seconds */ public Builder ttl(int ttl) { - // change only if - if (ttl < 0) { - throw new IllegalArgumentException( - "TTL cannot be negative. The supplied value was " + ttl + "." - ); - } + checkArgument(ttl >= 0, "TTL cannot be negative. The supplied value was " + ttl + "."); this.ttl = ttl; return this; } /** - * The identifier of a supported record type, for example, A, AAAA, MX, TXT, - * and so on. + * The identifier of a supported record type, for example, A, AAAA, MX, TXT, and so on. */ public Builder type(DnsRecordType type) { this.type = checkNotNull(type); @@ -171,8 +165,8 @@ public DnsRecord build() { */ public Builder managedZone(ManagedZoneInfo parent) { checkNotNull(parent); - this.parentId = parent.id(); - this.parentName = parent.name(); + this.zoneId = parent.id(); + this.zoneName = parent.name(); return this; } } @@ -192,9 +186,7 @@ public static Builder builder() { } /** - * Get user assigned name of this DNS record. - * - * TODO: is this field mandatory? + * Get the mandatory user assigned name of this DNS record. */ public String name() { return name; @@ -204,16 +196,12 @@ public String name() { * Returns a list of DNS record stored in this record set. */ public List rrdatas() { - return rrdatas; + return ImmutableList.copyOf(rrdatas); } /** - * Returns the number of seconds that this ResourceRecordSet can be cached by - * resolvers. - * - *

- * This number is provided by the user. If this values is not set, we use - * default of 86400. + * Returns the number of seconds that this ResourceRecordSet can be cached by resolvers. This + * number is provided by the user. */ public Integer ttl() { return ttl; @@ -227,28 +215,56 @@ public DnsRecordType type() { } /** - * Returns name of the managed zone that this record belongs to. - * - *

- * The name of the managed zone is provided by the user when the managed zone - * is created. It is unique within a project. If this DNS record is not - * associated with a managed zone, this returns null. + * Returns name of the managed zone that this record belongs to. The name of the managed zone is + * provided by the user when the managed zone is created. It is unique within a project. If this + * DNS record is not associated with a managed zone, this returns null. */ - public String parentName() { - return parentName; + public String zoneName() { + return zoneName; } /** * Returns name of the managed zone that this record belongs to. * - *

- * The id of the managed zone is determined by the server when the managed - * zone is created. It is a read only value. If this DNS record is not - * associated with a managed zone, or if the id of the managed zone was not - * loaded from the cloud service, this returns null. + *

The id of the managed zone is determined by the server when the managed zone is created. It + * is a read only value. If this DNS record is not associated with a managed zone, or if the id of + * the managed zone was not loaded from the cloud service, this returns null. */ - public Long parentId() { - return parentId; + public Long zoneId() { + return zoneId; + } + + @Override + public int hashCode() { + return Objects.hash(name, rrdatas, ttl, type, zoneName, zoneId); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof DnsRecord) { + DnsRecord other = (DnsRecord) obj; + return zoneId == other.zoneId() + && zoneName == other.zoneName + && this.toRRSet().equals(other.toRRSet()); + } + return false; + } + + com.google.api.services.dns.model.ResourceRecordSet toRRSet() { + com.google.api.services.dns.model.ResourceRecordSet rrset = + new com.google.api.services.dns.model.ResourceRecordSet(); + rrset.setName(name); + rrset.setRrdatas(this.rrdatas()); + rrset.setTtl(ttl); + rrset.setType(type == null ? null : type.name()); + return rrset; + } + + @Override + public String toString() { + return "DnsRecord{" + "name=" + name + ", rrdatas=" + rrdatas + + ", ttl=" + ttl + ", type=" + type + ", zoneName=" + + zoneName + ", zoneId=" + zoneId + '}'; } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java index 003854a91918..d5ed8351dc34 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java @@ -16,8 +16,8 @@ package com.google.gcloud.dns; /** - * TODO: Implement. - * TODO: Add documentation. + * todo(mderka): Implement. + * todo(mderka): Add documentation. */ public class ManagedZoneInfo { @@ -26,19 +26,19 @@ public class ManagedZoneInfo { public String name() { throw new UnsupportedOperationException("Not implemented yet."); - // TODO: Implement + // todo(mderka): Implement } public Long id() { return id; - // TODO: Implement + // todo(mderka): Implement } private ManagedZoneInfo() { name = null; id = null; throw new UnsupportedOperationException("Not implemented yet"); - // TODO: Implement + // todo(mderka): Implement } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 0709ca3bf0e4..55c72d794e87 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -15,38 +15,42 @@ */ package com.google.gcloud.dns; -import org.easymock.EasyMock; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.Assert.assertNotEquals; +import org.junit.BeforeClass; import org.junit.Test; -import org.junit.Before; -import static org.junit.Assert.*; +import org.easymock.EasyMock; + public class DnsRecordTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; private static final DnsRecord.DnsRecordType TYPE = DnsRecord.DnsRecordType.AAAA; - private static final ManagedZoneInfo MANAGED_ZONE_INFO_MOCK - = EasyMock.createMock(ManagedZoneInfo.class); - private static final Long PARENT_ID = 12L; - private static final String PARENT_NAME = "name"; + private static final ManagedZoneInfo MANAGED_ZONE_INFO_MOCK = + EasyMock.createMock(ManagedZoneInfo.class); + private static final Long ZONE_ID = 12L; + private static final String ZONE_NAME = "name"; + static { - EasyMock.expect(MANAGED_ZONE_INFO_MOCK.id()).andReturn(PARENT_ID); - EasyMock.expect(MANAGED_ZONE_INFO_MOCK.name()).andReturn(PARENT_NAME); + EasyMock.expect(MANAGED_ZONE_INFO_MOCK.id()).andReturn(ZONE_ID); + EasyMock.expect(MANAGED_ZONE_INFO_MOCK.name()).andReturn(ZONE_NAME); EasyMock.replay(MANAGED_ZONE_INFO_MOCK); } + private static final DnsRecord RECORD = DnsRecord.builder() .name(NAME) .ttl(TTL) .managedZone(MANAGED_ZONE_INFO_MOCK) .build(); - private static final Integer DEFAULT_TTL = 86400; @Test public void testDefaultDnsRecord() { DnsRecord record = DnsRecord.builder().build(); - assertEquals(DEFAULT_TTL, record.ttl()); assertEquals(0, record.rrdatas().size()); } @@ -56,8 +60,8 @@ public void testBuilder() { assertEquals(NAME, RECORD.name()); assertEquals(TTL, RECORD.ttl()); - assertEquals(PARENT_ID, RECORD.parentId()); // this was never assigned - assertEquals(PARENT_NAME, RECORD.parentName()); + assertEquals(ZONE_ID, RECORD.zoneId()); // this was never assigned + assertEquals(ZONE_NAME, RECORD.zoneName()); assertEquals(0, RECORD.rrdatas().size()); // verify that one can add records to the record set String testingRecord = "Testing record"; @@ -77,18 +81,48 @@ public void testValidTtl() { DnsRecord.builder().ttl(-1); fail("A negative value is not acceptable for ttl."); } catch (IllegalArgumentException e) { - // ok - } - try { - DnsRecord.builder().ttl(0); - } catch (IllegalArgumentException e) { - fail("0 is a valid value."); - } - try { - DnsRecord.builder().ttl(Integer.MAX_VALUE); - } catch (Exception e) { - fail("Large numbers should be ok too."); + // expected } + DnsRecord.builder().ttl(0); + DnsRecord.builder().ttl(Integer.MAX_VALUE); + } + + @Test + public void testEqualsAndNotEquals() { + DnsRecord clone = RECORD.toBuilder().build(); + assertEquals(clone, RECORD); + clone = RECORD.toBuilder().add("another record").build(); + final String differentName = "totally different name"; + clone = RECORD.toBuilder().name(differentName).build(); + assertNotEquals(clone, RECORD); + clone = RECORD.toBuilder().ttl(RECORD.ttl() + 1).build(); + assertNotEquals(clone, RECORD); + clone = RECORD.toBuilder().type(DnsRecord.DnsRecordType.TXT).build(); + assertNotEquals(clone, RECORD); + ManagedZoneInfo anotherMock = EasyMock.createMock(ManagedZoneInfo.class); + EasyMock.expect(anotherMock.id()).andReturn(ZONE_ID + 1); + EasyMock.expect(anotherMock.name()).andReturn(ZONE_NAME + "more text"); + EasyMock.replay(anotherMock); + clone = RECORD.toBuilder().managedZone(anotherMock).build(); + assertNotEquals(clone, RECORD); + } + + @Test + public void testSameHashCodeOnEquals() { + int hash = RECORD.hashCode(); + DnsRecord clone = RECORD.toBuilder().build(); + assertEquals(clone.hashCode(), hash); + } + + @Test + public void testDifferentHashCodeOnDifferent() { + int hash = RECORD.hashCode(); + final String differentName = "totally different name"; + DnsRecord clone = RECORD.toBuilder().name(differentName).build(); + assertNotEquals(differentName, RECORD.name()); + assertNotEquals(clone.hashCode(), hash); + DnsRecord anotherClone = RECORD.toBuilder().add("another record").build(); + assertNotEquals(anotherClone.hashCode(), hash); } } From b29945fd1fd920571d115b746185dfef36d2a0ab Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 20 Jan 2016 11:14:09 -0800 Subject: [PATCH 04/74] Second round of comments from @mziccard --- .../java/com/google/gcloud/dns/DnsRecord.java | 68 +++++++++------- .../com/google/gcloud/dns/DnsRecordTest.java | 78 ++++++++++--------- 2 files changed, 80 insertions(+), 66 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 56da63dc5fe3..91278fa2a1e7 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -18,6 +18,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import java.io.Serializable; @@ -29,7 +30,7 @@ /** * A class that represents Google Cloud DNS record set. * - *

A unit of data that will be returned by the DNS servers. + *

A unit of data that will be returned by the DNS servers. * * @see Google Cloud DNS * documentation @@ -44,9 +45,6 @@ public class DnsRecord implements Serializable { private final String zoneName; private final Long zoneId; - /** - * A private constructor. Obtain an instance using {@link DnsRecord#Builder}. - */ private DnsRecord() { this.name = null; this.rrdatas = null; @@ -68,7 +66,7 @@ private DnsRecord() { /** * Enum for the DNS record types supported by Cloud DNS. * - *

Google Cloud DNS currently supports records of type A, AAAA, CNAME, MX NAPTR, NS, PTR, SOA, + *

Google Cloud DNS currently supports records of type A, AAAA, CNAME, MX NAPTR, NS, PTR, SOA, * SPF, SRV, TXT. * * @see Cloud DNS @@ -85,7 +83,7 @@ public enum DnsRecordType { SOA, SPF, SRV, - TXT; + TXT } public static class Builder { @@ -162,13 +160,23 @@ public DnsRecord build() { /** * Sets references to the managed zone that this DNS record belongs to. + * + * todo(mderka): consider if this method is needed; may not be possible when listing records */ - public Builder managedZone(ManagedZoneInfo parent) { + Builder managedZone(ManagedZoneInfo parent) { checkNotNull(parent); this.zoneId = parent.id(); this.zoneName = parent.name(); return this; } + + /** + * Sets name reference to the managed zone that this DNS record belongs to. + */ + Builder managedZone(String managedZoneName) { + this.zoneName = checkNotNull(managedZoneName); + return this; + } } /** @@ -196,12 +204,12 @@ public String name() { * Returns a list of DNS record stored in this record set. */ public List rrdatas() { - return ImmutableList.copyOf(rrdatas); + return rrdatas; } /** - * Returns the number of seconds that this ResourceRecordSet can be cached by resolvers. This - * number is provided by the user. + * Returns the number of seconds that this DnsResource can be cached by resolvers. This number is + * provided by the user. */ public Integer ttl() { return ttl; @@ -224,9 +232,9 @@ public String zoneName() { } /** - * Returns name of the managed zone that this record belongs to. + * Returns id of the managed zone that this record belongs to. * - *

The id of the managed zone is determined by the server when the managed zone is created. It + *

The id of the managed zone is determined by the server when the managed zone is created. It * is a read only value. If this DNS record is not associated with a managed zone, or if the id of * the managed zone was not loaded from the cloud service, this returns null. */ @@ -241,30 +249,32 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (obj instanceof DnsRecord) { - DnsRecord other = (DnsRecord) obj; - return zoneId == other.zoneId() - && zoneName == other.zoneName - && this.toRRSet().equals(other.toRRSet()); - } - return false; + return (obj instanceof DnsRecord) && Objects.equals(this.toPb(), ((DnsRecord) obj).toPb()) + && this.zoneId().equals(((DnsRecord) obj).zoneId()) + && this.zoneName().equals(((DnsRecord) obj).zoneName()); + } - com.google.api.services.dns.model.ResourceRecordSet toRRSet() { - com.google.api.services.dns.model.ResourceRecordSet rrset = + com.google.api.services.dns.model.ResourceRecordSet toPb() { + com.google.api.services.dns.model.ResourceRecordSet pb = new com.google.api.services.dns.model.ResourceRecordSet(); - rrset.setName(name); - rrset.setRrdatas(this.rrdatas()); - rrset.setTtl(ttl); - rrset.setType(type == null ? null : type.name()); - return rrset; + pb.setName(this.name()); + pb.setRrdatas(this.rrdatas()); + pb.setTtl(this.ttl()); + pb.setType(this.type() == null ? null : this.type().name()); + return pb; } @Override public String toString() { - return "DnsRecord{" + "name=" + name + ", rrdatas=" + rrdatas - + ", ttl=" + ttl + ", type=" + type + ", zoneName=" - + zoneName + ", zoneId=" + zoneId + '}'; + return MoreObjects.toStringHelper(this) + .add("name", name()) + .add("rrdatas", rrdatas()) + .add("ttl", ttl()) + .add("type", type()) + .add("zoneName", zoneName()) + .add("zoneId", zoneId()) + .toString(); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 55c72d794e87..ee9e6e58d61d 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -25,29 +25,30 @@ import org.easymock.EasyMock; - public class DnsRecordTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; private static final DnsRecord.DnsRecordType TYPE = DnsRecord.DnsRecordType.AAAA; - private static final ManagedZoneInfo MANAGED_ZONE_INFO_MOCK = - EasyMock.createMock(ManagedZoneInfo.class); private static final Long ZONE_ID = 12L; private static final String ZONE_NAME = "name"; - - static { - EasyMock.expect(MANAGED_ZONE_INFO_MOCK.id()).andReturn(ZONE_ID); - EasyMock.expect(MANAGED_ZONE_INFO_MOCK.name()).andReturn(ZONE_NAME); - EasyMock.replay(MANAGED_ZONE_INFO_MOCK); + // the following is initialized in @BeforeClass setUp() + private static DnsRecord record; + private static ManagedZoneInfo managedZoneInfoMock; + + @BeforeClass + public static void setUp() { + managedZoneInfoMock = EasyMock.createMock(ManagedZoneInfo.class); + EasyMock.expect(managedZoneInfoMock.id()).andReturn(ZONE_ID); + EasyMock.expect(managedZoneInfoMock.name()).andReturn(ZONE_NAME); + EasyMock.replay(managedZoneInfoMock); + record = DnsRecord.builder() + .name(NAME) + .ttl(TTL) + .managedZone(managedZoneInfoMock) + .build(); } - private static final DnsRecord RECORD = DnsRecord.builder() - .name(NAME) - .ttl(TTL) - .managedZone(MANAGED_ZONE_INFO_MOCK) - .build(); - @Test public void testDefaultDnsRecord() { DnsRecord record = DnsRecord.builder().build(); @@ -57,20 +58,23 @@ public void testDefaultDnsRecord() { @Test public void testBuilder() { - assertEquals(NAME, RECORD.name()); - assertEquals(TTL, RECORD.ttl()); + assertEquals(NAME, record.name()); + assertEquals(TTL, record.ttl()); - assertEquals(ZONE_ID, RECORD.zoneId()); // this was never assigned - assertEquals(ZONE_NAME, RECORD.zoneName()); - assertEquals(0, RECORD.rrdatas().size()); + assertEquals(ZONE_ID, record.zoneId()); // this was never assigned + assertEquals(ZONE_NAME, record.zoneName()); + assertEquals(0, record.rrdatas().size()); // verify that one can add records to the record set String testingRecord = "Testing record"; String anotherTestingRecord = "Another record 123"; - DnsRecord anotherRecord = RECORD.toBuilder() + String differentName = ZONE_NAME + "something"; + DnsRecord anotherRecord = record.toBuilder() .add(testingRecord) .add(anotherTestingRecord) + .managedZone(differentName) .build(); assertEquals(2, anotherRecord.rrdatas().size()); + assertEquals(differentName, anotherRecord.zoneName()); assertTrue(anotherRecord.rrdatas().contains(testingRecord)); assertTrue(anotherRecord.rrdatas().contains(anotherTestingRecord)); } @@ -89,39 +93,39 @@ public void testValidTtl() { @Test public void testEqualsAndNotEquals() { - DnsRecord clone = RECORD.toBuilder().build(); - assertEquals(clone, RECORD); - clone = RECORD.toBuilder().add("another record").build(); + DnsRecord clone = record.toBuilder().build(); + assertEquals(clone, record); + clone = record.toBuilder().add("another record").build(); final String differentName = "totally different name"; - clone = RECORD.toBuilder().name(differentName).build(); - assertNotEquals(clone, RECORD); - clone = RECORD.toBuilder().ttl(RECORD.ttl() + 1).build(); - assertNotEquals(clone, RECORD); - clone = RECORD.toBuilder().type(DnsRecord.DnsRecordType.TXT).build(); - assertNotEquals(clone, RECORD); + clone = record.toBuilder().name(differentName).build(); + assertNotEquals(clone, record); + clone = record.toBuilder().ttl(record.ttl() + 1).build(); + assertNotEquals(clone, record); + clone = record.toBuilder().type(DnsRecord.DnsRecordType.TXT).build(); + assertNotEquals(clone, record); ManagedZoneInfo anotherMock = EasyMock.createMock(ManagedZoneInfo.class); EasyMock.expect(anotherMock.id()).andReturn(ZONE_ID + 1); EasyMock.expect(anotherMock.name()).andReturn(ZONE_NAME + "more text"); EasyMock.replay(anotherMock); - clone = RECORD.toBuilder().managedZone(anotherMock).build(); - assertNotEquals(clone, RECORD); + clone = record.toBuilder().managedZone(anotherMock).build(); + assertNotEquals(clone, record); } @Test public void testSameHashCodeOnEquals() { - int hash = RECORD.hashCode(); - DnsRecord clone = RECORD.toBuilder().build(); + int hash = record.hashCode(); + DnsRecord clone = record.toBuilder().build(); assertEquals(clone.hashCode(), hash); } @Test public void testDifferentHashCodeOnDifferent() { - int hash = RECORD.hashCode(); + int hash = record.hashCode(); final String differentName = "totally different name"; - DnsRecord clone = RECORD.toBuilder().name(differentName).build(); - assertNotEquals(differentName, RECORD.name()); + DnsRecord clone = record.toBuilder().name(differentName).build(); + assertNotEquals(differentName, record.name()); assertNotEquals(clone.hashCode(), hash); - DnsRecord anotherClone = RECORD.toBuilder().add("another record").build(); + DnsRecord anotherClone = record.toBuilder().add("another record").build(); assertNotEquals(anotherClone.hashCode(), hash); } From 1fc0e3275e352706734dc935c6d4bab77976fb1c Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 20 Jan 2016 17:55:43 -0800 Subject: [PATCH 05/74] Implemented comments by @aozarov. Also removed incomplete ManagedZoneInfo.java. --- .../java/com/google/gcloud/dns/DnsRecord.java | 170 ++++++++++-------- .../google/gcloud/dns/ManagedZoneInfo.java | 44 ----- .../com/google/gcloud/dns/DnsRecordTest.java | 68 ++----- 3 files changed, 105 insertions(+), 177 deletions(-) delete mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 91278fa2a1e7..9cc21acfa0a5 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.google.gcloud.dns; import static com.google.common.base.Preconditions.checkArgument; @@ -20,6 +21,7 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import java.io.Serializable; @@ -30,7 +32,10 @@ /** * A class that represents Google Cloud DNS record set. * - *

A unit of data that will be returned by the DNS servers. + *

A DnsRecord is the unit of data that will be returned by the DNS servers upon a DNS request + * for a specific domain. The DnsRecord holds the current state of the DNS records that make up a + * managed zone. You can read the records but you do not modify them directly. Rather, you edit + * the records in a managed zone by creating a {@link ChangeRequest}. * * @see Google Cloud DNS * documentation @@ -42,26 +47,6 @@ public class DnsRecord implements Serializable { private final List rrdatas; private final Integer ttl; private final DnsRecordType type; - private final String zoneName; - private final Long zoneId; - - private DnsRecord() { - this.name = null; - this.rrdatas = null; - this.ttl = null; - this.type = null; - this.zoneName = null; - this.zoneId = null; - } - - DnsRecord(Builder builder) { - this.name = builder.name; - this.rrdatas = ImmutableList.copyOf(builder.rrdatas); - this.ttl = builder.ttl; - this.type = builder.type; - this.zoneName = builder.zoneName; - this.zoneId = builder.zoneId; - } /** * Enum for the DNS record types supported by Cloud DNS. @@ -73,16 +58,51 @@ private DnsRecord() { * supported record types */ public enum DnsRecordType { + /** + * Address record, which is used to map host names to their IPv4 address. + */ A, + /** + * IPv6 Address record, which is used to map host names to their IPv6 address. + */ AAAA, + /** + * Canonical name record, which is used to alias names. + */ CNAME, + /** + * Mail exchange record, which is used in routing requests to mail servers. + */ MX, + /** + * Naming authority pointer record, defined by RFC3403. + */ NAPTR, + /** + * Name server record, which delegates a DNS zone to an authoritative server. + */ NS, + /** + * Pointer record, which is often used for reverse DNS lookups. + */ PTR, + /** + * Start of authority record, which specifies authoritative information about a DNS zone. + */ SOA, + /** + * Sender policy framework record, which is used in email validation systems. + */ SPF, + /** + * Service locator record, which is used by some voice over IP, instant messaging protocols and + * other applications. + */ SRV, + /** + * Text record, which can contain arbitrary text and can also be used to define machine readable + * data such as security or abuse prevention information. + */ TXT } @@ -92,8 +112,6 @@ public static class Builder { private String name; private Integer ttl; private DnsRecordType type; - private String zoneName; - private Long zoneId; private Builder() { } @@ -102,12 +120,10 @@ private Builder() { * Creates a builder and pre-populates attributes with the values from the provided DnsRecord * instance. */ - public Builder(DnsRecord record) { + private Builder(DnsRecord record) { this.name = record.name; this.ttl = record.ttl; this.type = record.type; - this.zoneId = record.zoneId; - this.zoneName = record.zoneName; this.rrdatas.addAll(record.rrdatas); } @@ -118,11 +134,46 @@ public Builder(DnsRecord record) { * @see Google * DNS documentation . */ - public Builder add(String record) { + public Builder addRecord(String record) { this.rrdatas.add(checkNotNull(record)); return this; } + /** + * Removes a record from the set. An exact match is required. + */ + public Builder removerRecord(String record) { + this.rrdatas.remove(checkNotNull(record)); + return this; + } + + /** + * Removes a record on the given index from the set. + */ + public Builder removerRecord(int index) { + checkArgument(index >= 0 && index < this.rrdatas.size(), "The index is out of bounds. An " + + "integer between 0 and " + (this.rrdatas.size() - 1) + " is required. The provided " + + "value was " + index + "."); + this.rrdatas.remove(index); + return this; + } + + /** + * Removes all the records. + */ + public Builder clearRecords() { + this.rrdatas.clear(); + return this; + } + + /** + * Replaces the current records with the provided list of records. + */ + public Builder records(List records) { + this.rrdatas = Lists.newLinkedList(checkNotNull(records)); + return this; + } + /** * Sets name for this DNS record set. For example, www.example.com. */ @@ -157,26 +208,13 @@ public Builder type(DnsRecordType type) { public DnsRecord build() { return new DnsRecord(this); } + } - /** - * Sets references to the managed zone that this DNS record belongs to. - * - * todo(mderka): consider if this method is needed; may not be possible when listing records - */ - Builder managedZone(ManagedZoneInfo parent) { - checkNotNull(parent); - this.zoneId = parent.id(); - this.zoneName = parent.name(); - return this; - } - - /** - * Sets name reference to the managed zone that this DNS record belongs to. - */ - Builder managedZone(String managedZoneName) { - this.zoneName = checkNotNull(managedZoneName); - return this; - } + DnsRecord(Builder builder) { + this.name = builder.name; + this.rrdatas = ImmutableList.copyOf(builder.rrdatas); + this.ttl = builder.ttl; + this.type = builder.type; } /** @@ -187,7 +225,7 @@ public Builder toBuilder() { } /** - * Creates an empty builder + * Creates an empty builder. */ public static Builder builder() { return new Builder(); @@ -203,13 +241,12 @@ public String name() { /** * Returns a list of DNS record stored in this record set. */ - public List rrdatas() { + public List records() { return rrdatas; } /** - * Returns the number of seconds that this DnsResource can be cached by resolvers. This number is - * provided by the user. + * Returns the number of seconds that this DnsResource can be cached by resolvers. */ public Integer ttl() { return ttl; @@ -222,44 +259,21 @@ public DnsRecordType type() { return type; } - /** - * Returns name of the managed zone that this record belongs to. The name of the managed zone is - * provided by the user when the managed zone is created. It is unique within a project. If this - * DNS record is not associated with a managed zone, this returns null. - */ - public String zoneName() { - return zoneName; - } - - /** - * Returns id of the managed zone that this record belongs to. - * - *

The id of the managed zone is determined by the server when the managed zone is created. It - * is a read only value. If this DNS record is not associated with a managed zone, or if the id of - * the managed zone was not loaded from the cloud service, this returns null. - */ - public Long zoneId() { - return zoneId; - } - @Override public int hashCode() { - return Objects.hash(name, rrdatas, ttl, type, zoneName, zoneId); + return Objects.hash(name, rrdatas, ttl, type); } @Override public boolean equals(Object obj) { - return (obj instanceof DnsRecord) && Objects.equals(this.toPb(), ((DnsRecord) obj).toPb()) - && this.zoneId().equals(((DnsRecord) obj).zoneId()) - && this.zoneName().equals(((DnsRecord) obj).zoneName()); - + return (obj instanceof DnsRecord) && Objects.equals(this.toPb(), ((DnsRecord) obj).toPb()); } com.google.api.services.dns.model.ResourceRecordSet toPb() { com.google.api.services.dns.model.ResourceRecordSet pb = new com.google.api.services.dns.model.ResourceRecordSet(); pb.setName(this.name()); - pb.setRrdatas(this.rrdatas()); + pb.setRrdatas(this.records()); pb.setTtl(this.ttl()); pb.setType(this.type() == null ? null : this.type().name()); return pb; @@ -269,11 +283,9 @@ com.google.api.services.dns.model.ResourceRecordSet toPb() { public String toString() { return MoreObjects.toStringHelper(this) .add("name", name()) - .add("rrdatas", rrdatas()) + .add("rrdatas", records()) .add("ttl", ttl()) .add("type", type()) - .add("zoneName", zoneName()) - .add("zoneId", zoneId()) .toString(); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java deleted file mode 100644 index d5ed8351dc34..000000000000 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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.dns; - -/** - * todo(mderka): Implement. - * todo(mderka): Add documentation. - */ -public class ManagedZoneInfo { - - private final String name; - private final Long id; - - public String name() { - throw new UnsupportedOperationException("Not implemented yet."); - // todo(mderka): Implement - } - - public Long id() { - return id; - // todo(mderka): Implement - } - - private ManagedZoneInfo() { - name = null; - id = null; - throw new UnsupportedOperationException("Not implemented yet"); - // todo(mderka): Implement - } - -} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index ee9e6e58d61d..4c03306ffb02 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -20,63 +20,40 @@ import static org.junit.Assert.fail; import static org.junit.Assert.assertNotEquals; -import org.junit.BeforeClass; import org.junit.Test; -import org.easymock.EasyMock; - public class DnsRecordTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; private static final DnsRecord.DnsRecordType TYPE = DnsRecord.DnsRecordType.AAAA; - private static final Long ZONE_ID = 12L; - private static final String ZONE_NAME = "name"; - // the following is initialized in @BeforeClass setUp() - private static DnsRecord record; - private static ManagedZoneInfo managedZoneInfoMock; - - @BeforeClass - public static void setUp() { - managedZoneInfoMock = EasyMock.createMock(ManagedZoneInfo.class); - EasyMock.expect(managedZoneInfoMock.id()).andReturn(ZONE_ID); - EasyMock.expect(managedZoneInfoMock.name()).andReturn(ZONE_NAME); - EasyMock.replay(managedZoneInfoMock); - record = DnsRecord.builder() - .name(NAME) - .ttl(TTL) - .managedZone(managedZoneInfoMock) - .build(); - } + private static final DnsRecord record = DnsRecord.builder() + .name(NAME) + .ttl(TTL) + .type(TYPE) + .build(); @Test public void testDefaultDnsRecord() { DnsRecord record = DnsRecord.builder().build(); - assertEquals(0, record.rrdatas().size()); + assertEquals(0, record.records().size()); } @Test public void testBuilder() { - assertEquals(NAME, record.name()); assertEquals(TTL, record.ttl()); - - assertEquals(ZONE_ID, record.zoneId()); // this was never assigned - assertEquals(ZONE_NAME, record.zoneName()); - assertEquals(0, record.rrdatas().size()); + assertEquals(0, record.records().size()); // verify that one can add records to the record set String testingRecord = "Testing record"; String anotherTestingRecord = "Another record 123"; - String differentName = ZONE_NAME + "something"; DnsRecord anotherRecord = record.toBuilder() - .add(testingRecord) - .add(anotherTestingRecord) - .managedZone(differentName) + .addRecord(testingRecord) + .addRecord(anotherTestingRecord) .build(); - assertEquals(2, anotherRecord.rrdatas().size()); - assertEquals(differentName, anotherRecord.zoneName()); - assertTrue(anotherRecord.rrdatas().contains(testingRecord)); - assertTrue(anotherRecord.rrdatas().contains(anotherTestingRecord)); + assertEquals(2, anotherRecord.records().size()); + assertTrue(anotherRecord.records().contains(testingRecord)); + assertTrue(anotherRecord.records().contains(anotherTestingRecord)); } @Test @@ -95,7 +72,8 @@ public void testValidTtl() { public void testEqualsAndNotEquals() { DnsRecord clone = record.toBuilder().build(); assertEquals(clone, record); - clone = record.toBuilder().add("another record").build(); + clone = record.toBuilder().addRecord("another record").build(); + assertNotEquals(clone, record); final String differentName = "totally different name"; clone = record.toBuilder().name(differentName).build(); assertNotEquals(clone, record); @@ -103,12 +81,6 @@ public void testEqualsAndNotEquals() { assertNotEquals(clone, record); clone = record.toBuilder().type(DnsRecord.DnsRecordType.TXT).build(); assertNotEquals(clone, record); - ManagedZoneInfo anotherMock = EasyMock.createMock(ManagedZoneInfo.class); - EasyMock.expect(anotherMock.id()).andReturn(ZONE_ID + 1); - EasyMock.expect(anotherMock.name()).andReturn(ZONE_NAME + "more text"); - EasyMock.replay(anotherMock); - clone = record.toBuilder().managedZone(anotherMock).build(); - assertNotEquals(clone, record); } @Test @@ -117,16 +89,4 @@ public void testSameHashCodeOnEquals() { DnsRecord clone = record.toBuilder().build(); assertEquals(clone.hashCode(), hash); } - - @Test - public void testDifferentHashCodeOnDifferent() { - int hash = record.hashCode(); - final String differentName = "totally different name"; - DnsRecord clone = record.toBuilder().name(differentName).build(); - assertNotEquals(differentName, record.name()); - assertNotEquals(clone.hashCode(), hash); - DnsRecord anotherClone = record.toBuilder().add("another record").build(); - assertNotEquals(anotherClone.hashCode(), hash); - } - } From 01662be5e9f6bf11496d84b909676f97ca0401b9 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 21 Jan 2016 10:00:41 -0800 Subject: [PATCH 06/74] Implements comments by @ajkannan --- gcloud-java-dns/pom.xml | 12 +++--- .../java/com/google/gcloud/dns/DnsRecord.java | 37 ++++++++++++------- .../com/google/gcloud/dns/DnsRecordTest.java | 36 ++++++++++++++---- pom.xml | 1 + 4 files changed, 59 insertions(+), 27 deletions(-) diff --git a/gcloud-java-dns/pom.xml b/gcloud-java-dns/pom.xml index 55d720bc0a36..5f04f261d500 100644 --- a/gcloud-java-dns/pom.xml +++ b/gcloud-java-dns/pom.xml @@ -1,5 +1,7 @@ - + 4.0.0 com.google.gcloud gcloud-java-dns @@ -28,10 +30,10 @@ v1-rev7-1.21.0 compile - - com.google.guava - guava-jdk5 - + + com.google.guava + guava-jdk5 + com.google.api-client google-api-client diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 9cc21acfa0a5..f73c880f22f3 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -24,18 +24,17 @@ import com.google.common.collect.Lists; import java.io.Serializable; - import java.util.LinkedList; import java.util.List; import java.util.Objects; /** - * A class that represents Google Cloud DNS record set. + * A class that represents a Google Cloud DNS record set. * - *

A DnsRecord is the unit of data that will be returned by the DNS servers upon a DNS request - * for a specific domain. The DnsRecord holds the current state of the DNS records that make up a - * managed zone. You can read the records but you do not modify them directly. Rather, you edit - * the records in a managed zone by creating a {@link ChangeRequest}. + *

A {@code DnsRecord} is the unit of data that will be returned by the DNS servers upon a DNS + * request for a specific domain. The {@code DnsRecord} holds the current state of the DNS records + * that make up a managed zone. You can read the records but you do not modify them directly. + * Rather, you edit the records in a managed zone by creating a ChangeRequest. * * @see Google Cloud DNS * documentation @@ -117,8 +116,8 @@ private Builder() { } /** - * Creates a builder and pre-populates attributes with the values from the provided DnsRecord - * instance. + * Creates a builder and pre-populates attributes with the values from the provided {@code + * DnsRecord} instance. */ private Builder(DnsRecord record) { this.name = record.name; @@ -142,7 +141,7 @@ public Builder addRecord(String record) { /** * Removes a record from the set. An exact match is required. */ - public Builder removerRecord(String record) { + public Builder removeRecord(String record) { this.rrdatas.remove(checkNotNull(record)); return this; } @@ -150,7 +149,7 @@ public Builder removerRecord(String record) { /** * Removes a record on the given index from the set. */ - public Builder removerRecord(int index) { + public Builder removeRecord(int index) { checkArgument(index >= 0 && index < this.rrdatas.size(), "The index is out of bounds. An " + "integer between 0 and " + (this.rrdatas.size() - 1) + " is required. The provided " + "value was " + index + "."); @@ -225,10 +224,10 @@ public Builder toBuilder() { } /** - * Creates an empty builder. + * Creates a builder for {@code DnsRecord} with mandatorily set name and type of the record. */ - public static Builder builder() { - return new Builder(); + public static Builder builder(String name, DnsRecordType type) { + return new Builder().name(name).type(type); } /** @@ -279,6 +278,17 @@ com.google.api.services.dns.model.ResourceRecordSet toPb() { return pb; } + static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) { + Builder b = builder(pb.getName(), DnsRecordType.valueOf(pb.getType())); + if (pb.getRrdatas() != null) { + b.records(pb.getRrdatas()); + } + if (pb.getTtl() != null) { + b.ttl(pb.getTtl()); + } + return b.build(); + } + @Override public String toString() { return MoreObjects.toStringHelper(this) @@ -288,5 +298,4 @@ public String toString() { .add("type", type()) .toString(); } - } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 4c03306ffb02..e5b283a20acc 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -27,15 +27,13 @@ public class DnsRecordTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; private static final DnsRecord.DnsRecordType TYPE = DnsRecord.DnsRecordType.AAAA; - private static final DnsRecord record = DnsRecord.builder() - .name(NAME) + private static final DnsRecord record = DnsRecord.builder(NAME, TYPE) .ttl(TTL) - .type(TYPE) .build(); @Test public void testDefaultDnsRecord() { - DnsRecord record = DnsRecord.builder().build(); + DnsRecord record = DnsRecord.builder(NAME, TYPE).build(); assertEquals(0, record.records().size()); } @@ -59,13 +57,13 @@ public void testBuilder() { @Test public void testValidTtl() { try { - DnsRecord.builder().ttl(-1); + DnsRecord.builder(NAME, TYPE).ttl(-1); fail("A negative value is not acceptable for ttl."); } catch (IllegalArgumentException e) { // expected } - DnsRecord.builder().ttl(0); - DnsRecord.builder().ttl(Integer.MAX_VALUE); + DnsRecord.builder(NAME, TYPE).ttl(0); + DnsRecord.builder(NAME, TYPE).ttl(Integer.MAX_VALUE); } @Test @@ -89,4 +87,26 @@ public void testSameHashCodeOnEquals() { DnsRecord clone = record.toBuilder().build(); assertEquals(clone.hashCode(), hash); } -} + + @Test + public void testToAndFromPb() { + assertEquals(record, DnsRecord.fromPb(record.toPb())); + DnsRecord partial = DnsRecord.builder(NAME, TYPE).build(); + assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + partial = DnsRecord.builder(NAME, TYPE).addRecord("test").build(); + assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + partial = DnsRecord.builder(NAME, TYPE).ttl(15).build(); + assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + } + + @Test + public void testToBuilder() { + assertEquals(record, record.toBuilder().build()); + DnsRecord partial = DnsRecord.builder(NAME, TYPE).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = DnsRecord.builder(NAME, TYPE).addRecord("test").build(); + assertEquals(partial, partial.toBuilder().build()); + partial = DnsRecord.builder(NAME, TYPE).ttl(15).build(); + assertEquals(partial, partial.toBuilder().build()); + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index cd5c19720cd8..7a435cc1dbae 100644 --- a/pom.xml +++ b/pom.xml @@ -70,6 +70,7 @@ gcloud-java-bigquery gcloud-java-core gcloud-java-datastore + gcloud-java-dns gcloud-java-examples gcloud-java-resourcemanager gcloud-java-storage From 1c657158857a343c2ad4c761cb287d535f396704 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 21 Jan 2016 13:44:40 -0800 Subject: [PATCH 07/74] Removed the method for removing a record by index. --- .../main/java/com/google/gcloud/dns/DnsRecord.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index f73c880f22f3..41a8569d3937 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -146,17 +146,6 @@ public Builder removeRecord(String record) { return this; } - /** - * Removes a record on the given index from the set. - */ - public Builder removeRecord(int index) { - checkArgument(index >= 0 && index < this.rrdatas.size(), "The index is out of bounds. An " + - "integer between 0 and " + (this.rrdatas.size() - 1) + " is required. The provided " + - "value was " + index + "."); - this.rrdatas.remove(index); - return this; - } - /** * Removes all the records. */ From f994057f1d2e8bf4f6b1196d4ae578ba3321951b Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 22 Jan 2016 10:17:34 -0800 Subject: [PATCH 08/74] Another round of comments from @aozarov. --- .../java/com/google/gcloud/dns/DnsRecord.java | 47 ++++++++++--------- .../com/google/gcloud/dns/DnsRecordTest.java | 41 ++++++++++++---- 2 files changed, 58 insertions(+), 30 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 41a8569d3937..c41e72a77400 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -33,7 +33,7 @@ * *

A {@code DnsRecord} is the unit of data that will be returned by the DNS servers upon a DNS * request for a specific domain. The {@code DnsRecord} holds the current state of the DNS records - * that make up a managed zone. You can read the records but you do not modify them directly. + * that make up a managed zone. You can read the records but you cannot modify them directly. * Rather, you edit the records in a managed zone by creating a ChangeRequest. * * @see Google Cloud DNS @@ -45,7 +45,7 @@ public class DnsRecord implements Serializable { private final String name; private final List rrdatas; private final Integer ttl; - private final DnsRecordType type; + private final Type type; /** * Enum for the DNS record types supported by Cloud DNS. @@ -56,7 +56,7 @@ public class DnsRecord implements Serializable { * @see Cloud DNS * supported record types */ - public enum DnsRecordType { + public enum Type { /** * Address record, which is used to map host names to their IPv4 address. */ @@ -105,14 +105,19 @@ public enum DnsRecordType { TXT } + /** + * A builder of {@link DnsRecord}. + */ public static class Builder { private List rrdatas = new LinkedList<>(); private String name; private Integer ttl; - private DnsRecordType type; + private Type type; - private Builder() { + private Builder(String name, Type type) { + this.name = checkNotNull(name); + this.type = checkNotNull(type); } /** @@ -177,7 +182,7 @@ public Builder name(String name) { * @param ttl A non-negative number of seconds */ public Builder ttl(int ttl) { - checkArgument(ttl >= 0, "TTL cannot be negative. The supplied value was " + ttl + "."); + checkArgument(ttl >= 0, "TTL cannot be negative. The supplied value was %s.", ttl); this.ttl = ttl; return this; } @@ -185,7 +190,7 @@ public Builder ttl(int ttl) { /** * The identifier of a supported record type, for example, A, AAAA, MX, TXT, and so on. */ - public Builder type(DnsRecordType type) { + public Builder type(Type type) { this.type = checkNotNull(type); return this; } @@ -198,7 +203,7 @@ public DnsRecord build() { } } - DnsRecord(Builder builder) { + private DnsRecord(Builder builder) { this.name = builder.name; this.rrdatas = ImmutableList.copyOf(builder.rrdatas); this.ttl = builder.ttl; @@ -213,14 +218,14 @@ public Builder toBuilder() { } /** - * Creates a builder for {@code DnsRecord} with mandatorily set name and type of the record. + * Creates a {@code DnsRecord} builder for the given {@code name} and {@code type}. */ - public static Builder builder(String name, DnsRecordType type) { - return new Builder().name(name).type(type); + public static Builder builder(String name, Type type) { + return new Builder(name, type); } /** - * Get the mandatory user assigned name of this DNS record. + * Returns the user-assigned name of this DNS record. */ public String name() { return name; @@ -243,7 +248,7 @@ public Integer ttl() { /** * Returns the type of this DNS record. */ - public DnsRecordType type() { + public Type type() { return type; } @@ -259,16 +264,16 @@ public boolean equals(Object obj) { com.google.api.services.dns.model.ResourceRecordSet toPb() { com.google.api.services.dns.model.ResourceRecordSet pb = - new com.google.api.services.dns.model.ResourceRecordSet(); + new com.google.api.services.dns.model.ResourceRecordSet(); pb.setName(this.name()); pb.setRrdatas(this.records()); pb.setTtl(this.ttl()); - pb.setType(this.type() == null ? null : this.type().name()); + pb.setType(this.type().name()); return pb; } static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) { - Builder b = builder(pb.getName(), DnsRecordType.valueOf(pb.getType())); + Builder b = builder(pb.getName(), Type.valueOf(pb.getType())); if (pb.getRrdatas() != null) { b.records(pb.getRrdatas()); } @@ -281,10 +286,10 @@ static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("name", name()) - .add("rrdatas", records()) - .add("ttl", ttl()) - .add("type", type()) - .toString(); + .add("name", name()) + .add("rrdatas", records()) + .add("ttl", ttl()) + .add("type", type()) + .toString(); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index e5b283a20acc..43ced20cf207 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -26,29 +26,32 @@ public class DnsRecordTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; - private static final DnsRecord.DnsRecordType TYPE = DnsRecord.DnsRecordType.AAAA; + private static final DnsRecord.Type TYPE = DnsRecord.Type.AAAA; private static final DnsRecord record = DnsRecord.builder(NAME, TYPE) - .ttl(TTL) - .build(); + .ttl(TTL) + .build(); @Test public void testDefaultDnsRecord() { DnsRecord record = DnsRecord.builder(NAME, TYPE).build(); assertEquals(0, record.records().size()); + assertEquals(TYPE, record.type()); + assertEquals(NAME, record.name()); } @Test public void testBuilder() { assertEquals(NAME, record.name()); assertEquals(TTL, record.ttl()); + assertEquals(TYPE, record.type()); assertEquals(0, record.records().size()); // verify that one can add records to the record set String testingRecord = "Testing record"; String anotherTestingRecord = "Another record 123"; DnsRecord anotherRecord = record.toBuilder() - .addRecord(testingRecord) - .addRecord(anotherTestingRecord) - .build(); + .addRecord(testingRecord) + .addRecord(anotherTestingRecord) + .build(); assertEquals(2, anotherRecord.records().size()); assertTrue(anotherRecord.records().contains(testingRecord)); assertTrue(anotherRecord.records().contains(anotherTestingRecord)); @@ -72,12 +75,12 @@ public void testEqualsAndNotEquals() { assertEquals(clone, record); clone = record.toBuilder().addRecord("another record").build(); assertNotEquals(clone, record); - final String differentName = "totally different name"; + String differentName = "totally different name"; clone = record.toBuilder().name(differentName).build(); assertNotEquals(clone, record); clone = record.toBuilder().ttl(record.ttl() + 1).build(); assertNotEquals(clone, record); - clone = record.toBuilder().type(DnsRecord.DnsRecordType.TXT).build(); + clone = record.toBuilder().type(DnsRecord.Type.TXT).build(); assertNotEquals(clone, record); } @@ -109,4 +112,24 @@ public void testToBuilder() { partial = DnsRecord.builder(NAME, TYPE).ttl(15).build(); assertEquals(partial, partial.toBuilder().build()); } -} \ No newline at end of file + + @Test + public void clearRecordSet() { + // make sure that we are starting not empty + DnsRecord clone = record.toBuilder().addRecord("record").addRecord("another").build(); + assertNotEquals(0, clone.records().size()); + clone = clone.toBuilder().clearRecords().build(); + assertEquals(0, clone.records().size()); + clone.toPb(); // verify that pb allows it + } + + @Test + public void removeFromRecordSet() { + String recordString = "record"; + // make sure that we are starting not empty + DnsRecord clone = record.toBuilder().addRecord(recordString).build(); + assertNotEquals(0, clone.records().size()); + clone = clone.toBuilder().removeRecord(recordString).build(); + assertEquals(0, clone.records().size()); + } +} From e8dd142fb0a6db4322fb83b79e999d97bd88e94e Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 19 Jan 2016 16:34:50 -0800 Subject: [PATCH 09/74] Created a ManagedZoneInfo class as part of the model. --- .../google/gcloud/dns/ManagedZoneInfo.java | 334 ++++++++++++++++++ .../gcloud/dns/ManagedZoneInfoTest.java | 198 +++++++++++ 2 files changed, 532 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java new file mode 100644 index 000000000000..e5b50b3e6669 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java @@ -0,0 +1,334 @@ +/* + * 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.dns; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +import java.io.Serializable; +import java.math.BigInteger; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; + +/** + * This class is a container for the managed zone metainformation. Managed zone is a resource that + * represents a DNS zone hosted by the Cloud DNS service. See Google + * Cloud DNS documentation for more information. + */ +public class ManagedZoneInfo implements Serializable { + + private static final long serialVersionUID = 201601191647L; + private final String name; + private final Long id; + private final Long creationTimeMillis; + private final String dnsName; + private final String description; + private final String nameServerSet; + private final List nameServers; + + /** + * A builder for {@code ManagedZoneInfo}. + */ + public static class Builder { + private String name; + private Long id; + private Long creationTimeMillis; + private String dnsName; + private String description; + private String nameServerSet; + private List nameServers = new LinkedList<>(); + + private Builder() { + } + + private Builder(Long id) { + this.id = checkNotNull(id); + } + + private Builder(String name) { + this.name = checkNotNull(name); + } + + private Builder(String name, Long id) { + this.name = checkNotNull(name); + this.id = checkNotNull(id); + } + + /** + * Creates a builder from an existing ManagedZoneInfo object. + */ + Builder(ManagedZoneInfo info) { + this.name = info.name; + this.id = info.id; + this.creationTimeMillis = info.creationTimeMillis; + this.dnsName = info.dnsName; + this.description = info.description; + this.nameServerSet = info.nameServerSet; + this.nameServers.addAll(info.nameServers); + } + + /** + * Sets a mandatory user-provided name for the zone. It must be unique within the project. + */ + public Builder name(String name) { + this.name = checkNotNull(name); + return this; + } + + /** + * Sets an id for the managed zone which is assigned to the managed zone by the server. + */ + public Builder id(long id) { + this.id = id; + return this; + } + + /** + * Sets the time when this managed zone was created. + */ + Builder creationTimeMillis(long creationTimeMillis) { + checkArgument(creationTimeMillis >= 0, "The timestamp cannot be negative."); + this.creationTimeMillis = creationTimeMillis; + return this; + } + + /** + * Sets a mandatory DNS name of this managed zone, for instance "example.com.". + */ + public Builder dnsName(String dnsName) { + this.dnsName = checkNotNull(dnsName); + return this; + } + + /** + * Sets a mandatory description for this managed zone. The value is a string of at most 1024 + * characters (this limit is posed by Google Cloud DNS; gcloud-java does not enforce the limit) + * which has no effect on the managed zone's function. + */ + public Builder description(String description) { + this.description = checkNotNull(description); + return this; + } + + /** + * Optionally specifies the NameServerSet for this managed zone. A NameServerSet is a set of DNS + * name servers that all host the same ManagedZones. + */ + public Builder nameServerSet(String nameServerSet) { + // todo(mderka) add more to the doc when questions are answered by the service owner + this.nameServerSet = checkNotNull(nameServerSet); + return this; + } + + /** + * Sets a list of servers that hold the information about the managed zone. This information is + * provided by Google Cloud DNS and is read only. + */ + Builder nameServers(List nameServers) { + this.nameServers.addAll(checkNotNull(nameServers)); + return this; + } + + /** + * Removes all the nameservers from the list. + */ + Builder clearNameServers() { + this.nameServers.clear(); + return this; + } + + /** + * Builds the instance of ManagedZoneInfo based on the information set here. + */ + public ManagedZoneInfo build() { + return new ManagedZoneInfo(this); + } + } + + private ManagedZoneInfo(Builder builder) { + this.name = builder.name; + this.id = builder.id; + this.creationTimeMillis = builder.creationTimeMillis; + this.dnsName = builder.dnsName; + this.description = builder.description; + this.nameServerSet = builder.nameServerSet; + this.nameServers = ImmutableList.copyOf(builder.nameServers); + } + + /** + * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code name}. + */ + public static Builder builder(String name) { + return new Builder(name); + } + + /** + * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code id}. + */ + public static Builder builder(Long id) { + return new Builder(id); + } + + /** + * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code name} and {@code id}. + */ + public static Builder builder(String name, Long id) { + return new Builder(name, id); + } + + /** + * Returns an empty builder for {@code ManagedZoneInfo}. We use it internally in {@code toPb()}. + */ + private static Builder builder() { + return new Builder(); + } + + /** + * Returns the user-defined name of the managed zone. + */ + public String name() { + return name; + } + + /** + * Returns the read-only managed zone id assigned by the server. + */ + public Long id() { + return id; + } + + /** + * Returns the time when this time that this managed zone was created on the server. + */ + public Long creationTimeMillis() { + return creationTimeMillis; + } + + /** + * Returns the DNS name of this managed zone, for instance "example.com.". + */ + public String dnsName() { + return dnsName; + } + + /** + * Returns the description of this managed zone. This is at most 1024 long mandatory string + * provided by the user. + */ + public String description() { + return description; + } + + /** + * Returns the optionally specified set of DNS name servers that all host this managed zone. + */ + public String nameServerSet() { + // todo(mderka) update this doc after finding out more about this from the service owners + return nameServerSet; + } + + /** + * The nameservers that the managed zone should be delegated to. This is defined by the Google DNS + * cloud. + */ + public List nameServers() { + return nameServers; + } + + /** + * Returns a builder for {@code ManagedZoneInfo} prepopulated with the metadata of this managed + * zone. + */ + public Builder toBuilder() { + return new Builder(this); + } + + com.google.api.services.dns.model.ManagedZone toPb() { + com.google.api.services.dns.model.ManagedZone pb = + new com.google.api.services.dns.model.ManagedZone(); + pb.setDescription(this.description()); + pb.setDnsName(this.dnsName()); + if (this.id() != null) { + pb.setId(BigInteger.valueOf(this.id())); + } + pb.setName(this.name()); + pb.setNameServers(this.nameServers()); + pb.setNameServerSet(this.nameServerSet()); + if (this.creationTimeMillis() != null) { + pb.setCreationTime(ISODateTimeFormat.dateTime() + .withZoneUTC() + .print(this.creationTimeMillis())); + } + return pb; + } + + static ManagedZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { + Builder b = builder(); + if (pb.getDescription() != null) { + b.description(pb.getDescription()); + } + if (pb.getDnsName() != null) { + b.dnsName(pb.getDnsName()); + } + if (pb.getId() != null) { + b.id(pb.getId().longValue()); + } + if (pb.getName() != null) { + b.name(pb.getName()); + } + if (pb.getNameServers() != null) { + b.nameServers(pb.getNameServers()); + } + if (pb.getNameServerSet() != null) { + b.nameServerSet(pb.getNameServerSet()); + } + if (pb.getCreationTime() != null) { + b.creationTimeMillis(DateTime.parse(pb.getCreationTime()).getMillis()); + } + return b.build(); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof ManagedZoneInfo && Objects.equals(toPb(), ((ManagedZoneInfo) obj).toPb()); + } + + @Override + public int hashCode() { + return Objects.hash(name, id, creationTimeMillis, dnsName, + description, nameServerSet, nameServers); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("name", name()) + .add("id", id()) + .add("description", description()) + .add("dnsName", dnsName()) + .add("nameServerSet", nameServerSet()) + .add("nameServers", nameServers()) + .toString(); + } +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java new file mode 100644 index 000000000000..6516c7577d2f --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java @@ -0,0 +1,198 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.common.collect.Lists; + +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.LinkedList; +import java.util.List; + +public class ManagedZoneInfoTest { + + private static final String NAME = "mz-example.com"; + private static final Long ID = 123L; + private static final Long CREATION_TIME_MILLIS = 1123468321321L; + private static final String DNS_NAME = "example.com."; + private static final String DESCRIPTION = "description for the zone"; + private static final String NAME_SERVER_SET = "some set"; + private static final String NS1 = "name server 1"; + private static final String NS2 = "name server 2"; + private static final String NS3 = "name server 3"; + private static List nameServers = new LinkedList<>(); + private static ManagedZoneInfo info; + + @BeforeClass + public static void setUp() { + nameServers.add(NS1); + nameServers.add(NS2); + nameServers.add(NS3); + assertEquals(3, nameServers.size()); + info = ManagedZoneInfo.builder(NAME, ID) + .creationTimeMillis(CREATION_TIME_MILLIS) + .dnsName(DNS_NAME) + .description(DESCRIPTION) + .nameServerSet(NAME_SERVER_SET) + .nameServers(nameServers) + .build(); + System.out.println(info); + } + + @Test + public void testDefaultBuilders() { + ManagedZoneInfo withName = ManagedZoneInfo.builder(NAME).build(); + assertTrue(withName.nameServers().isEmpty()); + assertEquals(NAME, withName.name()); + assertNull(withName.id()); + assertNull(withName.creationTimeMillis()); + assertNull(withName.nameServerSet()); + assertNull(withName.description()); + assertNull(withName.dnsName()); + ManagedZoneInfo withId = ManagedZoneInfo.builder(ID).build(); + assertTrue(withId.nameServers().isEmpty()); + assertEquals(ID, withId.id()); + assertNull(withId.name()); + assertNull(withId.creationTimeMillis()); + assertNull(withId.nameServerSet()); + assertNull(withId.description()); + assertNull(withId.dnsName()); + ManagedZoneInfo withBoth = ManagedZoneInfo.builder(NAME, ID).build(); + assertTrue(withBoth.nameServers().isEmpty()); + assertEquals(ID, withBoth.id()); + assertEquals(NAME, withBoth.name()); + assertNull(withBoth.creationTimeMillis()); + assertNull(withBoth.nameServerSet()); + assertNull(withBoth.description()); + assertNull(withBoth.dnsName()); + } + + @Test + public void testBuilder() { + assertEquals(3, info.nameServers().size()); + assertEquals(NS1, info.nameServers().get(0)); + assertEquals(NS2, info.nameServers().get(1)); + assertEquals(NS3, info.nameServers().get(2)); + assertEquals(NAME, info.name()); + assertEquals(ID, info.id()); + assertEquals(CREATION_TIME_MILLIS, info.creationTimeMillis()); + assertEquals(NAME_SERVER_SET, info.nameServerSet()); + assertEquals(DESCRIPTION, info.description()); + assertEquals(DNS_NAME, info.dnsName()); + } + + @Test + public void testValidCreationTime() { + try { + ManagedZoneInfo.builder(NAME).creationTimeMillis(-1); + fail("A negative value is not acceptable for creation time."); + } catch (IllegalArgumentException e) { + // expected + } + ManagedZoneInfo.builder(NAME).creationTimeMillis(0); + ManagedZoneInfo.builder(NAME).creationTimeMillis(Long.MAX_VALUE); + } + + @Test + public void testEqualsAndNotEquals() { + ManagedZoneInfo clone = info.toBuilder().build(); + assertEquals(clone, info); + List moreServers = Lists.newLinkedList(nameServers); + moreServers.add(NS1); + clone = info.toBuilder().nameServers(moreServers).build(); + assertNotEquals(clone, info); + String differentName = "totally different name"; + clone = info.toBuilder().name(differentName).build(); + assertNotEquals(clone, info); + clone = info.toBuilder().creationTimeMillis(info.creationTimeMillis() + 1).build(); + assertNotEquals(clone, info); + clone = info.toBuilder().description(info.description() + "aaaa").build(); + assertNotEquals(clone, info); + clone = info.toBuilder().dnsName(differentName).build(); + assertNotEquals(clone, info); + clone = info.toBuilder().id(info.id() + 1).build(); + assertNotEquals(clone, info); + clone = info.toBuilder().nameServerSet(info.nameServerSet() + "salt").build(); + assertNotEquals(clone, info); + } + + @Test + public void testSameHashCodeOnEquals() { + int hash = info.hashCode(); + ManagedZoneInfo clone = info.toBuilder().build(); + assertEquals(clone.hashCode(), hash); + } + + @Test + public void testToBuilder() { + assertEquals(info, info.toBuilder().build()); + ManagedZoneInfo partial = ManagedZoneInfo.builder(NAME).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ManagedZoneInfo.builder(ID).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ManagedZoneInfo.builder(NAME).description(DESCRIPTION).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ManagedZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ManagedZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); + assertEquals(partial, partial.toBuilder().build()); + List nameServers = new LinkedList<>(); + nameServers.add(NS1); + partial = ManagedZoneInfo.builder(NAME).nameServers(nameServers).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ManagedZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); + assertEquals(partial, partial.toBuilder().build()); + } + + @Test + public void testToAndFromPb() { + assertEquals(info, ManagedZoneInfo.fromPb(info.toPb())); + ManagedZoneInfo partial = ManagedZoneInfo.builder(NAME).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + partial = ManagedZoneInfo.builder(ID).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + partial = ManagedZoneInfo.builder(NAME).description(DESCRIPTION).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + partial = ManagedZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + partial = ManagedZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + List nameServers = new LinkedList<>(); + nameServers.add(NS1); + partial = ManagedZoneInfo.builder(NAME).nameServers(nameServers).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + partial = ManagedZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); + assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + } + + @Test + public void testClearNameServers() { + ManagedZoneInfo clone = info.toBuilder().build(); + assertFalse(clone.nameServers().isEmpty()); + clone = clone.toBuilder().clearNameServers().build(); + assertTrue(clone.nameServers().isEmpty()); + clone.toPb(); // test that this is allowed + } +} From c95c3aaa0c514ba573f29ee8d19a7619a0bf0e1c Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 22 Jan 2016 18:38:10 -0800 Subject: [PATCH 10/74] Implemented comments by @aozarov. --- .../google/gcloud/dns/ManagedZoneInfo.java | 65 ++++++++----------- .../gcloud/dns/ManagedZoneInfoTest.java | 43 ++++++------ 2 files changed, 49 insertions(+), 59 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java index e5b50b3e6669..191d41967124 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java @@ -16,11 +16,11 @@ package com.google.gcloud.dns; -import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; @@ -32,15 +32,16 @@ import java.util.Objects; /** - * This class is a container for the managed zone metainformation. Managed zone is a resource that - * represents a DNS zone hosted by the Cloud DNS service. See Google - * Cloud DNS documentation for more information. + * A {@code ManagedZone} represents a DNS zone hosted by the Google Cloud DNS service. A zone is a + * subtree of the DNS namespace under one administrative responsibility. See Google Cloud DNS documentation for + * more information. */ public class ManagedZoneInfo implements Serializable { private static final long serialVersionUID = 201601191647L; private final String name; - private final Long id; + private final BigInteger id; private final Long creationTimeMillis; private final String dnsName; private final String description; @@ -52,17 +53,21 @@ public class ManagedZoneInfo implements Serializable { */ public static class Builder { private String name; - private Long id; + private BigInteger id; private Long creationTimeMillis; private String dnsName; private String description; private String nameServerSet; private List nameServers = new LinkedList<>(); + /** + * Returns an empty builder for {@code ManagedZoneInfo}. We use it internally in {@code + * toPb()}. + */ private Builder() { } - private Builder(Long id) { + private Builder(BigInteger id) { this.id = checkNotNull(id); } @@ -70,7 +75,7 @@ private Builder(String name) { this.name = checkNotNull(name); } - private Builder(String name, Long id) { + private Builder(String name, BigInteger id) { this.name = checkNotNull(name); this.id = checkNotNull(id); } @@ -99,7 +104,7 @@ public Builder name(String name) { /** * Sets an id for the managed zone which is assigned to the managed zone by the server. */ - public Builder id(long id) { + Builder id(BigInteger id) { this.id = id; return this; } @@ -108,7 +113,6 @@ public Builder id(long id) { * Sets the time when this managed zone was created. */ Builder creationTimeMillis(long creationTimeMillis) { - checkArgument(creationTimeMillis >= 0, "The timestamp cannot be negative."); this.creationTimeMillis = creationTimeMillis; return this; } @@ -123,8 +127,7 @@ public Builder dnsName(String dnsName) { /** * Sets a mandatory description for this managed zone. The value is a string of at most 1024 - * characters (this limit is posed by Google Cloud DNS; gcloud-java does not enforce the limit) - * which has no effect on the managed zone's function. + * characters which has no effect on the managed zone's function. */ public Builder description(String description) { this.description = checkNotNull(description); @@ -133,7 +136,8 @@ public Builder description(String description) { /** * Optionally specifies the NameServerSet for this managed zone. A NameServerSet is a set of DNS - * name servers that all host the same ManagedZones. + * name servers that all host the same ManagedZones. Most users will not need to specify this + * value. */ public Builder nameServerSet(String nameServerSet) { // todo(mderka) add more to the doc when questions are answered by the service owner @@ -146,20 +150,13 @@ public Builder nameServerSet(String nameServerSet) { * provided by Google Cloud DNS and is read only. */ Builder nameServers(List nameServers) { - this.nameServers.addAll(checkNotNull(nameServers)); + checkNotNull(nameServers); + this.nameServers = Lists.newLinkedList(nameServers); return this; } /** - * Removes all the nameservers from the list. - */ - Builder clearNameServers() { - this.nameServers.clear(); - return this; - } - - /** - * Builds the instance of ManagedZoneInfo based on the information set here. + * Builds the instance of {@code ManagedZoneInfo} based on the information set by this builder. */ public ManagedZoneInfo build() { return new ManagedZoneInfo(this); @@ -186,24 +183,17 @@ public static Builder builder(String name) { /** * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code id}. */ - public static Builder builder(Long id) { + public static Builder builder(BigInteger id) { return new Builder(id); } /** * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code name} and {@code id}. */ - public static Builder builder(String name, Long id) { + public static Builder builder(String name, BigInteger id) { return new Builder(name, id); } - /** - * Returns an empty builder for {@code ManagedZoneInfo}. We use it internally in {@code toPb()}. - */ - private static Builder builder() { - return new Builder(); - } - /** * Returns the user-defined name of the managed zone. */ @@ -214,7 +204,7 @@ public String name() { /** * Returns the read-only managed zone id assigned by the server. */ - public Long id() { + public BigInteger id() { return id; } @@ -233,8 +223,7 @@ public String dnsName() { } /** - * Returns the description of this managed zone. This is at most 1024 long mandatory string - * provided by the user. + * Returns the description of this managed zone. */ public String description() { return description; @@ -270,7 +259,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { pb.setDescription(this.description()); pb.setDnsName(this.dnsName()); if (this.id() != null) { - pb.setId(BigInteger.valueOf(this.id())); + pb.setId(this.id()); } pb.setName(this.name()); pb.setNameServers(this.nameServers()); @@ -284,7 +273,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { } static ManagedZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { - Builder b = builder(); + Builder b = new Builder(); if (pb.getDescription() != null) { b.description(pb.getDescription()); } @@ -292,7 +281,7 @@ static ManagedZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) b.dnsName(pb.getDnsName()); } if (pb.getId() != null) { - b.id(pb.getId().longValue()); + b.id(pb.getId()); } if (pb.getName() != null) { b.name(pb.getName()); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java index 6516c7577d2f..89c9426f5b81 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java @@ -17,24 +17,23 @@ package com.google.gcloud.dns; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.google.common.collect.Lists; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; +import java.math.BigInteger; import java.util.LinkedList; import java.util.List; public class ManagedZoneInfoTest { private static final String NAME = "mz-example.com"; - private static final Long ID = 123L; + private static final BigInteger ID = BigInteger.valueOf(123L); private static final Long CREATION_TIME_MILLIS = 1123468321321L; private static final String DNS_NAME = "example.com."; private static final String DESCRIPTION = "description for the zone"; @@ -42,15 +41,14 @@ public class ManagedZoneInfoTest { private static final String NS1 = "name server 1"; private static final String NS2 = "name server 2"; private static final String NS3 = "name server 3"; - private static List nameServers = new LinkedList<>(); - private static ManagedZoneInfo info; + private List nameServers = new LinkedList<>(); + private ManagedZoneInfo info; - @BeforeClass - public static void setUp() { + @Before + public void setUp() { nameServers.add(NS1); nameServers.add(NS2); nameServers.add(NS3); - assertEquals(3, nameServers.size()); info = ManagedZoneInfo.builder(NAME, ID) .creationTimeMillis(CREATION_TIME_MILLIS) .dnsName(DNS_NAME) @@ -58,7 +56,6 @@ public static void setUp() { .nameServerSet(NAME_SERVER_SET) .nameServers(nameServers) .build(); - System.out.println(info); } @Test @@ -105,12 +102,7 @@ public void testBuilder() { @Test public void testValidCreationTime() { - try { - ManagedZoneInfo.builder(NAME).creationTimeMillis(-1); - fail("A negative value is not acceptable for creation time."); - } catch (IllegalArgumentException e) { - // expected - } + ManagedZoneInfo.builder(NAME).creationTimeMillis(-1); ManagedZoneInfo.builder(NAME).creationTimeMillis(0); ManagedZoneInfo.builder(NAME).creationTimeMillis(Long.MAX_VALUE); } @@ -132,7 +124,7 @@ public void testEqualsAndNotEquals() { assertNotEquals(clone, info); clone = info.toBuilder().dnsName(differentName).build(); assertNotEquals(clone, info); - clone = info.toBuilder().id(info.id() + 1).build(); + clone = info.toBuilder().id(info.id().add(BigInteger.ONE)).build(); assertNotEquals(clone, info); clone = info.toBuilder().nameServerSet(info.nameServerSet() + "salt").build(); assertNotEquals(clone, info); @@ -188,11 +180,20 @@ public void testToAndFromPb() { } @Test - public void testClearNameServers() { - ManagedZoneInfo clone = info.toBuilder().build(); - assertFalse(clone.nameServers().isEmpty()); - clone = clone.toBuilder().clearNameServers().build(); + public void testEmptyNameServers() { + ManagedZoneInfo clone = info.toBuilder().nameServers(new LinkedList()).build(); assertTrue(clone.nameServers().isEmpty()); clone.toPb(); // test that this is allowed } + + @Test + public void testDateParsing() { + com.google.api.services.dns.model.ManagedZone pb = + info.toPb(); + pb.setCreationTime("2016-01-19T18:00:12.854Z"); // a real value obtained from Google Cloud DNS + ManagedZoneInfo mz = ManagedZoneInfo.fromPb(pb); // parses the string timestamp to millis + com.google.api.services.dns.model.ManagedZone pbClone = mz.toPb(); // converts it back to string + assertEquals(pb, pbClone); + assertEquals(pb.getCreationTime(), pbClone.getCreationTime()); + } } From dacea19f586e0ae5f344da65f4ebc5c248818288 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 25 Jan 2016 09:06:33 -0800 Subject: [PATCH 11/74] Another round of comments from @aozarov. --- .../google/gcloud/dns/ManagedZoneInfo.java | 1 + .../com/google/gcloud/dns/DnsRecordTest.java | 10 +- .../gcloud/dns/ManagedZoneInfoTest.java | 100 ++++++++---------- 3 files changed, 48 insertions(+), 63 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java index 191d41967124..d27e134ad908 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java @@ -318,6 +318,7 @@ public String toString() { .add("dnsName", dnsName()) .add("nameServerSet", nameServerSet()) .add("nameServers", nameServers()) + .add("creationTimeMillis", creationTimeMillis()) .toString(); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 43ced20cf207..412aa2ce08ad 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -72,16 +72,16 @@ public void testValidTtl() { @Test public void testEqualsAndNotEquals() { DnsRecord clone = record.toBuilder().build(); - assertEquals(clone, record); + assertEquals(record, clone); clone = record.toBuilder().addRecord("another record").build(); - assertNotEquals(clone, record); + assertNotEquals(record, clone); String differentName = "totally different name"; clone = record.toBuilder().name(differentName).build(); - assertNotEquals(clone, record); + assertNotEquals(record, clone); clone = record.toBuilder().ttl(record.ttl() + 1).build(); - assertNotEquals(clone, record); + assertNotEquals(record, clone); clone = record.toBuilder().type(DnsRecord.Type.TXT).build(); - assertNotEquals(clone, record); + assertNotEquals(record, clone); } @Test diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java index 89c9426f5b81..936164c81723 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java @@ -21,9 +21,9 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.junit.Before; import org.junit.Test; import java.math.BigInteger; @@ -41,22 +41,14 @@ public class ManagedZoneInfoTest { private static final String NS1 = "name server 1"; private static final String NS2 = "name server 2"; private static final String NS3 = "name server 3"; - private List nameServers = new LinkedList<>(); - private ManagedZoneInfo info; - - @Before - public void setUp() { - nameServers.add(NS1); - nameServers.add(NS2); - nameServers.add(NS3); - info = ManagedZoneInfo.builder(NAME, ID) - .creationTimeMillis(CREATION_TIME_MILLIS) - .dnsName(DNS_NAME) - .description(DESCRIPTION) - .nameServerSet(NAME_SERVER_SET) - .nameServers(nameServers) - .build(); - } + private static final List NAME_SERVERS = ImmutableList.of(NS1, NS2, NS3); + private static final ManagedZoneInfo INFO = ManagedZoneInfo.builder(NAME, ID) + .creationTimeMillis(CREATION_TIME_MILLIS) + .dnsName(DNS_NAME) + .description(DESCRIPTION) + .nameServerSet(NAME_SERVER_SET) + .nameServers(NAME_SERVERS) + .build(); @Test public void testDefaultBuilders() { @@ -88,58 +80,51 @@ public void testDefaultBuilders() { @Test public void testBuilder() { - assertEquals(3, info.nameServers().size()); - assertEquals(NS1, info.nameServers().get(0)); - assertEquals(NS2, info.nameServers().get(1)); - assertEquals(NS3, info.nameServers().get(2)); - assertEquals(NAME, info.name()); - assertEquals(ID, info.id()); - assertEquals(CREATION_TIME_MILLIS, info.creationTimeMillis()); - assertEquals(NAME_SERVER_SET, info.nameServerSet()); - assertEquals(DESCRIPTION, info.description()); - assertEquals(DNS_NAME, info.dnsName()); - } - - @Test - public void testValidCreationTime() { - ManagedZoneInfo.builder(NAME).creationTimeMillis(-1); - ManagedZoneInfo.builder(NAME).creationTimeMillis(0); - ManagedZoneInfo.builder(NAME).creationTimeMillis(Long.MAX_VALUE); + assertEquals(3, INFO.nameServers().size()); + assertEquals(NS1, INFO.nameServers().get(0)); + assertEquals(NS2, INFO.nameServers().get(1)); + assertEquals(NS3, INFO.nameServers().get(2)); + assertEquals(NAME, INFO.name()); + assertEquals(ID, INFO.id()); + assertEquals(CREATION_TIME_MILLIS, INFO.creationTimeMillis()); + assertEquals(NAME_SERVER_SET, INFO.nameServerSet()); + assertEquals(DESCRIPTION, INFO.description()); + assertEquals(DNS_NAME, INFO.dnsName()); } @Test public void testEqualsAndNotEquals() { - ManagedZoneInfo clone = info.toBuilder().build(); - assertEquals(clone, info); - List moreServers = Lists.newLinkedList(nameServers); + ManagedZoneInfo clone = INFO.toBuilder().build(); + assertEquals(INFO, clone); + List moreServers = Lists.newLinkedList(NAME_SERVERS); moreServers.add(NS1); - clone = info.toBuilder().nameServers(moreServers).build(); - assertNotEquals(clone, info); + clone = INFO.toBuilder().nameServers(moreServers).build(); + assertNotEquals(INFO, clone); String differentName = "totally different name"; - clone = info.toBuilder().name(differentName).build(); - assertNotEquals(clone, info); - clone = info.toBuilder().creationTimeMillis(info.creationTimeMillis() + 1).build(); - assertNotEquals(clone, info); - clone = info.toBuilder().description(info.description() + "aaaa").build(); - assertNotEquals(clone, info); - clone = info.toBuilder().dnsName(differentName).build(); - assertNotEquals(clone, info); - clone = info.toBuilder().id(info.id().add(BigInteger.ONE)).build(); - assertNotEquals(clone, info); - clone = info.toBuilder().nameServerSet(info.nameServerSet() + "salt").build(); - assertNotEquals(clone, info); + clone = INFO.toBuilder().name(differentName).build(); + assertNotEquals(INFO, clone); + clone = INFO.toBuilder().creationTimeMillis(INFO.creationTimeMillis() + 1).build(); + assertNotEquals(INFO, clone); + clone = INFO.toBuilder().description(INFO.description() + "aaaa").build(); + assertNotEquals(INFO, clone); + clone = INFO.toBuilder().dnsName(differentName).build(); + assertNotEquals(INFO, clone); + clone = INFO.toBuilder().id(INFO.id().add(BigInteger.ONE)).build(); + assertNotEquals(INFO, clone); + clone = INFO.toBuilder().nameServerSet(INFO.nameServerSet() + "salt").build(); + assertNotEquals(INFO, clone); } @Test public void testSameHashCodeOnEquals() { - int hash = info.hashCode(); - ManagedZoneInfo clone = info.toBuilder().build(); + int hash = INFO.hashCode(); + ManagedZoneInfo clone = INFO.toBuilder().build(); assertEquals(clone.hashCode(), hash); } @Test public void testToBuilder() { - assertEquals(info, info.toBuilder().build()); + assertEquals(INFO, INFO.toBuilder().build()); ManagedZoneInfo partial = ManagedZoneInfo.builder(NAME).build(); assertEquals(partial, partial.toBuilder().build()); partial = ManagedZoneInfo.builder(ID).build(); @@ -160,7 +145,7 @@ public void testToBuilder() { @Test public void testToAndFromPb() { - assertEquals(info, ManagedZoneInfo.fromPb(info.toPb())); + assertEquals(INFO, ManagedZoneInfo.fromPb(INFO.toPb())); ManagedZoneInfo partial = ManagedZoneInfo.builder(NAME).build(); assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); partial = ManagedZoneInfo.builder(ID).build(); @@ -181,15 +166,14 @@ public void testToAndFromPb() { @Test public void testEmptyNameServers() { - ManagedZoneInfo clone = info.toBuilder().nameServers(new LinkedList()).build(); + ManagedZoneInfo clone = INFO.toBuilder().nameServers(new LinkedList()).build(); assertTrue(clone.nameServers().isEmpty()); clone.toPb(); // test that this is allowed } @Test public void testDateParsing() { - com.google.api.services.dns.model.ManagedZone pb = - info.toPb(); + com.google.api.services.dns.model.ManagedZone pb = INFO.toPb(); pb.setCreationTime("2016-01-19T18:00:12.854Z"); // a real value obtained from Google Cloud DNS ManagedZoneInfo mz = ManagedZoneInfo.fromPb(pb); // parses the string timestamp to millis com.google.api.services.dns.model.ManagedZone pbClone = mz.toPb(); // converts it back to string From 273b4418df7ed3d1dae00f6f66228c1dcee3b1ac Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 25 Jan 2016 17:11:34 -0800 Subject: [PATCH 12/74] Implemented ChangeRequest. --- .../com/google/gcloud/dns/ChangeRequest.java | 340 ++++++++++++++++++ .../com/google/gcloud/dns/DnsRecordTest.java | 1 + 2 files changed, 341 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java new file mode 100644 index 000000000000..40c6ff0ad151 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -0,0 +1,340 @@ +/* + * 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.dns; + +import com.google.common.base.MoreObjects; +import com.google.common.collect.Lists; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * A class representing a change. A change is an atomic update to a collection of {@link DnsRecord}s + * within a {@code ManagedZone}. + * + * @see Google Cloud DNS documentation + */ +public class ChangeRequest implements Serializable { + + private static final long serialVersionUID = 201601251649L; + private final List additions; + private final List deletions; + private final String id; + private final Long startTimeMillis; + private final Status status; + + /** + * This enumerates the possible states of a {@code ChangeRequest}. + * + * @see Google Cloud DNS + * documentation + */ + public enum Status { + PENDING("pending"), + DONE("done"); + + private final String status; + + Status(String status) { + this.status = status; + } + + static Status translate(String status) { + if ("pending".equals(status)) { + return PENDING; + } else if ("done".equals(status)) { + return DONE; + } else { + throw new IllegalArgumentException("Such a status is unknown."); + } + } + } + + /** + * A builder for {@code ChangeRequest}s. + */ + public static class Builder { + + private List additions = new LinkedList<>(); + private List deletions = new LinkedList<>(); + private String id; + private Long startTimeMillis; + private Status status; + + private Builder(ChangeRequest cr) { + this.additions = Lists.newLinkedList(cr.additions()); + this.deletions = Lists.newLinkedList(cr.deletions()); + this.id = cr.id(); + this.startTimeMillis = cr.startTimeMillis(); + this.status = cr.status(); + } + + private Builder() { + } + + /** + * Sets a collection of {@link DnsRecord}s which are to be added to the zone upon executing this + * {@code ChangeRequest}. + */ + public Builder additions(List additions) { + this.additions = Lists.newLinkedList(checkNotNull(additions)); + return this; + } + + /** + * Adds a {@link DnsRecord} which to be added to the zone upon executing this + * {@code ChangeRequest}. + */ + public Builder add(DnsRecord record) { + this.additions.add(checkNotNull(record)); + return this; + } + + /** + * Adds a {@link DnsRecord} which to be deleted to the zone upon executing this + * {@code ChangeRequest}. + */ + public Builder delete(DnsRecord record) { + this.deletions.add(checkNotNull(record)); + return this; + } + + /** + * Clears the collection of {@link DnsRecord}s which are to be added to the zone upon executing + * this {@code ChangeRequest}. + */ + public Builder clearAdditions() { + this.additions.clear(); + return this; + } + + /** + * Clears the collection of {@link DnsRecord}s which are to be deleted from the zone upon + * executing this {@code ChangeRequest}. + */ + public Builder clearDeletions() { + this.deletions.clear(); + return this; + } + + /** + * Removes a single {@link DnsRecord} from the collection of of records to be + * added to the zone upon executing this {@code ChangeRequest}. + */ + public Builder removeAddition(DnsRecord record) { + this.additions.remove(record); + return this; + } + + /** + * Removes a single {@link DnsRecord} from the collection of of records to be + * deleted from the zone upon executing this {@code ChangeRequest}. + */ + public Builder removeDeletion(DnsRecord record) { + this.deletions.remove(record); + return this; + } + + /** + * Sets a collection of {@link DnsRecord}s which are to be deleted from the zone upon executing + * this {@code ChangeRequest}. + */ + public Builder deletions(List deletions) { + this.deletions = Lists.newLinkedList(checkNotNull(deletions)); + return this; + } + + /** + * Associates a server-assigned id to this {@code ChangeRequest}. + */ + Builder id(String id) { + this.id = checkNotNull(id); + return this; + } + + /** + * Sets the time when this {@code ChangeRequest} was started by a server. + */ + Builder startTimeMillis(long startTimeMillis) { + this.startTimeMillis = startTimeMillis; + return this; + } + + /** + * Sets the current status of this {@code ChangeRequest}. + */ + Builder status(Status status) { + this.status = checkNotNull(status); + return this; + } + + /** + * Creates a {@code ChangeRequest} instance populated by the values associated with this + * builder. + */ + public ChangeRequest build() { + return new ChangeRequest(this); + } + } + + private ChangeRequest(Builder builder) { + this.additions = builder.additions; + this.deletions = builder.deletions; + this.id = builder.id; + this.startTimeMillis = builder.startTimeMillis; + this.status = builder.status; + } + + /** + * Returns an empty builder for the {@code ChangeRequest} class. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Creates a builder populated with values of this {@code ChangeRequest}. + */ + public Builder toBuilder() { + return new Builder(this); + } + + /** + * Returns the list of {@link DnsRecord}s to be added to the zone upon executing this {@code + * ChangeRequest}. + */ + public List additions() { + return additions; + } + + /** + * Returns the list of {@link DnsRecord}s to be deleted from the zone upon executing this {@code + * ChangeRequest}. + */ + public List deletions() { + return deletions; + } + + /** + * Returns the id assigned to this {@code ChangeRequest} by the server. + */ + public String id() { + return id; + } + + /** + * Returns the time when this {@code ChangeRequest} was started by the server. + */ + public Long startTimeMillis() { + return startTimeMillis; + } + + /** + * Returns the status of this {@code ChangeRequest}. + */ + public Status status() { + return status; + } + + com.google.api.services.dns.model.Change toPb() { + com.google.api.services.dns.model.Change pb = + new com.google.api.services.dns.model.Change(); + // set id + if (id() != null) { + pb.setId(id()); + } + // set timestamp + if (startTimeMillis() != null) { + pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(startTimeMillis())); + } + // set status + if (status() != null) { + pb.setStatus(status().status); + } + // set a list of additions + if (additions() != null) { + LinkedList additionsPb = + new LinkedList<>(); + for (DnsRecord addition : additions()) { + additionsPb.add(addition.toPb()); + } + pb.setAdditions(additionsPb); + } + // set a list of deletions + if (deletions() != null) { + LinkedList deletionsPb = + new LinkedList<>(); + for (DnsRecord deletion : deletions()) { + deletionsPb.add(deletion.toPb()); + } + pb.setDeletions(deletionsPb); + } + return pb; + } + + static ChangeRequest fromPb(com.google.api.services.dns.model.Change pb) { + Builder b = builder(); + if (pb.getId() != null) { + b.id(pb.getId()); + } + if (pb.getStartTime() != null) { + b.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); + } + if (pb.getStatus() != null) { + b.status(ChangeRequest.Status.translate(pb.getStatus())); + } + if (pb.getDeletions() != null) { + for (com.google.api.services.dns.model.ResourceRecordSet deletion : pb.getDeletions()) { + b.delete(DnsRecord.fromPb(deletion)); + } + } + if (pb.getAdditions() != null) { + for (com.google.api.services.dns.model.ResourceRecordSet addition : pb.getAdditions()) { + b.add(DnsRecord.fromPb(addition)); + } + } + return b.build(); + } + + @Override + public boolean equals(Object o) { + return (o instanceof ChangeRequest) && this.toPb().equals(((ChangeRequest) o).toPb()); + } + + @Override + public int hashCode() { + return Objects.hash(additions, deletions, id, startTimeMillis, status); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("additions", additions) + .add("deletions", deletions) + .add("id", id) + .add("startTimeMillis", startTimeMillis) + .add("status", status) + .toString(); + } +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 43ced20cf207..312cf564cbf2 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.google.gcloud.dns; import static org.junit.Assert.assertEquals; From 35cfd616b7294419d16aed9232fe40bb94321884 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 26 Jan 2016 14:31:39 -0800 Subject: [PATCH 13/74] Added test for ChangeRequest. --- .../google/gcloud/dns/ChangeRequestTest.java | 231 ++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java new file mode 100644 index 000000000000..da8006da8b51 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java @@ -0,0 +1,231 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.common.collect.ImmutableList; + +import org.junit.Test; + +import java.util.List; + +public class ChangeRequestTest { + + private static final String ID = "cr-id-1"; + private static final Long START_TIME_MILLIS = 12334567890L; + private static final ChangeRequest.Status STATUS = ChangeRequest.Status.PENDING; + private static final String NAME1 = "dns1"; + private static final DnsRecord.Type TYPE1 = DnsRecord.Type.A; + private static final String NAME2 = "dns2"; + private static final DnsRecord.Type TYPE2 = DnsRecord.Type.AAAA; + private static final String NAME3 = "dns3"; + private static final DnsRecord.Type TYPE3 = DnsRecord.Type.MX; + private static final DnsRecord RECORD1 = DnsRecord.builder(NAME1, TYPE1).build(); + private static final DnsRecord RECORD2 = DnsRecord.builder(NAME2, TYPE2).build(); + private static final DnsRecord RECORD3 = DnsRecord.builder(NAME3, TYPE3).build(); + private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); + private static final List DELETIONS = ImmutableList.of(RECORD3); + private static final ChangeRequest CHANGE = ChangeRequest.builder() + .add(RECORD1) + .add(RECORD2) + .delete(RECORD3) + .startTimeMillis(START_TIME_MILLIS) + .status(STATUS) + .id(ID) + .build(); + + @Test + public void testEmptyBuilder() { + ChangeRequest cr = ChangeRequest.builder().build(); + assertNotNull(cr.deletions()); + assertTrue(cr.deletions().isEmpty()); + assertNotNull(cr.additions()); + assertTrue(cr.additions().isEmpty()); + } + + @Test + public void testBuilder() { + assertEquals(ID, CHANGE.id()); + assertEquals(STATUS, CHANGE.status()); + assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); + assertEquals(ADDITIONS, CHANGE.additions()); + assertEquals(DELETIONS, CHANGE.deletions()); + List recordList = ImmutableList.of(RECORD1); + ChangeRequest another = CHANGE.toBuilder().additions(recordList).build(); + assertEquals(recordList, another.additions()); + assertEquals(CHANGE.deletions(), another.deletions()); + another = CHANGE.toBuilder().deletions(recordList).build(); + assertEquals(recordList, another.deletions()); + assertEquals(CHANGE.additions(), another.additions()); + } + + @Test + public void testEqualsAndNotEquals() { + ChangeRequest clone = CHANGE.toBuilder().build(); + assertEquals(CHANGE, clone); + clone = ChangeRequest.fromPb(CHANGE.toPb()); + assertEquals(CHANGE, clone); + clone = CHANGE.toBuilder().id("some-other-id").build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().startTimeMillis(CHANGE.startTimeMillis() + 1).build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().add(RECORD3).build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().delete(RECORD1).build(); + assertNotEquals(CHANGE, clone); + ChangeRequest empty = ChangeRequest.builder().build(); + assertNotEquals(CHANGE, empty); + assertEquals(empty, ChangeRequest.builder().build()); + } + + @Test + public void testSameHashCodeOnEquals() { + ChangeRequest clone = CHANGE.toBuilder().build(); + assertEquals(CHANGE, clone); + assertEquals(CHANGE.hashCode(), clone.hashCode()); + ChangeRequest empty = ChangeRequest.builder().build(); + assertEquals(empty.hashCode(), ChangeRequest.builder().build().hashCode()); + } + + @Test + public void testToAndFromPb() { + assertEquals(CHANGE, ChangeRequest.fromPb(CHANGE.toPb())); + ChangeRequest partial = ChangeRequest.builder().build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().id(ID).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().add(RECORD1).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().delete(RECORD1).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().additions(ADDITIONS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().deletions(DELETIONS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().status(STATUS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + } + + @Test + public void testToBuilder() { + assertEquals(CHANGE, CHANGE.toBuilder().build()); + ChangeRequest partial = ChangeRequest.builder().build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().id(ID).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().add(RECORD1).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().delete(RECORD1).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().additions(ADDITIONS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().deletions(DELETIONS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().status(STATUS).build(); + assertEquals(partial, partial.toBuilder().build()); + } + + @Test + public void testClearAdditions() { + ChangeRequest clone = CHANGE.toBuilder().clearAdditions().build(); + assertTrue(clone.additions().isEmpty()); + assertFalse(clone.deletions().isEmpty()); + } + + @Test + public void testAddAddition() { + try { + CHANGE.toBuilder().add(null).build(); + fail("Should not be able to add null DnsRecord."); + } catch (NullPointerException e) { + // expected + } + ChangeRequest clone = CHANGE.toBuilder().add(RECORD1).build(); + assertEquals(CHANGE.additions().size() + 1, clone.additions().size()); + } + + @Test + public void testAddDeletion() { + try { + ChangeRequest clone = CHANGE.toBuilder().delete(null).build(); + fail("Should not be able to delete null DnsRecord."); + } catch (NullPointerException e) { + // expected + } + ChangeRequest clone = CHANGE.toBuilder().delete(RECORD1).build(); + assertEquals(CHANGE.deletions().size() + 1, clone.deletions().size()); + } + + @Test + public void testClearDeletions() { + ChangeRequest clone = CHANGE.toBuilder().clearDeletions().build(); + assertTrue(clone.deletions().isEmpty()); + assertFalse(clone.additions().isEmpty()); + } + + @Test + public void testRemoveAddition() { + ChangeRequest clone = CHANGE.toBuilder().removeAddition(RECORD1).build(); + assertTrue(clone.additions().contains(RECORD2)); + assertFalse(clone.additions().contains(RECORD1)); + assertTrue(clone.deletions().contains(RECORD3)); + clone = CHANGE.toBuilder().removeAddition(RECORD2).removeAddition(RECORD1).build(); + assertFalse(clone.additions().contains(RECORD2)); + assertFalse(clone.additions().contains(RECORD1)); + assertTrue(clone.additions().isEmpty()); + assertTrue(clone.deletions().contains(RECORD3)); + } + + @Test + public void testRemoveDeletion() { + ChangeRequest clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); + assertFalse(clone.deletions().contains(RECORD3)); + assertTrue(clone.deletions().isEmpty()); + } + + @Test + public void testDateParsing() { + String startTime = "2016-01-26T18:33:43.512Z"; // obtained from service + com.google.api.services.dns.model.Change change = CHANGE.toPb().setStartTime(startTime); + ChangeRequest converted = ChangeRequest.fromPb(change); + assertNotNull(converted.startTimeMillis()); + assertEquals(change, converted.toPb()); + assertEquals(change.getStartTime(), converted.toPb().getStartTime()); + } + + @Test + public void testStatusTranslation() { + assertEquals(ChangeRequest.Status.DONE, ChangeRequest.Status.translate("done")); + assertEquals(ChangeRequest.Status.PENDING, ChangeRequest.Status.translate("pending")); + try { + ChangeRequest.Status.translate("another"); + fail("Such a status does not exist."); + } catch (IllegalArgumentException e) { + // expected + } + } +} From 6f9e1c09b831b39def386076826eecf20daa1bc2 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 26 Jan 2016 17:15:14 -0800 Subject: [PATCH 14/74] Implements comments from @ajkannan and @aozarov. --- .../com/google/gcloud/dns/ChangeRequest.java | 126 ++++++++---------- .../java/com/google/gcloud/dns/DnsRecord.java | 8 +- .../google/gcloud/dns/ChangeRequestTest.java | 17 +-- .../com/google/gcloud/dns/DnsRecordTest.java | 2 +- 4 files changed, 62 insertions(+), 91 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index 40c6ff0ad151..5ed03b1ea071 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -16,7 +16,12 @@ package com.google.gcloud.dns; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.base.Function; import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.joda.time.DateTime; @@ -27,17 +32,29 @@ import java.util.List; import java.util.Objects; -import static com.google.common.base.Preconditions.checkNotNull; - /** - * A class representing a change. A change is an atomic update to a collection of {@link DnsRecord}s - * within a {@code ManagedZone}. + * A class representing an atomic update to a collection of {@link DnsRecord}s within a {@code + * ManagedZone}. * * @see Google Cloud DNS documentation */ public class ChangeRequest implements Serializable { - private static final long serialVersionUID = 201601251649L; + private static final Function FROM_PB_FUNCTION = + new Function() { + @Override + public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { + return DnsRecord.fromPb(pb); + } + }; + private static final Function TO_PB_FUNCTION = + new Function() { + @Override + public com.google.api.services.dns.model.ResourceRecordSet apply(DnsRecord error) { + return error.toPb(); + } + }; + private static final long serialVersionUID = -8703939628990291682L; private final List additions; private final List deletions; private final String id; @@ -51,24 +68,8 @@ public class ChangeRequest implements Serializable { * documentation */ public enum Status { - PENDING("pending"), - DONE("done"); - - private final String status; - - Status(String status) { - this.status = status; - } - - static Status translate(String status) { - if ("pending".equals(status)) { - return PENDING; - } else if ("done".equals(status)) { - return DONE; - } else { - throw new IllegalArgumentException("Such a status is unknown."); - } - } + PENDING, + DONE } /** @@ -101,10 +102,19 @@ public Builder additions(List additions) { this.additions = Lists.newLinkedList(checkNotNull(additions)); return this; } + + /** + * Sets a collection of {@link DnsRecord}s which are to be deleted from the zone upon executing + * this {@code ChangeRequest}. + */ + public Builder deletions(List deletions) { + this.deletions = Lists.newLinkedList(checkNotNull(deletions)); + return this; + } /** - * Adds a {@link DnsRecord} which to be added to the zone upon executing this - * {@code ChangeRequest}. + * Adds a {@link DnsRecord} to be added to the zone upon executing this {@code + * ChangeRequest}. */ public Builder add(DnsRecord record) { this.additions.add(checkNotNull(record)); @@ -112,7 +122,7 @@ public Builder add(DnsRecord record) { } /** - * Adds a {@link DnsRecord} which to be deleted to the zone upon executing this + * Adds a {@link DnsRecord} to be deleted to the zone upon executing this * {@code ChangeRequest}. */ public Builder delete(DnsRecord record) { @@ -139,7 +149,7 @@ public Builder clearDeletions() { } /** - * Removes a single {@link DnsRecord} from the collection of of records to be + * Removes a single {@link DnsRecord} from the collection of records to be * added to the zone upon executing this {@code ChangeRequest}. */ public Builder removeAddition(DnsRecord record) { @@ -148,7 +158,7 @@ public Builder removeAddition(DnsRecord record) { } /** - * Removes a single {@link DnsRecord} from the collection of of records to be + * Removes a single {@link DnsRecord} from the collection of records to be * deleted from the zone upon executing this {@code ChangeRequest}. */ public Builder removeDeletion(DnsRecord record) { @@ -156,15 +166,6 @@ public Builder removeDeletion(DnsRecord record) { return this; } - /** - * Sets a collection of {@link DnsRecord}s which are to be deleted from the zone upon executing - * this {@code ChangeRequest}. - */ - public Builder deletions(List deletions) { - this.deletions = Lists.newLinkedList(checkNotNull(deletions)); - return this; - } - /** * Associates a server-assigned id to this {@code ChangeRequest}. */ @@ -199,8 +200,8 @@ public ChangeRequest build() { } private ChangeRequest(Builder builder) { - this.additions = builder.additions; - this.deletions = builder.deletions; + this.additions = ImmutableList.copyOf(builder.additions); + this.deletions = ImmutableList.copyOf(builder.deletions); this.id = builder.id; this.startTimeMillis = builder.startTimeMillis; this.status = builder.status; @@ -221,7 +222,7 @@ public Builder toBuilder() { } /** - * Returns the list of {@link DnsRecord}s to be added to the zone upon executing this {@code + * Returns the list of {@link DnsRecord}s to be added to the zone upon submitting this {@code * ChangeRequest}. */ public List additions() { @@ -229,7 +230,7 @@ public List additions() { } /** - * Returns the list of {@link DnsRecord}s to be deleted from the zone upon executing this {@code + * Returns the list of {@link DnsRecord}s to be deleted from the zone upon submitting this {@code * ChangeRequest}. */ public List deletions() { @@ -270,56 +271,39 @@ com.google.api.services.dns.model.Change toPb() { } // set status if (status() != null) { - pb.setStatus(status().status); + pb.setStatus(status().name().toLowerCase()); } // set a list of additions - if (additions() != null) { - LinkedList additionsPb = - new LinkedList<>(); - for (DnsRecord addition : additions()) { - additionsPb.add(addition.toPb()); - } - pb.setAdditions(additionsPb); - } + pb.setAdditions(Lists.transform(additions(), TO_PB_FUNCTION)); // set a list of deletions - if (deletions() != null) { - LinkedList deletionsPb = - new LinkedList<>(); - for (DnsRecord deletion : deletions()) { - deletionsPb.add(deletion.toPb()); - } - pb.setDeletions(deletionsPb); - } + pb.setDeletions(Lists.transform(deletions(), TO_PB_FUNCTION)); return pb; } static ChangeRequest fromPb(com.google.api.services.dns.model.Change pb) { - Builder b = builder(); + Builder builder = builder(); if (pb.getId() != null) { - b.id(pb.getId()); + builder.id(pb.getId()); } if (pb.getStartTime() != null) { - b.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); + builder.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); } if (pb.getStatus() != null) { - b.status(ChangeRequest.Status.translate(pb.getStatus())); + // we are assuming that status indicated in pb is a lower case version of the enum name + builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); } if (pb.getDeletions() != null) { - for (com.google.api.services.dns.model.ResourceRecordSet deletion : pb.getDeletions()) { - b.delete(DnsRecord.fromPb(deletion)); - } + builder.deletions(Lists.transform(pb.getDeletions(), FROM_PB_FUNCTION)); } if (pb.getAdditions() != null) { - for (com.google.api.services.dns.model.ResourceRecordSet addition : pb.getAdditions()) { - b.add(DnsRecord.fromPb(addition)); - } + builder.additions(Lists.transform(pb.getAdditions(), FROM_PB_FUNCTION)); } - return b.build(); + return builder.build(); } @Override - public boolean equals(Object o) { - return (o instanceof ChangeRequest) && this.toPb().equals(((ChangeRequest) o).toPb()); + public boolean equals(Object other) { + return (other instanceof ChangeRequest) && toPb().equals(((ChangeRequest) other).toPb()); } @Override diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index c41e72a77400..4236d9c1c561 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -273,14 +273,14 @@ com.google.api.services.dns.model.ResourceRecordSet toPb() { } static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) { - Builder b = builder(pb.getName(), Type.valueOf(pb.getType())); + Builder builder = builder(pb.getName(), Type.valueOf(pb.getType())); if (pb.getRrdatas() != null) { - b.records(pb.getRrdatas()); + builder.records(pb.getRrdatas()); } if (pb.getTtl() != null) { - b.ttl(pb.getTtl()); + builder.ttl(pb.getTtl()); } - return b.build(); + return builder.build(); } @Override diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java index da8006da8b51..8b40a4dcff34 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java @@ -159,7 +159,7 @@ public void testClearAdditions() { @Test public void testAddAddition() { try { - CHANGE.toBuilder().add(null).build(); + CHANGE.toBuilder().add(null); fail("Should not be able to add null DnsRecord."); } catch (NullPointerException e) { // expected @@ -171,7 +171,7 @@ public void testAddAddition() { @Test public void testAddDeletion() { try { - ChangeRequest clone = CHANGE.toBuilder().delete(null).build(); + CHANGE.toBuilder().delete(null); fail("Should not be able to delete null DnsRecord."); } catch (NullPointerException e) { // expected @@ -203,7 +203,6 @@ public void testRemoveAddition() { @Test public void testRemoveDeletion() { ChangeRequest clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); - assertFalse(clone.deletions().contains(RECORD3)); assertTrue(clone.deletions().isEmpty()); } @@ -216,16 +215,4 @@ public void testDateParsing() { assertEquals(change, converted.toPb()); assertEquals(change.getStartTime(), converted.toPb().getStartTime()); } - - @Test - public void testStatusTranslation() { - assertEquals(ChangeRequest.Status.DONE, ChangeRequest.Status.translate("done")); - assertEquals(ChangeRequest.Status.PENDING, ChangeRequest.Status.translate("pending")); - try { - ChangeRequest.Status.translate("another"); - fail("Such a status does not exist."); - } catch (IllegalArgumentException e) { - // expected - } - } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 312cf564cbf2..60eb6f033ce0 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -17,9 +17,9 @@ package com.google.gcloud.dns; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.junit.Assert.assertNotEquals; import org.junit.Test; From 9b4ff48b64c2192a42d914a672d9004e59a4b822 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 25 Jan 2016 16:23:48 -0800 Subject: [PATCH 15/74] Added ProjectInfo. --- .../com/google/gcloud/dns/ProjectInfo.java | 284 ++++++++++++++++++ .../google/gcloud/dns/ProjectInfoTest.java | 118 ++++++++ 2 files changed, 402 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java new file mode 100644 index 000000000000..614b9033a18e --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -0,0 +1,284 @@ +/* + * 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.dns; + +import static com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.MoreObjects; + +import java.io.Serializable; +import java.math.BigInteger; +import java.util.Objects; + +/** + * The class that encapsulates information about a project in Google Cloud DNS. A project is a top + * level container for resources including {@link ManagedZone}s. Projects can be created only in the + * APIs console. + * + * @see Google Cloud DNS documentation + */ +public class ProjectInfo implements Serializable { + + private static final long serialVersionUID = 201601251420L; + private final String id; + private final BigInteger number; + private final Quota quota; + + /** + * This class represents quotas assigned to the {@code ProjectInfo}. + * + * @see Google Cloud DNS documentation + */ + public static class Quota { + + private Integer zones; + private Integer resourceRecordsPerRrset; + private Integer rrsetAdditionsPerChange; + private Integer rrsetDeletionsPerChange; + private Integer rrsetsPerManagedZone; + private Integer totalRrdataSizePerChange; + + /** + * Creates an instance of {@code Quota}. + * + * This is the only way of creating an instance of {@code Quota}. As the service does not allow + * for specifying options, quota is an "all-or-nothing object" and we do not need a builder. + */ + Quota(Integer zones, + Integer resourceRecordsPerRrset, + Integer rrsetAdditionsPerChange, + Integer rrsetDeletionsPerChange, + Integer rrsetsPerManagedZone, + Integer totalRrdataSizePerChange) { + this.zones = checkNotNull(zones); + this.resourceRecordsPerRrset = checkNotNull(resourceRecordsPerRrset); + this.rrsetAdditionsPerChange = checkNotNull(rrsetAdditionsPerChange); + this.rrsetDeletionsPerChange = checkNotNull(rrsetDeletionsPerChange); + this.rrsetsPerManagedZone = checkNotNull(rrsetsPerManagedZone); + this.totalRrdataSizePerChange = checkNotNull(totalRrdataSizePerChange); + } + + /** + * Returns the maximum allowed number of managed zones in the project. + */ + public Integer zones() { + return zones; + } + + /** + * Returns the maximum allowed number of records per {@link DnsRecord}. + */ + public Integer resourceRecordsPerRrset() { + return resourceRecordsPerRrset; + } + + /** + * Returns the maximum allowed number of {@link DnsRecord}s to add per {@code ChangesRequest}. + */ + public Integer rrsetAdditionsPerChange() { + return rrsetAdditionsPerChange; + } + + /** + * Returns the maximum allowed number of {@link DnsRecord}s to delete per {@code + * ChangesRequest}. + */ + public Integer rrsetDeletionsPerChange() { + return rrsetDeletionsPerChange; + } + + /** + * Returns the maximum allowed number of {@link DnsRecord}s per {@link ManagedZone} in the + * project. + */ + public Integer rrsetsPerManagedZone() { + return rrsetsPerManagedZone; + } + + /** + * Returns the maximum allowed size for total records in one ChangesRequest in bytes. + */ + public Integer totalRrdataSizePerChange() { + return totalRrdataSizePerChange; + } + + @Override + public boolean equals(Object o) { + return (o instanceof Quota) && this.toPb().equals(((Quota) o).toPb()); + } + + @Override + public int hashCode() { + return Objects.hash(zones, resourceRecordsPerRrset, rrsetAdditionsPerChange, + rrsetDeletionsPerChange, rrsetsPerManagedZone, totalRrdataSizePerChange); + } + + com.google.api.services.dns.model.Quota toPb() { + com.google.api.services.dns.model.Quota pb = new com.google.api.services.dns.model.Quota(); + pb.setManagedZones(zones); + pb.setResourceRecordsPerRrset(resourceRecordsPerRrset); + pb.setRrsetAdditionsPerChange(rrsetAdditionsPerChange); + pb.setRrsetDeletionsPerChange(rrsetDeletionsPerChange); + pb.setRrsetsPerManagedZone(rrsetsPerManagedZone); + pb.setTotalRrdataSizePerChange(totalRrdataSizePerChange); + return pb; + } + + static Quota fromPb(com.google.api.services.dns.model.Quota pb) { + Quota q = new Quota(pb.getManagedZones(), + pb.getResourceRecordsPerRrset(), + pb.getRrsetAdditionsPerChange(), + pb.getRrsetDeletionsPerChange(), + pb.getRrsetsPerManagedZone(), + pb.getTotalRrdataSizePerChange() + ); + return q; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("zones", zones) + .add("resourceRecordsPerRrset", resourceRecordsPerRrset) + .add("rrsetAdditionsPerChange", rrsetAdditionsPerChange) + .add("rrsetDeletionsPerChange", rrsetDeletionsPerChange) + .add("rrsetsPerManagedZone", rrsetsPerManagedZone) + .add("totalRrdataSizePerChange", totalRrdataSizePerChange) + .toString(); + } + } + + /** + * A builder for {@code ProjectInfo}. + */ + static class Builder { + private String id; + private BigInteger number; + private Quota quota; + + private Builder() { + } + + /** + * Sets an id of the project. + */ + Builder id(String id) { + this.id = checkNotNull(id); + return this; + } + + /** + * Sets a number of the project. + */ + Builder number(BigInteger number) { + this.number = checkNotNull(number); + return this; + } + + /** + * Sets quotas assigned to the project. + */ + Builder quota(Quota quota) { + this.quota = checkNotNull(quota); + return this; + } + + /** + * Builds an instance of the {@code ProjectInfo}. + */ + ProjectInfo build() { + return new ProjectInfo(this); + } + } + + private ProjectInfo(Builder b) { + this.id = b.id; + this.number = b.number; + this.quota = b.quota; + } + + /** + * Returns a builder for {@code ProjectInfo}. + */ + static Builder builder() { + return new Builder(); + } + + /** + * Returns the user-assigned unique identifier for the project. + */ + public String id() { + return id; + } + + /** + * Returns the unique numeric identifier for the project. + */ + public BigInteger number() { + return number; + } + + /** + * Returns the {@code Quota} object which contains quotas assigned to this project. + */ + public Quota quota() { + return quota; + } + + com.google.api.services.dns.model.Project toPb() { + com.google.api.services.dns.model.Project pb = new com.google.api.services.dns.model.Project(); + pb.setId(id()); + pb.setNumber(number()); + if (this.quota() != null) { + pb.setQuota(quota().toPb()); + } + return pb; + } + + static ProjectInfo fromPb(com.google.api.services.dns.model.Project pb) { + Builder b = builder(); + if (pb.getId() != null) { + b.id(pb.getId()); + } + if (pb.getNumber() != null) { + b.number(pb.getNumber()); + } + if (pb.getQuota() != null) { + b.quota(Quota.fromPb(pb.getQuota())); + } + return b.build(); + } + + @Override + public boolean equals(Object o) { + return (o instanceof ProjectInfo) && this.toPb().equals(((ProjectInfo) o).toPb()); + } + + @Override + public int hashCode() { + return Objects.hash(id, number, quota); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("id", id) + .add("number", number) + .add("quota", quota) + .toString(); + } +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java new file mode 100644 index 000000000000..2c5e1ffa7100 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java @@ -0,0 +1,118 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import java.math.BigInteger; + +public class ProjectInfoTest { + + private static final String ID = "project-id-123"; + private static final BigInteger NUMBER = new BigInteger("123"); + private static final ProjectInfo.Quota QUOTA = new ProjectInfo.Quota(1, 2, 3, 4, 5, 6); + private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder() + .id(ID).number(NUMBER).quota(QUOTA).build(); + + @Test + public void testBuilder() { + ProjectInfo withId = ProjectInfo.builder().id(ID).build(); + assertEquals(ID, withId.id()); + assertNull(withId.number()); + assertNull(withId.quota()); + ProjectInfo withNumber = ProjectInfo.builder().number(NUMBER).build(); + assertEquals(NUMBER, withNumber.number()); + assertNull(withNumber.quota()); + assertNull(withNumber.id()); + ProjectInfo withQuota = ProjectInfo.builder().quota(QUOTA).build(); + assertEquals(QUOTA, withQuota.quota()); + assertNull(withQuota.id()); + assertNull(withQuota.number()); + assertEquals(QUOTA, PROJECT_INFO.quota()); + assertEquals(NUMBER, PROJECT_INFO.number()); + assertEquals(ID, PROJECT_INFO.id()); + } + + @Test + public void testQuotaConstructor() { + assertEquals(Integer.valueOf(1), QUOTA.zones()); + assertEquals(Integer.valueOf(2), QUOTA.resourceRecordsPerRrset()); + assertEquals(Integer.valueOf(3), QUOTA.rrsetAdditionsPerChange()); + assertEquals(Integer.valueOf(4), QUOTA.rrsetDeletionsPerChange()); + assertEquals(Integer.valueOf(5), QUOTA.rrsetsPerManagedZone()); + assertEquals(Integer.valueOf(6), QUOTA.totalRrdataSizePerChange()); + } + + @Test + public void testEqualsAndNotEqualsQuota() { + ProjectInfo.Quota clone = new ProjectInfo.Quota(6, 5, 4, 3, 2, 1); + assertNotEquals(QUOTA, clone); + clone = ProjectInfo.Quota.fromPb(QUOTA.toPb()); + assertEquals(QUOTA, clone); + } + + @Test + public void testSameHashCodeOnEqualsQuota() { + ProjectInfo.Quota clone = ProjectInfo.Quota.fromPb(QUOTA.toPb()); + assertEquals(QUOTA, clone); + assertEquals(QUOTA.hashCode(), clone.hashCode()); + } + + @Test + public void testEqualsAndNotEquals() { + ProjectInfo clone = ProjectInfo.builder().build(); + assertNotEquals(PROJECT_INFO, clone); + clone = ProjectInfo.builder().id(PROJECT_INFO.id()).number(PROJECT_INFO.number()).build(); + assertNotEquals(PROJECT_INFO, clone); + clone = ProjectInfo.builder().id(PROJECT_INFO.id()).quota(PROJECT_INFO.quota()).build(); + assertNotEquals(PROJECT_INFO, clone); + clone = ProjectInfo.builder().number(PROJECT_INFO.number()).quota(PROJECT_INFO.quota()).build(); + assertNotEquals(PROJECT_INFO, clone); + clone = ProjectInfo.fromPb(PROJECT_INFO.toPb()); + assertEquals(PROJECT_INFO, clone); + } + + @Test + public void testSameHashCodeOnEquals() { + ProjectInfo clone = ProjectInfo.fromPb(PROJECT_INFO.toPb()); + assertEquals(PROJECT_INFO, clone); + assertEquals(PROJECT_INFO.hashCode(), clone.hashCode()); + } + + @Test + public void testToAndFromPb() { + assertEquals(PROJECT_INFO, ProjectInfo.fromPb(PROJECT_INFO.toPb())); + ProjectInfo partial = ProjectInfo.builder().id(ID).build(); + assertEquals(partial, PROJECT_INFO.fromPb(partial.toPb())); + partial = ProjectInfo.builder().number(NUMBER).build(); + assertEquals(partial, PROJECT_INFO.fromPb(partial.toPb())); + partial = ProjectInfo.builder().quota(QUOTA).build(); + assertEquals(partial, PROJECT_INFO.fromPb(partial.toPb())); + assertNotEquals(PROJECT_INFO, partial); + } + + @Test + public void testToAndFromPbQuota() { + assertEquals(QUOTA, ProjectInfo.Quota.fromPb(QUOTA.toPb())); + ProjectInfo.Quota wrong = new ProjectInfo.Quota(5, 6, 3, 6, 2, 1); + assertNotEquals(QUOTA, ProjectInfo.Quota.fromPb(wrong.toPb())); + } +} From a47158db527eeb220534189ee24c7837f75bddda Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 27 Jan 2016 12:35:32 -0800 Subject: [PATCH 16/74] Fixed serialization, javadoc and checkstyle. --- .../com/google/gcloud/dns/ProjectInfo.java | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index 614b9033a18e..dc9c2e6ef55e 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -26,14 +26,14 @@ /** * The class that encapsulates information about a project in Google Cloud DNS. A project is a top - * level container for resources including {@link ManagedZone}s. Projects can be created only in the + * level container for resources including {@code ManagedZone}s. Projects can be created only in the * APIs console. * * @see Google Cloud DNS documentation */ public class ProjectInfo implements Serializable { - private static final long serialVersionUID = 201601251420L; + private static final long serialVersionUID = 8696578863323485036L; private final String id; private final BigInteger number; private final Quota quota; @@ -55,8 +55,9 @@ public static class Quota { /** * Creates an instance of {@code Quota}. * - * This is the only way of creating an instance of {@code Quota}. As the service does not allow - * for specifying options, quota is an "all-or-nothing object" and we do not need a builder. + *

This is the only way of creating an instance of {@code Quota}. As the service does not + * allow for specifying options, quota is an "all-or-nothing object" and we do not need a + * builder. */ Quota(Integer zones, Integer resourceRecordsPerRrset, @@ -102,7 +103,7 @@ public Integer rrsetDeletionsPerChange() { } /** - * Returns the maximum allowed number of {@link DnsRecord}s per {@link ManagedZone} in the + * Returns the maximum allowed number of {@link DnsRecord}s per {@code ManagedZone} in the * project. */ public Integer rrsetsPerManagedZone() { @@ -117,8 +118,8 @@ public Integer totalRrdataSizePerChange() { } @Override - public boolean equals(Object o) { - return (o instanceof Quota) && this.toPb().equals(((Quota) o).toPb()); + public boolean equals(Object other) { + return (other instanceof Quota) && this.toPb().equals(((Quota) other).toPb()); } @Override @@ -139,14 +140,14 @@ com.google.api.services.dns.model.Quota toPb() { } static Quota fromPb(com.google.api.services.dns.model.Quota pb) { - Quota q = new Quota(pb.getManagedZones(), + Quota quota = new Quota(pb.getManagedZones(), pb.getResourceRecordsPerRrset(), pb.getRrsetAdditionsPerChange(), pb.getRrsetDeletionsPerChange(), pb.getRrsetsPerManagedZone(), pb.getTotalRrdataSizePerChange() ); - return q; + return quota; } @Override @@ -205,10 +206,10 @@ ProjectInfo build() { } } - private ProjectInfo(Builder b) { - this.id = b.id; - this.number = b.number; - this.quota = b.quota; + private ProjectInfo(Builder builder) { + this.id = builder.id; + this.number = builder.number; + this.quota = builder.quota; } /** @@ -250,22 +251,22 @@ com.google.api.services.dns.model.Project toPb() { } static ProjectInfo fromPb(com.google.api.services.dns.model.Project pb) { - Builder b = builder(); + Builder builder = builder(); if (pb.getId() != null) { - b.id(pb.getId()); + builder.id(pb.getId()); } if (pb.getNumber() != null) { - b.number(pb.getNumber()); + builder.number(pb.getNumber()); } if (pb.getQuota() != null) { - b.quota(Quota.fromPb(pb.getQuota())); + builder.quota(Quota.fromPb(pb.getQuota())); } - return b.build(); + return builder.build(); } @Override - public boolean equals(Object o) { - return (o instanceof ProjectInfo) && this.toPb().equals(((ProjectInfo) o).toPb()); + public boolean equals(Object other) { + return (other instanceof ProjectInfo) && this.toPb().equals(((ProjectInfo) other).toPb()); } @Override From 9db27d44a072233955a57670c4c77a8a1f72afca Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 27 Jan 2016 16:00:44 -0800 Subject: [PATCH 17/74] Implements comment from @aozarov and @ajkannan into ProjectInfo. --- .../com/google/gcloud/dns/ProjectInfo.java | 83 ++++++++++--------- .../google/gcloud/dns/ProjectInfoTest.java | 12 +-- 2 files changed, 48 insertions(+), 47 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index dc9c2e6ef55e..f8b2e33a1e9f 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -25,9 +25,9 @@ import java.util.Objects; /** - * The class that encapsulates information about a project in Google Cloud DNS. A project is a top - * level container for resources including {@code ManagedZone}s. Projects can be created only in the - * APIs console. + * The class provides the Google Cloud DNS information associated with this project. A project is a + * top level container for resources including {@code ManagedZone}s. Projects can be created only in + * the APIs console. * * @see Google Cloud DNS documentation */ @@ -41,16 +41,17 @@ public class ProjectInfo implements Serializable { /** * This class represents quotas assigned to the {@code ProjectInfo}. * - * @see Google Cloud DNS documentation + * @see Google Cloud DNS + * documentation */ public static class Quota { - private Integer zones; - private Integer resourceRecordsPerRrset; - private Integer rrsetAdditionsPerChange; - private Integer rrsetDeletionsPerChange; - private Integer rrsetsPerManagedZone; - private Integer totalRrdataSizePerChange; + private final int zones; + private final int resourceRecordsPerRrset; + private final int rrsetAdditionsPerChange; + private final int rrsetDeletionsPerChange; + private final int rrsetsPerManagedZone; + private final int totalRrdataSizePerChange; /** * Creates an instance of {@code Quota}. @@ -59,38 +60,38 @@ public static class Quota { * allow for specifying options, quota is an "all-or-nothing object" and we do not need a * builder. */ - Quota(Integer zones, - Integer resourceRecordsPerRrset, - Integer rrsetAdditionsPerChange, - Integer rrsetDeletionsPerChange, - Integer rrsetsPerManagedZone, - Integer totalRrdataSizePerChange) { - this.zones = checkNotNull(zones); - this.resourceRecordsPerRrset = checkNotNull(resourceRecordsPerRrset); - this.rrsetAdditionsPerChange = checkNotNull(rrsetAdditionsPerChange); - this.rrsetDeletionsPerChange = checkNotNull(rrsetDeletionsPerChange); - this.rrsetsPerManagedZone = checkNotNull(rrsetsPerManagedZone); - this.totalRrdataSizePerChange = checkNotNull(totalRrdataSizePerChange); + Quota(int zones, + int resourceRecordsPerRrset, + int rrsetAdditionsPerChange, + int rrsetDeletionsPerChange, + int rrsetsPerManagedZone, + int totalRrdataSizePerChange) { + this.zones = zones; + this.resourceRecordsPerRrset = resourceRecordsPerRrset; + this.rrsetAdditionsPerChange = rrsetAdditionsPerChange; + this.rrsetDeletionsPerChange = rrsetDeletionsPerChange; + this.rrsetsPerManagedZone = rrsetsPerManagedZone; + this.totalRrdataSizePerChange = totalRrdataSizePerChange; } /** * Returns the maximum allowed number of managed zones in the project. */ - public Integer zones() { + public int zones() { return zones; } /** * Returns the maximum allowed number of records per {@link DnsRecord}. */ - public Integer resourceRecordsPerRrset() { + public int resourceRecordsPerRrset() { return resourceRecordsPerRrset; } /** * Returns the maximum allowed number of {@link DnsRecord}s to add per {@code ChangesRequest}. */ - public Integer rrsetAdditionsPerChange() { + public int rrsetAdditionsPerChange() { return rrsetAdditionsPerChange; } @@ -98,7 +99,7 @@ public Integer rrsetAdditionsPerChange() { * Returns the maximum allowed number of {@link DnsRecord}s to delete per {@code * ChangesRequest}. */ - public Integer rrsetDeletionsPerChange() { + public int rrsetDeletionsPerChange() { return rrsetDeletionsPerChange; } @@ -106,14 +107,14 @@ public Integer rrsetDeletionsPerChange() { * Returns the maximum allowed number of {@link DnsRecord}s per {@code ManagedZone} in the * project. */ - public Integer rrsetsPerManagedZone() { + public int rrsetsPerManagedZone() { return rrsetsPerManagedZone; } /** * Returns the maximum allowed size for total records in one ChangesRequest in bytes. */ - public Integer totalRrdataSizePerChange() { + public int totalRrdataSizePerChange() { return totalRrdataSizePerChange; } @@ -220,32 +221,32 @@ static Builder builder() { } /** - * Returns the user-assigned unique identifier for the project. + * Returns the {@code Quota} object which contains quotas assigned to this project. */ - public String id() { - return id; + public Quota quota() { + return quota; } /** - * Returns the unique numeric identifier for the project. + * Returns project number. For internal use only. */ - public BigInteger number() { + BigInteger number() { return number; } /** - * Returns the {@code Quota} object which contains quotas assigned to this project. + * Returns project id. For internal use only. */ - public Quota quota() { - return quota; + String id() { + return id; } com.google.api.services.dns.model.Project toPb() { com.google.api.services.dns.model.Project pb = new com.google.api.services.dns.model.Project(); - pb.setId(id()); - pb.setNumber(number()); - if (this.quota() != null) { - pb.setQuota(quota().toPb()); + pb.setId(id); + pb.setNumber(number); + if (this.quota != null) { + pb.setQuota(quota.toPb()); } return pb; } @@ -266,7 +267,7 @@ static ProjectInfo fromPb(com.google.api.services.dns.model.Project pb) { @Override public boolean equals(Object other) { - return (other instanceof ProjectInfo) && this.toPb().equals(((ProjectInfo) other).toPb()); + return (other instanceof ProjectInfo) && toPb().equals(((ProjectInfo) other).toPb()); } @Override diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java index 2c5e1ffa7100..2af8b5ad3995 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java @@ -53,12 +53,12 @@ public void testBuilder() { @Test public void testQuotaConstructor() { - assertEquals(Integer.valueOf(1), QUOTA.zones()); - assertEquals(Integer.valueOf(2), QUOTA.resourceRecordsPerRrset()); - assertEquals(Integer.valueOf(3), QUOTA.rrsetAdditionsPerChange()); - assertEquals(Integer.valueOf(4), QUOTA.rrsetDeletionsPerChange()); - assertEquals(Integer.valueOf(5), QUOTA.rrsetsPerManagedZone()); - assertEquals(Integer.valueOf(6), QUOTA.totalRrdataSizePerChange()); + assertEquals(1, QUOTA.zones()); + assertEquals(2, QUOTA.resourceRecordsPerRrset()); + assertEquals(3, QUOTA.rrsetAdditionsPerChange()); + assertEquals(4, QUOTA.rrsetDeletionsPerChange()); + assertEquals(5, QUOTA.rrsetsPerManagedZone()); + assertEquals(6, QUOTA.totalRrdataSizePerChange()); } @Test From 4412c7304cda6bd5d3846161b6451740972bc929 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 27 Jan 2016 16:13:37 -0800 Subject: [PATCH 18/74] Changed documentation @code to @link where applicable. --- .../src/main/java/com/google/gcloud/dns/ProjectInfo.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index f8b2e33a1e9f..e65524913920 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -89,22 +89,22 @@ public int resourceRecordsPerRrset() { } /** - * Returns the maximum allowed number of {@link DnsRecord}s to add per {@code ChangesRequest}. + * Returns the maximum allowed number of {@link DnsRecord}s to add per {@link ChangeRequest}. */ public int rrsetAdditionsPerChange() { return rrsetAdditionsPerChange; } /** - * Returns the maximum allowed number of {@link DnsRecord}s to delete per {@code - * ChangesRequest}. + * Returns the maximum allowed number of {@link DnsRecord}s to delete per {@link + * ChangeRequest}. */ public int rrsetDeletionsPerChange() { return rrsetDeletionsPerChange; } /** - * Returns the maximum allowed number of {@link DnsRecord}s per {@code ManagedZone} in the + * Returns the maximum allowed number of {@link DnsRecord}s per {@link ManagedZoneInfo} in the * project. */ public int rrsetsPerManagedZone() { From 81a46d8429909998bdbf65cdc0726e9a404d62b1 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 27 Jan 2016 18:01:27 -0800 Subject: [PATCH 19/74] Renames ManagedZone to Zone. Acommodates codecheck. Fixes #579. --- .../com/google/gcloud/dns/ChangeRequest.java | 4 +- .../java/com/google/gcloud/dns/DnsRecord.java | 4 +- .../com/google/gcloud/dns/ProjectInfo.java | 6 +- .../{ManagedZoneInfo.java => ZoneInfo.java} | 88 +++++++++---------- ...gedZoneInfoTest.java => ZoneInfoTest.java} | 62 ++++++------- 5 files changed, 80 insertions(+), 84 deletions(-) rename gcloud-java-dns/src/main/java/com/google/gcloud/dns/{ManagedZoneInfo.java => ZoneInfo.java} (70%) rename gcloud-java-dns/src/test/java/com/google/gcloud/dns/{ManagedZoneInfoTest.java => ZoneInfoTest.java} (72%) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index 5ed03b1ea071..582dd2b2e05b 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -34,7 +34,7 @@ /** * A class representing an atomic update to a collection of {@link DnsRecord}s within a {@code - * ManagedZone}. + * Zone}. * * @see Google Cloud DNS documentation */ @@ -102,7 +102,7 @@ public Builder additions(List additions) { this.additions = Lists.newLinkedList(checkNotNull(additions)); return this; } - + /** * Sets a collection of {@link DnsRecord}s which are to be deleted from the zone upon executing * this {@code ChangeRequest}. diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 4236d9c1c561..b9e8134d9921 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -33,8 +33,8 @@ * *

A {@code DnsRecord} is the unit of data that will be returned by the DNS servers upon a DNS * request for a specific domain. The {@code DnsRecord} holds the current state of the DNS records - * that make up a managed zone. You can read the records but you cannot modify them directly. - * Rather, you edit the records in a managed zone by creating a ChangeRequest. + * that make up a zone. You can read the records but you cannot modify them directly. + * Rather, you edit the records in a zone by creating a ChangeRequest. * * @see Google Cloud DNS * documentation diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index e65524913920..b7933956ed88 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -26,7 +26,7 @@ /** * The class provides the Google Cloud DNS information associated with this project. A project is a - * top level container for resources including {@code ManagedZone}s. Projects can be created only in + * top level container for resources including {@code Zone}s. Projects can be created only in * the APIs console. * * @see Google Cloud DNS documentation @@ -75,7 +75,7 @@ public static class Quota { } /** - * Returns the maximum allowed number of managed zones in the project. + * Returns the maximum allowed number of zones in the project. */ public int zones() { return zones; @@ -104,7 +104,7 @@ public int rrsetDeletionsPerChange() { } /** - * Returns the maximum allowed number of {@link DnsRecord}s per {@link ManagedZoneInfo} in the + * Returns the maximum allowed number of {@link DnsRecord}s per {@link ZoneInfo} in the * project. */ public int rrsetsPerManagedZone() { diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java similarity index 70% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index d27e134ad908..3e8afd9a30f9 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ManagedZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -32,12 +32,12 @@ import java.util.Objects; /** - * A {@code ManagedZone} represents a DNS zone hosted by the Google Cloud DNS service. A zone is a - * subtree of the DNS namespace under one administrative responsibility. See Google Cloud DNS documentation for * more information. */ -public class ManagedZoneInfo implements Serializable { +public class ZoneInfo implements Serializable { private static final long serialVersionUID = 201601191647L; private final String name; @@ -49,7 +49,7 @@ public class ManagedZoneInfo implements Serializable { private final List nameServers; /** - * A builder for {@code ManagedZoneInfo}. + * A builder for {@code ZoneInfo}. */ public static class Builder { private String name; @@ -61,8 +61,7 @@ public static class Builder { private List nameServers = new LinkedList<>(); /** - * Returns an empty builder for {@code ManagedZoneInfo}. We use it internally in {@code - * toPb()}. + * Returns an empty builder for {@code ZoneInfo}. We use it internally in {@code toPb()}. */ private Builder() { } @@ -81,9 +80,9 @@ private Builder(String name, BigInteger id) { } /** - * Creates a builder from an existing ManagedZoneInfo object. + * Creates a builder from an existing ZoneInfo object. */ - Builder(ManagedZoneInfo info) { + Builder(ZoneInfo info) { this.name = info.name; this.id = info.id; this.creationTimeMillis = info.creationTimeMillis; @@ -102,7 +101,7 @@ public Builder name(String name) { } /** - * Sets an id for the managed zone which is assigned to the managed zone by the server. + * Sets an id for the zone which is assigned to the zone by the server. */ Builder id(BigInteger id) { this.id = id; @@ -110,7 +109,7 @@ Builder id(BigInteger id) { } /** - * Sets the time when this managed zone was created. + * Sets the time when this zone was created. */ Builder creationTimeMillis(long creationTimeMillis) { this.creationTimeMillis = creationTimeMillis; @@ -118,7 +117,7 @@ Builder creationTimeMillis(long creationTimeMillis) { } /** - * Sets a mandatory DNS name of this managed zone, for instance "example.com.". + * Sets a mandatory DNS name of this zone, for instance "example.com.". */ public Builder dnsName(String dnsName) { this.dnsName = checkNotNull(dnsName); @@ -126,8 +125,8 @@ public Builder dnsName(String dnsName) { } /** - * Sets a mandatory description for this managed zone. The value is a string of at most 1024 - * characters which has no effect on the managed zone's function. + * Sets a mandatory description for this zone. The value is a string of at most 1024 characters + * which has no effect on the zone's function. */ public Builder description(String description) { this.description = checkNotNull(description); @@ -135,9 +134,8 @@ public Builder description(String description) { } /** - * Optionally specifies the NameServerSet for this managed zone. A NameServerSet is a set of DNS - * name servers that all host the same ManagedZones. Most users will not need to specify this - * value. + * Optionally specifies the NameServerSet for this zone. A NameServerSet is a set of DNS name + * servers that all host the same zones. Most users will not need to specify this value. */ public Builder nameServerSet(String nameServerSet) { // todo(mderka) add more to the doc when questions are answered by the service owner @@ -146,8 +144,8 @@ public Builder nameServerSet(String nameServerSet) { } /** - * Sets a list of servers that hold the information about the managed zone. This information is - * provided by Google Cloud DNS and is read only. + * Sets a list of servers that hold the information about the zone. This information is provided + * by Google Cloud DNS and is read only. */ Builder nameServers(List nameServers) { checkNotNull(nameServers); @@ -156,14 +154,14 @@ Builder nameServers(List nameServers) { } /** - * Builds the instance of {@code ManagedZoneInfo} based on the information set by this builder. + * Builds the instance of {@code ZoneInfo} based on the information set by this builder. */ - public ManagedZoneInfo build() { - return new ManagedZoneInfo(this); + public ZoneInfo build() { + return new ZoneInfo(this); } } - private ManagedZoneInfo(Builder builder) { + private ZoneInfo(Builder builder) { this.name = builder.name; this.id = builder.id; this.creationTimeMillis = builder.creationTimeMillis; @@ -174,63 +172,63 @@ private ManagedZoneInfo(Builder builder) { } /** - * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code name}. + * Returns a builder for {@code ZoneInfo} with an assigned {@code name}. */ public static Builder builder(String name) { return new Builder(name); } /** - * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code id}. + * Returns a builder for {@code ZoneInfo} with an assigned {@code id}. */ public static Builder builder(BigInteger id) { return new Builder(id); } /** - * Returns a builder for {@code ManagedZoneInfo} with an assigned {@code name} and {@code id}. + * Returns a builder for {@code ZoneInfo} with an assigned {@code name} and {@code id}. */ public static Builder builder(String name, BigInteger id) { return new Builder(name, id); } /** - * Returns the user-defined name of the managed zone. + * Returns the user-defined name of the zone. */ public String name() { return name; } /** - * Returns the read-only managed zone id assigned by the server. + * Returns the read-only zone id assigned by the server. */ public BigInteger id() { return id; } /** - * Returns the time when this time that this managed zone was created on the server. + * Returns the time when this time that this zone was created on the server. */ public Long creationTimeMillis() { return creationTimeMillis; } /** - * Returns the DNS name of this managed zone, for instance "example.com.". + * Returns the DNS name of this zone, for instance "example.com.". */ public String dnsName() { return dnsName; } /** - * Returns the description of this managed zone. + * Returns the description of this zone. */ public String description() { return description; } /** - * Returns the optionally specified set of DNS name servers that all host this managed zone. + * Returns the optionally specified set of DNS name servers that all host this zone. */ public String nameServerSet() { // todo(mderka) update this doc after finding out more about this from the service owners @@ -238,16 +236,14 @@ public String nameServerSet() { } /** - * The nameservers that the managed zone should be delegated to. This is defined by the Google DNS - * cloud. + * The nameservers that the zone should be delegated to. This is defined by the Google DNS cloud. */ public List nameServers() { return nameServers; } /** - * Returns a builder for {@code ManagedZoneInfo} prepopulated with the metadata of this managed - * zone. + * Returns a builder for {@code ZoneInfo} prepopulated with the metadata of this zone. */ public Builder toBuilder() { return new Builder(this); @@ -272,35 +268,35 @@ com.google.api.services.dns.model.ManagedZone toPb() { return pb; } - static ManagedZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { - Builder b = new Builder(); + static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { + Builder builder = new Builder(); if (pb.getDescription() != null) { - b.description(pb.getDescription()); + builder.description(pb.getDescription()); } if (pb.getDnsName() != null) { - b.dnsName(pb.getDnsName()); + builder.dnsName(pb.getDnsName()); } if (pb.getId() != null) { - b.id(pb.getId()); + builder.id(pb.getId()); } if (pb.getName() != null) { - b.name(pb.getName()); + builder.name(pb.getName()); } if (pb.getNameServers() != null) { - b.nameServers(pb.getNameServers()); + builder.nameServers(pb.getNameServers()); } if (pb.getNameServerSet() != null) { - b.nameServerSet(pb.getNameServerSet()); + builder.nameServerSet(pb.getNameServerSet()); } if (pb.getCreationTime() != null) { - b.creationTimeMillis(DateTime.parse(pb.getCreationTime()).getMillis()); + builder.creationTimeMillis(DateTime.parse(pb.getCreationTime()).getMillis()); } - return b.build(); + return builder.build(); } @Override public boolean equals(Object obj) { - return obj instanceof ManagedZoneInfo && Objects.equals(toPb(), ((ManagedZoneInfo) obj).toPb()); + return obj instanceof ZoneInfo && Objects.equals(toPb(), ((ZoneInfo) obj).toPb()); } @Override diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java similarity index 72% rename from gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java rename to gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java index 936164c81723..2c9fea8f7bde 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ManagedZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java @@ -30,7 +30,7 @@ import java.util.LinkedList; import java.util.List; -public class ManagedZoneInfoTest { +public class ZoneInfoTest { private static final String NAME = "mz-example.com"; private static final BigInteger ID = BigInteger.valueOf(123L); @@ -42,7 +42,7 @@ public class ManagedZoneInfoTest { private static final String NS2 = "name server 2"; private static final String NS3 = "name server 3"; private static final List NAME_SERVERS = ImmutableList.of(NS1, NS2, NS3); - private static final ManagedZoneInfo INFO = ManagedZoneInfo.builder(NAME, ID) + private static final ZoneInfo INFO = ZoneInfo.builder(NAME, ID) .creationTimeMillis(CREATION_TIME_MILLIS) .dnsName(DNS_NAME) .description(DESCRIPTION) @@ -52,7 +52,7 @@ public class ManagedZoneInfoTest { @Test public void testDefaultBuilders() { - ManagedZoneInfo withName = ManagedZoneInfo.builder(NAME).build(); + ZoneInfo withName = ZoneInfo.builder(NAME).build(); assertTrue(withName.nameServers().isEmpty()); assertEquals(NAME, withName.name()); assertNull(withName.id()); @@ -60,7 +60,7 @@ public void testDefaultBuilders() { assertNull(withName.nameServerSet()); assertNull(withName.description()); assertNull(withName.dnsName()); - ManagedZoneInfo withId = ManagedZoneInfo.builder(ID).build(); + ZoneInfo withId = ZoneInfo.builder(ID).build(); assertTrue(withId.nameServers().isEmpty()); assertEquals(ID, withId.id()); assertNull(withId.name()); @@ -68,7 +68,7 @@ public void testDefaultBuilders() { assertNull(withId.nameServerSet()); assertNull(withId.description()); assertNull(withId.dnsName()); - ManagedZoneInfo withBoth = ManagedZoneInfo.builder(NAME, ID).build(); + ZoneInfo withBoth = ZoneInfo.builder(NAME, ID).build(); assertTrue(withBoth.nameServers().isEmpty()); assertEquals(ID, withBoth.id()); assertEquals(NAME, withBoth.name()); @@ -94,7 +94,7 @@ public void testBuilder() { @Test public void testEqualsAndNotEquals() { - ManagedZoneInfo clone = INFO.toBuilder().build(); + ZoneInfo clone = INFO.toBuilder().build(); assertEquals(INFO, clone); List moreServers = Lists.newLinkedList(NAME_SERVERS); moreServers.add(NS1); @@ -118,55 +118,55 @@ public void testEqualsAndNotEquals() { @Test public void testSameHashCodeOnEquals() { int hash = INFO.hashCode(); - ManagedZoneInfo clone = INFO.toBuilder().build(); + ZoneInfo clone = INFO.toBuilder().build(); assertEquals(clone.hashCode(), hash); } @Test public void testToBuilder() { assertEquals(INFO, INFO.toBuilder().build()); - ManagedZoneInfo partial = ManagedZoneInfo.builder(NAME).build(); + ZoneInfo partial = ZoneInfo.builder(NAME).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ManagedZoneInfo.builder(ID).build(); + partial = ZoneInfo.builder(ID).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ManagedZoneInfo.builder(NAME).description(DESCRIPTION).build(); + partial = ZoneInfo.builder(NAME).description(DESCRIPTION).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ManagedZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); + partial = ZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ManagedZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); + partial = ZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); assertEquals(partial, partial.toBuilder().build()); List nameServers = new LinkedList<>(); nameServers.add(NS1); - partial = ManagedZoneInfo.builder(NAME).nameServers(nameServers).build(); + partial = ZoneInfo.builder(NAME).nameServers(nameServers).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ManagedZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); + partial = ZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); assertEquals(partial, partial.toBuilder().build()); } @Test public void testToAndFromPb() { - assertEquals(INFO, ManagedZoneInfo.fromPb(INFO.toPb())); - ManagedZoneInfo partial = ManagedZoneInfo.builder(NAME).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); - partial = ManagedZoneInfo.builder(ID).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); - partial = ManagedZoneInfo.builder(NAME).description(DESCRIPTION).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); - partial = ManagedZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); - partial = ManagedZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + assertEquals(INFO, ZoneInfo.fromPb(INFO.toPb())); + ZoneInfo partial = ZoneInfo.builder(NAME).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); + partial = ZoneInfo.builder(ID).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); + partial = ZoneInfo.builder(NAME).description(DESCRIPTION).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); + partial = ZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); + partial = ZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); List nameServers = new LinkedList<>(); nameServers.add(NS1); - partial = ManagedZoneInfo.builder(NAME).nameServers(nameServers).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); - partial = ManagedZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); - assertEquals(partial, ManagedZoneInfo.fromPb(partial.toPb())); + partial = ZoneInfo.builder(NAME).nameServers(nameServers).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); + partial = ZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); + assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); } @Test public void testEmptyNameServers() { - ManagedZoneInfo clone = INFO.toBuilder().nameServers(new LinkedList()).build(); + ZoneInfo clone = INFO.toBuilder().nameServers(new LinkedList()).build(); assertTrue(clone.nameServers().isEmpty()); clone.toPb(); // test that this is allowed } @@ -175,7 +175,7 @@ public void testEmptyNameServers() { public void testDateParsing() { com.google.api.services.dns.model.ManagedZone pb = INFO.toPb(); pb.setCreationTime("2016-01-19T18:00:12.854Z"); // a real value obtained from Google Cloud DNS - ManagedZoneInfo mz = ManagedZoneInfo.fromPb(pb); // parses the string timestamp to millis + ZoneInfo mz = ZoneInfo.fromPb(pb); // parses the string timestamp to millis com.google.api.services.dns.model.ManagedZone pbClone = mz.toPb(); // converts it back to string assertEquals(pb, pbClone); assertEquals(pb.getCreationTime(), pbClone.getCreationTime()); From c364ff322187be6404c1a9cd0e1673b8f64a7c35 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 09:30:55 -0800 Subject: [PATCH 20/74] Modified ttl to accept time unit. Fixed #581. --- .../java/com/google/gcloud/dns/DnsRecord.java | 30 +++++++++----- .../com/google/gcloud/dns/DnsRecordTest.java | 39 ++++++++++++------- 2 files changed, 46 insertions(+), 23 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index b9e8134d9921..a3a673b99cc6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -27,14 +27,15 @@ import java.util.LinkedList; import java.util.List; import java.util.Objects; +import java.util.concurrent.TimeUnit; /** * A class that represents a Google Cloud DNS record set. * *

A {@code DnsRecord} is the unit of data that will be returned by the DNS servers upon a DNS * request for a specific domain. The {@code DnsRecord} holds the current state of the DNS records - * that make up a zone. You can read the records but you cannot modify them directly. - * Rather, you edit the records in a zone by creating a ChangeRequest. + * that make up a zone. You can read the records but you cannot modify them directly. Rather, you + * edit the records in a zone by creating a ChangeRequest. * * @see Google Cloud DNS * documentation @@ -44,7 +45,7 @@ public class DnsRecord implements Serializable { private static final long serialVersionUID = 2016011914302204L; private final String name; private final List rrdatas; - private final Integer ttl; + private final Integer ttl; // this is in seconds private final Type type; /** @@ -176,14 +177,23 @@ public Builder name(String name) { } /** - * Sets the number of seconds that this record can be cached by resolvers. This number must be - * non-negative. + * Sets the time that this record can be cached by resolvers. This number must be non-negative. + * The maximum duration must be equivalent to at most {@link Integer#MAX_VALUE} seconds. * - * @param ttl A non-negative number of seconds + * @param duration A non-negative number of time units + * @param unit The unit of the ttl parameter */ - public Builder ttl(int ttl) { - checkArgument(ttl >= 0, "TTL cannot be negative. The supplied value was %s.", ttl); - this.ttl = ttl; + public Builder ttl(int duration, TimeUnit unit) { + checkArgument(duration >= 0, + "Duration cannot be negative. The supplied value was %s.", duration); + checkNotNull(unit); + // convert to seconds and check that we are not overflowing int + // we cannot do that because pb does not support it + long converted = unit.toSeconds(duration); + checkArgument(converted <= Integer.MAX_VALUE, + "The duration converted to seconds is out of range of int. The value converts to %s sec.", + converted); + ttl = (int) converted; return this; } @@ -278,7 +288,7 @@ static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) builder.records(pb.getRrdatas()); } if (pb.getTtl() != null) { - builder.ttl(pb.getTtl()); + builder.ttl(pb.getTtl(), TimeUnit.SECONDS); } return builder.build(); } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java index 7a7daf8aac3c..5fc972cede78 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java @@ -16,6 +16,7 @@ package com.google.gcloud.dns; +import static com.google.gcloud.dns.DnsRecord.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; @@ -23,18 +24,22 @@ import org.junit.Test; +import java.util.concurrent.TimeUnit; + public class DnsRecordTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; + private static final TimeUnit UNIT = TimeUnit.HOURS; + private static final Integer UNIT_TTL = 1; private static final DnsRecord.Type TYPE = DnsRecord.Type.AAAA; - private static final DnsRecord record = DnsRecord.builder(NAME, TYPE) - .ttl(TTL) + private static final DnsRecord record = builder(NAME, TYPE) + .ttl(UNIT_TTL, UNIT) .build(); @Test public void testDefaultDnsRecord() { - DnsRecord record = DnsRecord.builder(NAME, TYPE).build(); + DnsRecord record = builder(NAME, TYPE).build(); assertEquals(0, record.records().size()); assertEquals(TYPE, record.type()); assertEquals(NAME, record.name()); @@ -61,13 +66,21 @@ public void testBuilder() { @Test public void testValidTtl() { try { - DnsRecord.builder(NAME, TYPE).ttl(-1); + builder(NAME, TYPE).ttl(-1, TimeUnit.SECONDS); fail("A negative value is not acceptable for ttl."); } catch (IllegalArgumentException e) { // expected } - DnsRecord.builder(NAME, TYPE).ttl(0); - DnsRecord.builder(NAME, TYPE).ttl(Integer.MAX_VALUE); + builder(NAME, TYPE).ttl(0, TimeUnit.SECONDS); + builder(NAME, TYPE).ttl(Integer.MAX_VALUE, TimeUnit.SECONDS); + try { + builder(NAME, TYPE).ttl(Integer.MAX_VALUE, TimeUnit.HOURS); + fail("This value is too large for int."); + } catch (IllegalArgumentException e) { + // expected + } + DnsRecord record = DnsRecord.builder(NAME, TYPE).ttl(UNIT_TTL, UNIT).build(); + assertEquals(TTL, record.ttl()); } @Test @@ -79,7 +92,7 @@ public void testEqualsAndNotEquals() { String differentName = "totally different name"; clone = record.toBuilder().name(differentName).build(); assertNotEquals(record, clone); - clone = record.toBuilder().ttl(record.ttl() + 1).build(); + clone = record.toBuilder().ttl(record.ttl() + 1, TimeUnit.SECONDS).build(); assertNotEquals(record, clone); clone = record.toBuilder().type(DnsRecord.Type.TXT).build(); assertNotEquals(record, clone); @@ -95,22 +108,22 @@ public void testSameHashCodeOnEquals() { @Test public void testToAndFromPb() { assertEquals(record, DnsRecord.fromPb(record.toPb())); - DnsRecord partial = DnsRecord.builder(NAME, TYPE).build(); + DnsRecord partial = builder(NAME, TYPE).build(); assertEquals(partial, DnsRecord.fromPb(partial.toPb())); - partial = DnsRecord.builder(NAME, TYPE).addRecord("test").build(); + partial = builder(NAME, TYPE).addRecord("test").build(); assertEquals(partial, DnsRecord.fromPb(partial.toPb())); - partial = DnsRecord.builder(NAME, TYPE).ttl(15).build(); + partial = builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); assertEquals(partial, DnsRecord.fromPb(partial.toPb())); } @Test public void testToBuilder() { assertEquals(record, record.toBuilder().build()); - DnsRecord partial = DnsRecord.builder(NAME, TYPE).build(); + DnsRecord partial = builder(NAME, TYPE).build(); assertEquals(partial, partial.toBuilder().build()); - partial = DnsRecord.builder(NAME, TYPE).addRecord("test").build(); + partial = builder(NAME, TYPE).addRecord("test").build(); assertEquals(partial, partial.toBuilder().build()); - partial = DnsRecord.builder(NAME, TYPE).ttl(15).build(); + partial = builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); assertEquals(partial, partial.toBuilder().build()); } From 7bcff48454c09e73ab94b1b995563e390200d081 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 10:27:21 -0800 Subject: [PATCH 21/74] Implemented comments by @aozarov. --- .../java/com/google/gcloud/dns/DnsRecord.java | 9 +++------ .../java/com/google/gcloud/dns/ProjectInfo.java | 16 ++++++++-------- .../java/com/google/gcloud/dns/ZoneInfo.java | 2 +- .../com/google/gcloud/dns/ProjectInfoTest.java | 8 ++++---- 4 files changed, 16 insertions(+), 19 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index a3a673b99cc6..99ca20386419 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -22,6 +22,7 @@ import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; import java.io.Serializable; import java.util.LinkedList; @@ -187,13 +188,9 @@ public Builder ttl(int duration, TimeUnit unit) { checkArgument(duration >= 0, "Duration cannot be negative. The supplied value was %s.", duration); checkNotNull(unit); - // convert to seconds and check that we are not overflowing int - // we cannot do that because pb does not support it + // we cannot have long because pb does not support it long converted = unit.toSeconds(duration); - checkArgument(converted <= Integer.MAX_VALUE, - "The duration converted to seconds is out of range of int. The value converts to %s sec.", - converted); - ttl = (int) converted; + ttl = Ints.checkedCast(converted); return this; } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index b7933956ed88..4db0497946b1 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -50,7 +50,7 @@ public static class Quota { private final int resourceRecordsPerRrset; private final int rrsetAdditionsPerChange; private final int rrsetDeletionsPerChange; - private final int rrsetsPerManagedZone; + private final int rrsetsPerZone; private final int totalRrdataSizePerChange; /** @@ -64,13 +64,13 @@ public static class Quota { int resourceRecordsPerRrset, int rrsetAdditionsPerChange, int rrsetDeletionsPerChange, - int rrsetsPerManagedZone, + int rrsetsPerZone, int totalRrdataSizePerChange) { this.zones = zones; this.resourceRecordsPerRrset = resourceRecordsPerRrset; this.rrsetAdditionsPerChange = rrsetAdditionsPerChange; this.rrsetDeletionsPerChange = rrsetDeletionsPerChange; - this.rrsetsPerManagedZone = rrsetsPerManagedZone; + this.rrsetsPerZone = rrsetsPerZone; this.totalRrdataSizePerChange = totalRrdataSizePerChange; } @@ -107,8 +107,8 @@ public int rrsetDeletionsPerChange() { * Returns the maximum allowed number of {@link DnsRecord}s per {@link ZoneInfo} in the * project. */ - public int rrsetsPerManagedZone() { - return rrsetsPerManagedZone; + public int rrsetsPerZone() { + return rrsetsPerZone; } /** @@ -126,7 +126,7 @@ public boolean equals(Object other) { @Override public int hashCode() { return Objects.hash(zones, resourceRecordsPerRrset, rrsetAdditionsPerChange, - rrsetDeletionsPerChange, rrsetsPerManagedZone, totalRrdataSizePerChange); + rrsetDeletionsPerChange, rrsetsPerZone, totalRrdataSizePerChange); } com.google.api.services.dns.model.Quota toPb() { @@ -135,7 +135,7 @@ com.google.api.services.dns.model.Quota toPb() { pb.setResourceRecordsPerRrset(resourceRecordsPerRrset); pb.setRrsetAdditionsPerChange(rrsetAdditionsPerChange); pb.setRrsetDeletionsPerChange(rrsetDeletionsPerChange); - pb.setRrsetsPerManagedZone(rrsetsPerManagedZone); + pb.setRrsetsPerManagedZone(rrsetsPerZone); pb.setTotalRrdataSizePerChange(totalRrdataSizePerChange); return pb; } @@ -158,7 +158,7 @@ public String toString() { .add("resourceRecordsPerRrset", resourceRecordsPerRrset) .add("rrsetAdditionsPerChange", rrsetAdditionsPerChange) .add("rrsetDeletionsPerChange", rrsetDeletionsPerChange) - .add("rrsetsPerManagedZone", rrsetsPerManagedZone) + .add("rrsetsPerZone", rrsetsPerZone) .add("totalRrdataSizePerChange", totalRrdataSizePerChange) .toString(); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index 3e8afd9a30f9..524309eaa8e9 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -207,7 +207,7 @@ public BigInteger id() { } /** - * Returns the time when this time that this zone was created on the server. + * Returns the time when this zone was created on the server. */ public Long creationTimeMillis() { return creationTimeMillis; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java index 2af8b5ad3995..d959d44d4351 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ProjectInfoTest.java @@ -57,7 +57,7 @@ public void testQuotaConstructor() { assertEquals(2, QUOTA.resourceRecordsPerRrset()); assertEquals(3, QUOTA.rrsetAdditionsPerChange()); assertEquals(4, QUOTA.rrsetDeletionsPerChange()); - assertEquals(5, QUOTA.rrsetsPerManagedZone()); + assertEquals(5, QUOTA.rrsetsPerZone()); assertEquals(6, QUOTA.totalRrdataSizePerChange()); } @@ -101,11 +101,11 @@ public void testSameHashCodeOnEquals() { public void testToAndFromPb() { assertEquals(PROJECT_INFO, ProjectInfo.fromPb(PROJECT_INFO.toPb())); ProjectInfo partial = ProjectInfo.builder().id(ID).build(); - assertEquals(partial, PROJECT_INFO.fromPb(partial.toPb())); + assertEquals(partial, ProjectInfo.fromPb(partial.toPb())); partial = ProjectInfo.builder().number(NUMBER).build(); - assertEquals(partial, PROJECT_INFO.fromPb(partial.toPb())); + assertEquals(partial, ProjectInfo.fromPb(partial.toPb())); partial = ProjectInfo.builder().quota(QUOTA).build(); - assertEquals(partial, PROJECT_INFO.fromPb(partial.toPb())); + assertEquals(partial, ProjectInfo.fromPb(partial.toPb())); assertNotEquals(PROJECT_INFO, partial); } From f9b6f6a4762484da32ceee58e5281f1d615a1a12 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 15:55:06 -0800 Subject: [PATCH 22/74] Added DnsService interface. --- .../com/google/gcloud/dns/DnsService.java | 507 ++++++++++++++++++ 1 file changed, 507 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java new file mode 100644 index 000000000000..694b0b288154 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java @@ -0,0 +1,507 @@ +/* + * 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.dns; + +import com.google.common.base.Joiner; +import com.google.common.collect.Sets; +import com.google.gcloud.spi.DnsServiceRpc; + +import java.io.Serializable; +import java.util.Set; + +/** + * An interface for the Google Cloud DNS service. + * + * @see Google Cloud DNS + */ +public interface DnsService extends Service { + + /** + * The fields of a project. + * + *

These values can be used to specify the fields to include in a partial response when calling + * {@code DnsService#getProjectInfo(ProjectOptions...)}. Project ID is always returned, even if + * not specified. + */ + enum ProjectField { + PROJECT_ID("id"), + PROJECT_NUMBER("number"), + QUOTA("quota"); + + private final String selector; + + ProjectField(String selector) { + this.selector = selector; + } + + public String selector() { + return selector; + } + + static String selector(ProjectField... fields) { + Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); + fieldStrings.add(PROJECT_ID.selector()); + for (ProjectField field : fields) { + fieldStrings.add(field.selector()); + } + return Joiner.on(',').join(fieldStrings); + } + } + + /** + * The fields of a zone. + * + *

These values can be used to specify the fields to include in a partial response when calling + * {@code DnsService#getZone(BigInteger, ZoneFieldOptions...)} or {@code + * DnsService#getZone(String, ZoneFieldOptions...)}. The ID is always returned, even if not + * specified. + */ + enum ZoneField { + CREATION_TIME("creationTime"), + DESCRIPTION("description"), + DNS_NAME("dnsName"), + ZONE_ID("id"), + NAME("name"), + NAME_SERVER_SET("nameServerSet"), + NAME_SERVERS("nameServers"); + + private final String selector; + + ZoneField(String selector) { + this.selector = selector; + } + + public String selector() { + return selector; + } + + static String selector(ZoneField... fields) { + Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); + fieldStrings.add(ZONE_ID.selector()); + for (ZoneField field : fields) { + fieldStrings.add(field.selector()); + } + return Joiner.on(',').join(fieldStrings); + } + } + + /** + * The fields of a DNS record. + * + *

These values can be used to specify the fields to include in a partial response when calling + * {@code DnsService#listDnsRecords(BigInteger, DnsRecordOptions...)} or {@code + * DnsService#listDnsRecords(String, DnsRecordOptions...)}. The name is always returned even if + * not selected. + */ + enum DnsRecordField { + DNS_RECORDS("rrdatas"), + NAME("name"), + TTL("ttl"), + TYPE("type"); + + private final String selector; + + DnsRecordField(String selector) { + this.selector = selector; + } + + public String selector() { + return selector; + } + + static String selector(DnsRecordField... fields) { + Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); + fieldStrings.add(NAME.selector()); + for (DnsRecordField field : fields) { + fieldStrings.add(field.selector()); + } + return Joiner.on(',').join(fieldStrings); + } + } + + /** + * The fields of a change request. + * + *

These values can be used to specify the fields to include in a partial response when calling + * {@code DnsService#applyChangeRequest(ChangeRequest, BigInteger, ChangeRequestFieldOptions...)} + * or {@code DnsService#applyChangeRequest(ChangeRequest, String, ChangeRequestFieldOptions...)} + * The ID is always returned even if not selected. + */ + enum ChangeRequestField { + ID("id"), + START_TIME("startTime"), + STATUS("status"), + ADDITIONS("additions"), + DELETIONS("deletions"); + + private final String selector; + + ChangeRequestField(String selector) { + this.selector = selector; + } + + public String selector() { + return selector; + } + + static String selector(ChangeRequestField... fields) { + Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); + fieldStrings.add(ID.selector()); + for (ChangeRequestField field : fields) { + fieldStrings.add(field.selector()); + } + return Joiner.on(',').join(fieldStrings); + } + } + + /** + * The sorting keys for listing change requests. The only currently supported sorting key is the + * change sequence. + */ + enum ChangeRequestSortingKey { + CHANGE_SEQUENCE("changeSequence"); + + private final String selector; + + ChangeRequestSortingKey(String selector) { + this.selector = selector; + } + + public String selector() { + return selector; + } + } + + /** + * The sorting order for listing change requests. + */ + enum ChangeRequestSortingOrder { + DESCENDING, ASCENDING; + + public String selector() { + return this.name().toLowerCase(); + } + } + + /** + * Class that for specifying DNS record options. + */ + class DnsRecordOptions extends AbstractOption implements Serializable { + + private static final long serialVersionUID = 201601261646L; + + DnsRecordOptions(DnsServiceRpc.Option option, Object value) { + super(option, value); + } + + /** + * Returns an option to specify the DNS record's fields to be returned by the RPC call. + * + *

If this option is not provided all record fields are returned. {@code + * DnsRecordField.fields} can be used to specify only the fields of interest. The name of the + * DNS record always returned, even if not specified. {@link DnsRecordField} provides a list of + * fields that can be used. + */ + public static DnsRecordOptions fields(DnsRecordField... fields) { + StringBuilder builder = new StringBuilder(); + builder.append("rrsets(").append(DnsRecordField.selector(fields)).append(")"); + return new DnsRecordOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); + } + + /** + * Returns an option to specify a page token. + * + *

The page token (returned from a previous call to list) indicates from where listing should + * continue. + */ + public static DnsRecordOptions pageToken(String pageToken) { + return new DnsRecordOptions(DnsServiceRpc.Option.PAGE_TOKEN, pageToken); + } + + /** + * The maximum number of DNS records to return per RPC. + * + *

The server can return fewer records than requested. When there are more results than the + * page size, the server will return a page token that can be used to fetch other results. + */ + public static DnsRecordOptions pageSize(int pageSize) { + return new DnsRecordOptions(DnsServiceRpc.Option.PAGE_SIZE, pageSize); + } + + /** + * Restricts the list to return only zones with this fully qualified domain name. + */ + public static DnsRecordOptions dnsName(String dnsName) { + return new DnsRecordOptions(DnsServiceRpc.Option.DNS_NAME, dnsName); + } + } + + /** + * Class for specifying zone field options. + */ + class ZoneFieldOptions extends AbstractOption implements Serializable { + + private static final long serialVersionUID = -7294186261285469986L; + + ZoneFieldOptions(DnsServiceRpc.Option option, Object value) { + super(option, value); + } + + /** + * Returns an option to specify the zones's fields to be returned by the RPC call. + * + *

If this option is not provided all zone fields are returned. {@code + * ZoneFieldOptions.fields} can be used to specify only the fields of interest. Zone ID is + * always returned, even if not specified. {@link ZoneField} provides a list of fields that can + * be used. + */ + public static ZoneFieldOptions fields(ZoneField... fields) { + return new ZoneFieldOptions(DnsServiceRpc.Option.FIELDS, ZoneField.selector(fields)); + } + } + + /** + * Class for specifying zone listing options. + */ + class ZoneListOptions extends AbstractOption implements Serializable { + + private static final long serialVersionUID = -7922038132321229290L; + + ZoneListOptions(DnsServiceRpc.Option option, Object value) { + super(option, value); + } + + /** + * Returns an option to specify the zones's fields to be returned by the RPC call. + * + *

If this option is not provided all zone fields are returned. {@code + * ZoneFieldOptions.fields} can be used to specify only the fields of interest. Zone ID is + * always returned, even if not specified. {@link ZoneField} provides a list of fields that can + * be used. + */ + public static ZoneListOptions fields(ZoneField... fields) { + return new ZoneListOptions(DnsServiceRpc.Option.FIELDS, ZoneField.selector(fields)); + } + + /** + * Returns an option to specify a page token. + * + *

The page token (returned from a previous call to list) indicates from where listing should + * continue. + */ + public static ZoneListOptions pageToken(String pageToken) { + return new ZoneListOptions(DnsServiceRpc.Option.PAGE_TOKEN, pageToken); + } + + /** + * The maximum number of zones to return per RPC. + * + *

The server can return fewer zones than requested. When there are more results than the + * page size, the server will return a page token that can be used to fetch other results. + */ + public static ZoneListOptions pageSize(int pageSize) { + return new ZoneListOptions(DnsServiceRpc.Option.PAGE_SIZE, pageSize); + } + + /** + * Restricts the list to return only zones with this fully qualified domain name. + */ + public static ZoneListOptions dnsName(String dnsName) { + return new ZoneListOptions(DnsServiceRpc.Option.DNS_NAME, dnsName); + } + } + + /** + * Class for specifying project options. + */ + class ProjectOptions extends AbstractOption implements Serializable { + + private static final long serialVersionUID = 6817937338218847748L; + + ProjectOptions(DnsServiceRpc.Option option, Object value) { + super(option, value); + } + + /** + * Returns an option to specify the project's fields to be returned by the RPC call. + * + *

If this option is not provided all project fields are returned. {@code + * ProjectOptions.fields} can be used to specify only the fields of interest. Project ID is + * always returned, even if not specified. {@link ProjectField} provides a list of fields that + * can be used. + */ + public static ProjectOptions fields(ProjectField... fields) { + return new ProjectOptions(DnsServiceRpc.Option.FIELDS, ProjectField.selector(fields)); + } + } + + /** + * Class for specifying change request field options. + */ + class ChangeRequestFieldOptions extends AbstractOption implements Serializable { + + private static final long serialVersionUID = 1067273695061077782L; + + ChangeRequestFieldOptions(DnsServiceRpc.Option option, Object value) { + super(option, value); + } + + /** + * Returns an option to specify which fields of DNS records to be added by the {@link + * ChangeRequest} should be returned by the service. + * + *

If this option is not provided, all record fields are returned. {@code + * ChangeRequestFieldOptions.additionsFields} can be used to specify only the fields of + * interest. The name of the DNS record always returned, even if not specified. {@link + * DnsRecordField} provides a list of fields that can be used. + */ + public static ChangeRequestFieldOptions additionsFields(DnsRecordField... fields) { + StringBuilder builder = new StringBuilder(); + builder.append("additions(").append(DnsRecordField.selector(fields)).append(")"); + return new ChangeRequestFieldOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); + } + + /** + * Returns an option to specify which fields of DNS records to be deleted by the {@link + * ChangeRequest} should be returned by the service. + * + *

If this option is not provided, all record fields are returned. {@code + * ChangeRequestFieldOptions.deletionsFields} can be used to specify only the fields of + * interest. The name of the DNS record always returned, even if not specified. {@link + * DnsRecordField} provides a list of fields that can be used. + */ + public static ChangeRequestFieldOptions deletionsFields(DnsRecordField... fields) { + StringBuilder builder = new StringBuilder(); + builder.append("deletions(").append(DnsRecordField.selector(fields)).append(")"); + return new ChangeRequestFieldOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); + + } + + /** + * Returns an option to specify which fields of {@link ChangeRequest} should be returned by the + * service. + * + *

If this option is not provided all change request fields are returned. {@code + * ChangeRequestFieldOptions.fields} can be used to specify only the fields of interest. The ID + * of the change request is always returned, even if not specified. {@link ChangeRequestField} + * provides a list of fields that can be used. + */ + public static ChangeRequestFieldOptions fields(ChangeRequestField... fields) { + return new ChangeRequestFieldOptions( + DnsServiceRpc.Option.FIELDS, + ChangeRequestField.selector(fields) + ); + } + } + + /** + * Class for specifying change request listing options. + */ + class ChangeRequestListOptions extends AbstractOption implements Serializable { + + private static final long serialVersionUID = -900209143895376089L; + + ChangeRequestListOptions(DnsServiceRpc.Option option, Object value) { + super(option, value); + } + + /** + * Returns an option to specify which fields of DNS records to be added by the {@link + * ChangeRequest} should be returned by the service. + * + *

If this option is not provided, all record fields are returned. {@code + * ChangeRequestFieldOptions.additionsFields} can be used to specify only the fields of + * interest. The name of the DNS record always returned, even if not specified. {@link + * DnsRecordField} provides a list of fields that can be used. + */ + public static ChangeRequestListOptions additionsFields(DnsRecordField... fields) { + StringBuilder builder = new StringBuilder(); + builder.append("changes(additions(").append(DnsRecordField.selector(fields)).append("))"); + return new ChangeRequestListOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); + } + + /** + * Returns an option to specify which fields of DNS records to be deleted by the {@link + * ChangeRequest} should be returned by the service. + * + *

If this option is not provided, all record fields are returned. {@code + * ChangeRequestFieldOptions.deletionsFields} can be used to specify only the fields of + * interest. The name of the DNS record always returned, even if not specified. {@link + * DnsRecordField} provides a list of fields that can be used. + */ + public static ChangeRequestListOptions deletionsFields(DnsRecordField... fields) { + StringBuilder builder = new StringBuilder(); + builder.append("changes(deletions(").append(DnsRecordField.selector(fields)).append("))"); + return new ChangeRequestListOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); + } + + /** + * Returns an option to specify which fields of{@link ChangeRequest} should be returned by the + * service. + * + *

If this option is not provided all change request fields are returned. {@code + * ChangeRequestFieldOptions.fields} can be used to specify only the fields of interest. The ID + * of the change request is always returned, even if not specified. {@link ChangeRequestField} + * provides a list of fields that can be used. + */ + public static ChangeRequestListOptions fields(ChangeRequestField... fields) { + return new ChangeRequestListOptions( + DnsServiceRpc.Option.FIELDS, + ChangeRequestField.selector(fields) + ); + } + + /** + * Returns an option to specify a page token. + * + *

The page token (returned from a previous call to list) indicates from where listing should + * continue. + */ + public static ChangeRequestListOptions pageToken(String pageToken) { + return new ChangeRequestListOptions(DnsServiceRpc.Option.PAGE_TOKEN, pageToken); + } + + /** + * The maximum number of change requests to return per RPC. + * + *

The server can return fewer change requests than requested. When there are more results + * than the page size, the server will return a page token that can be used to fetch other + * results. + */ + public static ChangeRequestListOptions pageSize(int pageSize) { + return new ChangeRequestListOptions(DnsServiceRpc.Option.PAGE_SIZE, pageSize); + } + + /** + * Returns an option for specifying the sorting criterion of change requests. Note the the only + * currently supported criterion is the change sequence. + */ + public static ChangeRequestListOptions sortBy(ChangeRequestSortingKey key) { + return new ChangeRequestListOptions(DnsServiceRpc.Option.SORTING_KEY, key.selector()); + } + + /** + * Returns an option to specify whether the the change requests should be listed in ascending or + * descending order. + */ + public static ChangeRequestListOptions sortOrder(ChangeRequestSortingOrder order) { + return new ChangeRequestListOptions(DnsServiceRpc.Option.SORTING_ORDER, order.selector()); + } + } + + // TODO(mderka) Add methods. Created issue #596. +} From 4fdc8ee53b189a137aa990dca366db369e47cf9c Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 15:57:12 -0800 Subject: [PATCH 23/74] Added AbstractOption. --- .../com/google/gcloud/dns/AbstractOption.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java new file mode 100644 index 000000000000..6b6fbbf0606e --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java @@ -0,0 +1,69 @@ +/* + * 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.dns; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.MoreObjects; +import com.google.gcloud.spi.DnsServiceRpc; + +import java.io.Serializable; +import java.util.Objects; + +/** + * A base class for options. + */ +public abstract class AbstractOption implements Serializable { + + private static final long serialVersionUID = 201601261704L; + private final Object value; + private final DnsServiceRpc.Option rpcOption; + + AbstractOption(DnsServiceRpc.Option rpcOption, Object value) { + this.rpcOption = checkNotNull(rpcOption); + this.value = value; + } + + Object value() { + return value; + } + + DnsServiceRpc.Option rpcOption() { + return rpcOption; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof AbstractOption)) { + return false; + } + AbstractOption other = (AbstractOption) obj; + return Objects.equals(value, other.value); + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("value", value) + .toString(); + } +} From 06becd885dc0d4c45cd779a06be448b5179e77d1 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 15:58:13 -0800 Subject: [PATCH 24/74] Added DnsException. --- .../com/google/gcloud/dns/DnsException.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java new file mode 100644 index 000000000000..ab4a3df0f457 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java @@ -0,0 +1,37 @@ +/* + * 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.dns; + +import com.google.gcloud.BaseServiceException; + +/** + * DNS service exception. + */ +public class DnsException extends BaseServiceException { + + private static final long serialVersionUID = 490302380416260252L; + + public DnsException(int code, String message, boolean retryable) { + super(code, message, retryable); + } + + public DnsException(int code, String message, boolean retryable, Exception cause) { + super(code, message, retryable, cause); + } + + //TODO(mderka) Add translation and retry functionality. Created issue #593. +} From 81cedc4edf78e745817c831c1d7cde7653dfc4f8 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 16:00:19 -0800 Subject: [PATCH 25/74] Added DnsServiceRpc. --- .../com/google/gcloud/spi/DnsServiceRpc.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java new file mode 100644 index 000000000000..e97ee9a1b001 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java @@ -0,0 +1,56 @@ +/* + * 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.spi; + +import java.util.Map; + +public interface DnsServiceRpc { + + enum Option { + FIELDS("fields"), + PAGE_SIZE("maxSize"), + PAGE_TOKEN("pageToken"), + DNS_NAME("dnsName"), + SORTING_KEY("sortBy"), + SORTING_ORDER("sortOrder"); + + private final String value; + + Option(String value) { + this.value = value; + } + + public String value() { + return value; + } + + @SuppressWarnings("unchecked") + T get(Map options) { + return (T) options.get(this); + } + + String getString(Map options) { + return get(options); + } + + Integer getInt(Map options) { + return get(options); + } + } + + //TODO(mderka) add supported operations. Created issue #594. +} From bf1361c034633137ba395f6e565a1579fb4797fb Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 16:38:21 -0800 Subject: [PATCH 26/74] Added DnsServiceOptions and necessary dependencies. --- .../com/google/gcloud/dns/DnsService.java | 1 + .../google/gcloud/dns/DnsServiceFactory.java | 25 ++++++ .../google/gcloud/dns/DnsServiceOptions.java | 85 +++++++++++++++++++ .../gcloud/spi/DnsServiceRpcFactory.java | 26 ++++++ 4 files changed, 137 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java index 694b0b288154..9cbd60eccf5a 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java @@ -18,6 +18,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.Sets; +import com.google.gcloud.Service; import com.google.gcloud.spi.DnsServiceRpc; import java.io.Serializable; diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java new file mode 100644 index 000000000000..aaa0dfb68e1b --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java @@ -0,0 +1,25 @@ +/* + * 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.dns; + +import com.google.gcloud.ServiceFactory; + +/** + * An interface for DnsService factories. + */ +public interface DnsServiceFactory extends ServiceFactory { +} diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java new file mode 100644 index 000000000000..84eb9c33dcaa --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java @@ -0,0 +1,85 @@ +/* + * Copyright 2015 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.dns; + +import com.google.gcloud.ServiceOptions; +import com.google.gcloud.spi.DnsServiceRpc; +import com.google.gcloud.spi.DnsServiceRpcFactory; + +import java.util.Set; + +public class DnsServiceOptions + extends ServiceOptions { + + private static final long serialVersionUID = -5311219368450107146L; + + // TODO(mderka) Finish implementation. Created issue #595. + + public static class DefaultDnsServiceFactory implements DnsServiceFactory { + private static final DnsServiceFactory INSTANCE = new DefaultDnsServiceFactory(); + + @Override + public DnsService create(DnsServiceOptions options) { + // TODO(mderka) Implement. Created issue #595. + return null; + } + } + + public static class Builder extends ServiceOptions.Builder { + + private Builder() { + } + + private Builder(DnsServiceOptions options) { + super(options); + } + + @Override + public DnsServiceOptions build() { + return new DnsServiceOptions(this); + } + } + + private DnsServiceOptions(Builder builder) { + super(DnsServiceFactory.class, DnsServiceRpcFactory.class, builder); + } + + @Override + protected DnsServiceFactory defaultServiceFactory() { + return DefaultDnsServiceFactory.INSTANCE; + } + + @Override + protected DnsServiceRpcFactory defaultRpcFactory() { + return null; + } + + @Override + protected Set scopes() { + return null; + } + + @Override + public Builder toBuilder() { + return new Builder(this); + } + + public static Builder builder() { + return new Builder(); + } +} diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java new file mode 100644 index 000000000000..13ec9fe881c8 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java @@ -0,0 +1,26 @@ +/* + * 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.spi; + +import com.google.gcloud.dns.DnsServiceOptions; + +/** + * An interface for DnsServiceRpc factory. Implementation will be loaded via {@link + * java.util.ServiceLoader}. + */ +public interface DnsServiceRpcFactory extends ServiceRpcFactory { +} From 465f5327d81035666a12c1ef37bab0a1bfd55300 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 28 Jan 2016 18:15:47 -0800 Subject: [PATCH 27/74] Modified DnsException to pass tests. --- .../main/java/com/google/gcloud/dns/DnsException.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java index ab4a3df0f457..d18f6163a881 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java @@ -18,6 +18,8 @@ import com.google.gcloud.BaseServiceException; +import java.io.IOException; + /** * DNS service exception. */ @@ -25,12 +27,8 @@ public class DnsException extends BaseServiceException { private static final long serialVersionUID = 490302380416260252L; - public DnsException(int code, String message, boolean retryable) { - super(code, message, retryable); - } - - public DnsException(int code, String message, boolean retryable, Exception cause) { - super(code, message, retryable, cause); + public DnsException(IOException exception, boolean idempotent) { + super(exception, idempotent); } //TODO(mderka) Add translation and retry functionality. Created issue #593. From a8bee9c1e07337d1e710d378d7a600215e26c1ba Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 29 Jan 2016 16:10:25 -0800 Subject: [PATCH 28/74] Implements comments by @aozarov. --- .../com/google/gcloud/dns/AbstractOption.java | 17 +- .../gcloud/dns/{DnsService.java => Dns.java} | 229 +++++++----------- ...DnsServiceFactory.java => DnsFactory.java} | 4 +- ...DnsServiceOptions.java => DnsOptions.java} | 38 +-- .../spi/{DnsServiceRpc.java => DnsRpc.java} | 3 +- ...viceRpcFactory.java => DnsRpcFactory.java} | 6 +- 6 files changed, 120 insertions(+), 177 deletions(-) rename gcloud-java-dns/src/main/java/com/google/gcloud/dns/{DnsService.java => Dns.java} (51%) rename gcloud-java-dns/src/main/java/com/google/gcloud/dns/{DnsServiceFactory.java => DnsFactory.java} (84%) rename gcloud-java-dns/src/main/java/com/google/gcloud/dns/{DnsServiceOptions.java => DnsOptions.java} (59%) rename gcloud-java-dns/src/main/java/com/google/gcloud/spi/{DnsServiceRpc.java => DnsRpc.java} (96%) rename gcloud-java-dns/src/main/java/com/google/gcloud/spi/{DnsServiceRpcFactory.java => DnsRpcFactory.java} (74%) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java index 6b6fbbf0606e..a148468d14b5 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java @@ -19,7 +19,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; -import com.google.gcloud.spi.DnsServiceRpc; +import com.google.gcloud.spi.DnsRpc; import java.io.Serializable; import java.util.Objects; @@ -27,13 +27,13 @@ /** * A base class for options. */ -public abstract class AbstractOption implements Serializable { +abstract class AbstractOption implements Serializable { - private static final long serialVersionUID = 201601261704L; + private static final long serialVersionUID = -5912727967831484228L; private final Object value; - private final DnsServiceRpc.Option rpcOption; + private final DnsRpc.Option rpcOption; - AbstractOption(DnsServiceRpc.Option rpcOption, Object value) { + AbstractOption(DnsRpc.Option rpcOption, Object value) { this.rpcOption = checkNotNull(rpcOption); this.value = value; } @@ -42,7 +42,7 @@ Object value() { return value; } - DnsServiceRpc.Option rpcOption() { + DnsRpc.Option rpcOption() { return rpcOption; } @@ -52,18 +52,19 @@ public boolean equals(Object obj) { return false; } AbstractOption other = (AbstractOption) obj; - return Objects.equals(value, other.value); + return Objects.equals(value, other.value) && Objects.equals(rpcOption, other.rpcOption); } @Override public int hashCode() { - return Objects.hash(value); + return Objects.hash(value, rpcOption); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("value", value) + .add("rpcOption", rpcOption) .toString(); } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java similarity index 51% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 9cbd60eccf5a..737ec1a38699 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsService.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -19,7 +19,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.Sets; import com.google.gcloud.Service; -import com.google.gcloud.spi.DnsServiceRpc; +import com.google.gcloud.spi.DnsRpc; import java.io.Serializable; import java.util.Set; @@ -29,13 +29,13 @@ * * @see Google Cloud DNS */ -public interface DnsService extends Service { +public interface Dns extends Service { /** * The fields of a project. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code DnsService#getProjectInfo(ProjectOptions...)}. Project ID is always returned, even if + * {@code Dns#getProjectInfo(ProjectGetOption...)}. Project ID is always returned, even if * not specified. */ enum ProjectField { @@ -49,7 +49,7 @@ enum ProjectField { this.selector = selector; } - public String selector() { + String selector() { return selector; } @@ -67,9 +67,8 @@ static String selector(ProjectField... fields) { * The fields of a zone. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code DnsService#getZone(BigInteger, ZoneFieldOptions...)} or {@code - * DnsService#getZone(String, ZoneFieldOptions...)}. The ID is always returned, even if not - * specified. + * {@code Dns#getZone(BigInteger, ZoneFieldOption...)} or {@code Dns#getZone(String, + * ZoneFieldOption...)}. The ID is always returned, even if not specified. */ enum ZoneField { CREATION_TIME("creationTime"), @@ -86,7 +85,7 @@ enum ZoneField { this.selector = selector; } - public String selector() { + String selector() { return selector; } @@ -104,8 +103,8 @@ static String selector(ZoneField... fields) { * The fields of a DNS record. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code DnsService#listDnsRecords(BigInteger, DnsRecordOptions...)} or {@code - * DnsService#listDnsRecords(String, DnsRecordOptions...)}. The name is always returned even if + * {@code Dns#listDnsRecords(BigInteger, DnsRecordListOption...)} or {@code + * Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if * not selected. */ enum DnsRecordField { @@ -120,7 +119,7 @@ enum DnsRecordField { this.selector = selector; } - public String selector() { + String selector() { return selector; } @@ -138,8 +137,8 @@ static String selector(DnsRecordField... fields) { * The fields of a change request. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code DnsService#applyChangeRequest(ChangeRequest, BigInteger, ChangeRequestFieldOptions...)} - * or {@code DnsService#applyChangeRequest(ChangeRequest, String, ChangeRequestFieldOptions...)} + * {@code Dns#applyChangeRequest(ChangeRequest, BigInteger, ChangeRequestOption...)} + * or {@code Dns#applyChangeRequest(ChangeRequest, String, ChangeRequestOption...)} * The ID is always returned even if not selected. */ enum ChangeRequestField { @@ -155,7 +154,7 @@ enum ChangeRequestField { this.selector = selector; } - public String selector() { + String selector() { return selector; } @@ -171,10 +170,10 @@ static String selector(ChangeRequestField... fields) { /** * The sorting keys for listing change requests. The only currently supported sorting key is the - * change sequence. + * when the change request was created. */ enum ChangeRequestSortingKey { - CHANGE_SEQUENCE("changeSequence"); + TIME_CREATED("changeSequence"); private final String selector; @@ -182,15 +181,15 @@ enum ChangeRequestSortingKey { this.selector = selector; } - public String selector() { + String selector() { return selector; } } /** - * The sorting order for listing change requests. + * The sorting order for listing. */ - enum ChangeRequestSortingOrder { + enum SortingOrder { DESCENDING, ASCENDING; public String selector() { @@ -201,11 +200,11 @@ public String selector() { /** * Class that for specifying DNS record options. */ - class DnsRecordOptions extends AbstractOption implements Serializable { + class DnsRecordListOption extends AbstractOption implements Serializable { - private static final long serialVersionUID = 201601261646L; + private static final long serialVersionUID = 1009627025381096098L; - DnsRecordOptions(DnsServiceRpc.Option option, Object value) { + DnsRecordListOption(DnsRpc.Option option, Object value) { super(option, value); } @@ -217,10 +216,10 @@ class DnsRecordOptions extends AbstractOption implements Serializable { * DNS record always returned, even if not specified. {@link DnsRecordField} provides a list of * fields that can be used. */ - public static DnsRecordOptions fields(DnsRecordField... fields) { + public static DnsRecordListOption fields(DnsRecordField... fields) { StringBuilder builder = new StringBuilder(); - builder.append("rrsets(").append(DnsRecordField.selector(fields)).append(")"); - return new DnsRecordOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); + builder.append("rrsets(").append(DnsRecordField.selector(fields)).append(')'); + return new DnsRecordListOption(DnsRpc.Option.FIELDS, builder.toString()); } /** @@ -229,8 +228,8 @@ public static DnsRecordOptions fields(DnsRecordField... fields) { *

The page token (returned from a previous call to list) indicates from where listing should * continue. */ - public static DnsRecordOptions pageToken(String pageToken) { - return new DnsRecordOptions(DnsServiceRpc.Option.PAGE_TOKEN, pageToken); + public static DnsRecordListOption pageToken(String pageToken) { + return new DnsRecordListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); } /** @@ -239,26 +238,34 @@ public static DnsRecordOptions pageToken(String pageToken) { *

The server can return fewer records than requested. When there are more results than the * page size, the server will return a page token that can be used to fetch other results. */ - public static DnsRecordOptions pageSize(int pageSize) { - return new DnsRecordOptions(DnsServiceRpc.Option.PAGE_SIZE, pageSize); + public static DnsRecordListOption pageSize(int pageSize) { + return new DnsRecordListOption(DnsRpc.Option.PAGE_SIZE, pageSize); } /** - * Restricts the list to return only zones with this fully qualified domain name. + * Restricts the list to only DNS records with this fully qualified domain name. */ - public static DnsRecordOptions dnsName(String dnsName) { - return new DnsRecordOptions(DnsServiceRpc.Option.DNS_NAME, dnsName); + public static DnsRecordListOption dnsName(String dnsName) { + return new DnsRecordListOption(DnsRpc.Option.DNS_NAME, dnsName); + } + + /** + * Restricts the list to return only records of this type. If present, {@link + * Dns.DnsRecordListOption#dnsName(String)} must also be present. + */ + public static DnsRecordListOption type(DnsRecord.Type type) { + return new DnsRecordListOption(DnsRpc.Option.DNS_TYPE, type); } } /** * Class for specifying zone field options. */ - class ZoneFieldOptions extends AbstractOption implements Serializable { + class ZoneFieldOption extends AbstractOption implements Serializable { - private static final long serialVersionUID = -7294186261285469986L; + private static final long serialVersionUID = -8065564464895945037L; - ZoneFieldOptions(DnsServiceRpc.Option option, Object value) { + ZoneFieldOption(DnsRpc.Option option, Object value) { super(option, value); } @@ -266,23 +273,23 @@ class ZoneFieldOptions extends AbstractOption implements Serializable { * Returns an option to specify the zones's fields to be returned by the RPC call. * *

If this option is not provided all zone fields are returned. {@code - * ZoneFieldOptions.fields} can be used to specify only the fields of interest. Zone ID is - * always returned, even if not specified. {@link ZoneField} provides a list of fields that can - * be used. + * ZoneFieldOption.fields} can be used to specify only the fields of interest. Zone ID is always + * returned, even if not specified. {@link ZoneField} provides a list of fields that can be + * used. */ - public static ZoneFieldOptions fields(ZoneField... fields) { - return new ZoneFieldOptions(DnsServiceRpc.Option.FIELDS, ZoneField.selector(fields)); + public static ZoneFieldOption fields(ZoneField... fields) { + return new ZoneFieldOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); } } /** * Class for specifying zone listing options. */ - class ZoneListOptions extends AbstractOption implements Serializable { + class ZoneListOption extends AbstractOption implements Serializable { - private static final long serialVersionUID = -7922038132321229290L; + private static final long serialVersionUID = -2830645032124504717L; - ZoneListOptions(DnsServiceRpc.Option option, Object value) { + ZoneListOption(DnsRpc.Option option, Object value) { super(option, value); } @@ -290,12 +297,12 @@ class ZoneListOptions extends AbstractOption implements Serializable { * Returns an option to specify the zones's fields to be returned by the RPC call. * *

If this option is not provided all zone fields are returned. {@code - * ZoneFieldOptions.fields} can be used to specify only the fields of interest. Zone ID is - * always returned, even if not specified. {@link ZoneField} provides a list of fields that can - * be used. + * ZoneFieldOption.fields} can be used to specify only the fields of interest. Zone ID is always + * returned, even if not specified. {@link ZoneField} provides a list of fields that can be + * used. */ - public static ZoneListOptions fields(ZoneField... fields) { - return new ZoneListOptions(DnsServiceRpc.Option.FIELDS, ZoneField.selector(fields)); + public static ZoneListOption fields(ZoneField... fields) { + return new ZoneListOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); } /** @@ -304,8 +311,8 @@ public static ZoneListOptions fields(ZoneField... fields) { *

The page token (returned from a previous call to list) indicates from where listing should * continue. */ - public static ZoneListOptions pageToken(String pageToken) { - return new ZoneListOptions(DnsServiceRpc.Option.PAGE_TOKEN, pageToken); + public static ZoneListOption pageToken(String pageToken) { + return new ZoneListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); } /** @@ -314,26 +321,19 @@ public static ZoneListOptions pageToken(String pageToken) { *

The server can return fewer zones than requested. When there are more results than the * page size, the server will return a page token that can be used to fetch other results. */ - public static ZoneListOptions pageSize(int pageSize) { - return new ZoneListOptions(DnsServiceRpc.Option.PAGE_SIZE, pageSize); - } - - /** - * Restricts the list to return only zones with this fully qualified domain name. - */ - public static ZoneListOptions dnsName(String dnsName) { - return new ZoneListOptions(DnsServiceRpc.Option.DNS_NAME, dnsName); + public static ZoneListOption pageSize(int pageSize) { + return new ZoneListOption(DnsRpc.Option.PAGE_SIZE, pageSize); } } /** * Class for specifying project options. */ - class ProjectOptions extends AbstractOption implements Serializable { + class ProjectGetOption extends AbstractOption implements Serializable { private static final long serialVersionUID = 6817937338218847748L; - ProjectOptions(DnsServiceRpc.Option option, Object value) { + ProjectGetOption(DnsRpc.Option option, Object value) { super(option, value); } @@ -341,69 +341,38 @@ class ProjectOptions extends AbstractOption implements Serializable { * Returns an option to specify the project's fields to be returned by the RPC call. * *

If this option is not provided all project fields are returned. {@code - * ProjectOptions.fields} can be used to specify only the fields of interest. Project ID is + * ProjectGetOption.fields} can be used to specify only the fields of interest. Project ID is * always returned, even if not specified. {@link ProjectField} provides a list of fields that * can be used. */ - public static ProjectOptions fields(ProjectField... fields) { - return new ProjectOptions(DnsServiceRpc.Option.FIELDS, ProjectField.selector(fields)); + public static ProjectGetOption fields(ProjectField... fields) { + return new ProjectGetOption(DnsRpc.Option.FIELDS, ProjectField.selector(fields)); } } /** * Class for specifying change request field options. */ - class ChangeRequestFieldOptions extends AbstractOption implements Serializable { + class ChangeRequestOption extends AbstractOption implements Serializable { private static final long serialVersionUID = 1067273695061077782L; - ChangeRequestFieldOptions(DnsServiceRpc.Option option, Object value) { + ChangeRequestOption(DnsRpc.Option option, Object value) { super(option, value); } - /** - * Returns an option to specify which fields of DNS records to be added by the {@link - * ChangeRequest} should be returned by the service. - * - *

If this option is not provided, all record fields are returned. {@code - * ChangeRequestFieldOptions.additionsFields} can be used to specify only the fields of - * interest. The name of the DNS record always returned, even if not specified. {@link - * DnsRecordField} provides a list of fields that can be used. - */ - public static ChangeRequestFieldOptions additionsFields(DnsRecordField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("additions(").append(DnsRecordField.selector(fields)).append(")"); - return new ChangeRequestFieldOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); - } - - /** - * Returns an option to specify which fields of DNS records to be deleted by the {@link - * ChangeRequest} should be returned by the service. - * - *

If this option is not provided, all record fields are returned. {@code - * ChangeRequestFieldOptions.deletionsFields} can be used to specify only the fields of - * interest. The name of the DNS record always returned, even if not specified. {@link - * DnsRecordField} provides a list of fields that can be used. - */ - public static ChangeRequestFieldOptions deletionsFields(DnsRecordField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("deletions(").append(DnsRecordField.selector(fields)).append(")"); - return new ChangeRequestFieldOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); - - } - /** * Returns an option to specify which fields of {@link ChangeRequest} should be returned by the * service. * *

If this option is not provided all change request fields are returned. {@code - * ChangeRequestFieldOptions.fields} can be used to specify only the fields of interest. The ID + * ChangeRequestOption.fields} can be used to specify only the fields of interest. The ID * of the change request is always returned, even if not specified. {@link ChangeRequestField} * provides a list of fields that can be used. */ - public static ChangeRequestFieldOptions fields(ChangeRequestField... fields) { - return new ChangeRequestFieldOptions( - DnsServiceRpc.Option.FIELDS, + public static ChangeRequestOption fields(ChangeRequestField... fields) { + return new ChangeRequestOption( + DnsRpc.Option.FIELDS, ChangeRequestField.selector(fields) ); } @@ -412,56 +381,26 @@ public static ChangeRequestFieldOptions fields(ChangeRequestField... fields) { /** * Class for specifying change request listing options. */ - class ChangeRequestListOptions extends AbstractOption implements Serializable { + class ChangeRequestListOption extends AbstractOption implements Serializable { private static final long serialVersionUID = -900209143895376089L; - ChangeRequestListOptions(DnsServiceRpc.Option option, Object value) { + ChangeRequestListOption(DnsRpc.Option option, Object value) { super(option, value); } - /** - * Returns an option to specify which fields of DNS records to be added by the {@link - * ChangeRequest} should be returned by the service. - * - *

If this option is not provided, all record fields are returned. {@code - * ChangeRequestFieldOptions.additionsFields} can be used to specify only the fields of - * interest. The name of the DNS record always returned, even if not specified. {@link - * DnsRecordField} provides a list of fields that can be used. - */ - public static ChangeRequestListOptions additionsFields(DnsRecordField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("changes(additions(").append(DnsRecordField.selector(fields)).append("))"); - return new ChangeRequestListOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); - } - - /** - * Returns an option to specify which fields of DNS records to be deleted by the {@link - * ChangeRequest} should be returned by the service. - * - *

If this option is not provided, all record fields are returned. {@code - * ChangeRequestFieldOptions.deletionsFields} can be used to specify only the fields of - * interest. The name of the DNS record always returned, even if not specified. {@link - * DnsRecordField} provides a list of fields that can be used. - */ - public static ChangeRequestListOptions deletionsFields(DnsRecordField... fields) { - StringBuilder builder = new StringBuilder(); - builder.append("changes(deletions(").append(DnsRecordField.selector(fields)).append("))"); - return new ChangeRequestListOptions(DnsServiceRpc.Option.FIELDS, builder.toString()); - } - /** * Returns an option to specify which fields of{@link ChangeRequest} should be returned by the * service. * *

If this option is not provided all change request fields are returned. {@code - * ChangeRequestFieldOptions.fields} can be used to specify only the fields of interest. The ID + * ChangeRequestOption.fields} can be used to specify only the fields of interest. The ID * of the change request is always returned, even if not specified. {@link ChangeRequestField} * provides a list of fields that can be used. */ - public static ChangeRequestListOptions fields(ChangeRequestField... fields) { - return new ChangeRequestListOptions( - DnsServiceRpc.Option.FIELDS, + public static ChangeRequestListOption fields(ChangeRequestField... fields) { + return new ChangeRequestListOption( + DnsRpc.Option.FIELDS, ChangeRequestField.selector(fields) ); } @@ -472,8 +411,8 @@ public static ChangeRequestListOptions fields(ChangeRequestField... fields) { *

The page token (returned from a previous call to list) indicates from where listing should * continue. */ - public static ChangeRequestListOptions pageToken(String pageToken) { - return new ChangeRequestListOptions(DnsServiceRpc.Option.PAGE_TOKEN, pageToken); + public static ChangeRequestListOption pageToken(String pageToken) { + return new ChangeRequestListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); } /** @@ -483,24 +422,24 @@ public static ChangeRequestListOptions pageToken(String pageToken) { * than the page size, the server will return a page token that can be used to fetch other * results. */ - public static ChangeRequestListOptions pageSize(int pageSize) { - return new ChangeRequestListOptions(DnsServiceRpc.Option.PAGE_SIZE, pageSize); + public static ChangeRequestListOption pageSize(int pageSize) { + return new ChangeRequestListOption(DnsRpc.Option.PAGE_SIZE, pageSize); } /** * Returns an option for specifying the sorting criterion of change requests. Note the the only * currently supported criterion is the change sequence. */ - public static ChangeRequestListOptions sortBy(ChangeRequestSortingKey key) { - return new ChangeRequestListOptions(DnsServiceRpc.Option.SORTING_KEY, key.selector()); + public static ChangeRequestListOption sortBy(ChangeRequestSortingKey key) { + return new ChangeRequestListOption(DnsRpc.Option.SORTING_KEY, key.selector()); } /** * Returns an option to specify whether the the change requests should be listed in ascending or * descending order. */ - public static ChangeRequestListOptions sortOrder(ChangeRequestSortingOrder order) { - return new ChangeRequestListOptions(DnsServiceRpc.Option.SORTING_ORDER, order.selector()); + public static ChangeRequestListOption sortOrder(SortingOrder order) { + return new ChangeRequestListOption(DnsRpc.Option.SORTING_ORDER, order.selector()); } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsFactory.java similarity index 84% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsFactory.java index aaa0dfb68e1b..734652afb24d 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceFactory.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsFactory.java @@ -19,7 +19,7 @@ import com.google.gcloud.ServiceFactory; /** - * An interface for DnsService factories. + * An interface for Dns factories. */ -public interface DnsServiceFactory extends ServiceFactory { +public interface DnsFactory extends ServiceFactory { } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java similarity index 59% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java index 84eb9c33dcaa..3663211d3b41 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsServiceOptions.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsOptions.java @@ -16,62 +16,64 @@ package com.google.gcloud.dns; +import com.google.common.collect.Sets; import com.google.gcloud.ServiceOptions; -import com.google.gcloud.spi.DnsServiceRpc; -import com.google.gcloud.spi.DnsServiceRpcFactory; +import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.spi.DnsRpcFactory; import java.util.Set; -public class DnsServiceOptions - extends ServiceOptions { +public class DnsOptions + extends ServiceOptions { private static final long serialVersionUID = -5311219368450107146L; // TODO(mderka) Finish implementation. Created issue #595. - public static class DefaultDnsServiceFactory implements DnsServiceFactory { - private static final DnsServiceFactory INSTANCE = new DefaultDnsServiceFactory(); + public static class DefaultDnsFactory implements DnsFactory { + private static final DnsFactory INSTANCE = new DefaultDnsFactory(); @Override - public DnsService create(DnsServiceOptions options) { + public Dns create(DnsOptions options) { // TODO(mderka) Implement. Created issue #595. return null; } } - public static class Builder extends ServiceOptions.Builder { + public static class Builder extends ServiceOptions.Builder { private Builder() { } - private Builder(DnsServiceOptions options) { + private Builder(DnsOptions options) { super(options); } @Override - public DnsServiceOptions build() { - return new DnsServiceOptions(this); + public DnsOptions build() { + return new DnsOptions(this); } } - private DnsServiceOptions(Builder builder) { - super(DnsServiceFactory.class, DnsServiceRpcFactory.class, builder); + private DnsOptions(Builder builder) { + super(DnsFactory.class, DnsRpcFactory.class, builder); } @Override - protected DnsServiceFactory defaultServiceFactory() { - return DefaultDnsServiceFactory.INSTANCE; + protected DnsFactory defaultServiceFactory() { + return DefaultDnsFactory.INSTANCE; } @Override - protected DnsServiceRpcFactory defaultRpcFactory() { + protected DnsRpcFactory defaultRpcFactory() { return null; } @Override protected Set scopes() { - return null; + // TODO(mderka) Verify. + return Sets.newHashSet("ndev.clouddns.readwrite"); } @Override diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java similarity index 96% rename from gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java index e97ee9a1b001..02afb7309c6a 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java @@ -18,13 +18,14 @@ import java.util.Map; -public interface DnsServiceRpc { +public interface DnsRpc { enum Option { FIELDS("fields"), PAGE_SIZE("maxSize"), PAGE_TOKEN("pageToken"), DNS_NAME("dnsName"), + DNS_TYPE("type"), SORTING_KEY("sortBy"), SORTING_ORDER("sortOrder"); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpcFactory.java similarity index 74% rename from gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpcFactory.java index 13ec9fe881c8..3d25f09bb1e5 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsServiceRpcFactory.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpcFactory.java @@ -16,11 +16,11 @@ package com.google.gcloud.spi; -import com.google.gcloud.dns.DnsServiceOptions; +import com.google.gcloud.dns.DnsOptions; /** - * An interface for DnsServiceRpc factory. Implementation will be loaded via {@link + * An interface for DnsRpc factory. Implementation will be loaded via {@link * java.util.ServiceLoader}. */ -public interface DnsServiceRpcFactory extends ServiceRpcFactory { +public interface DnsRpcFactory extends ServiceRpcFactory { } From 762483b94f6c95aa3f860803ead53a962f41d336 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 29 Jan 2016 16:11:13 -0800 Subject: [PATCH 29/74] Makes ProjectInfo.Quota serializable. Fixed #599. --- .../src/main/java/com/google/gcloud/dns/ProjectInfo.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index 4db0497946b1..f7b12b94bae8 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -44,8 +44,9 @@ public class ProjectInfo implements Serializable { * @see Google Cloud DNS * documentation */ - public static class Quota { + public static class Quota implements Serializable { + private static final long serialVersionUID = 6854685970605363639L; private final int zones; private final int resourceRecordsPerRrset; private final int rrsetAdditionsPerChange; From e17bedb4640e6d5c434670eb03a4ea6b2f9028c9 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 29 Jan 2016 17:50:18 -0800 Subject: [PATCH 30/74] Implemented DnsOptions up to two unavailable classes. --- .../com/google/gcloud/dns/DnsOptions.java | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) 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 3663211d3b41..a5c689f4c719 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 @@ -16,7 +16,7 @@ package com.google.gcloud.dns; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet; import com.google.gcloud.ServiceOptions; import com.google.gcloud.spi.DnsRpc; import com.google.gcloud.spi.DnsRpcFactory; @@ -26,16 +26,28 @@ public class DnsOptions extends ServiceOptions { - private static final long serialVersionUID = -5311219368450107146L; - - // TODO(mderka) Finish implementation. Created issue #595. + private static final long serialVersionUID = -519128051411747771L; + private static final String GC_DNS_RW = "https://www.googleapis.com/auth/ndev.clouddns.readwrite"; + private static final String GC_DNS_R = "https://www.googleapis.com/auth/ndev.clouddns.readonly"; + private static final Set SCOPES = ImmutableSet.of(GC_DNS_RW, GC_DNS_R); public static class DefaultDnsFactory implements DnsFactory { private static final DnsFactory INSTANCE = new DefaultDnsFactory(); @Override public Dns create(DnsOptions options) { - // TODO(mderka) Implement. Created issue #595. + // TODO(mderka) Implement when DnsImpl is available. Created issue #595. + return null; + } + } + + public static class DefaultDnsRpcFactory implements DnsRpcFactory { + + private static final DnsRpcFactory INSTANCE = new DefaultDnsRpcFactory(); + + @Override + public DnsRpc create(DnsOptions options) { + // TODO(mderka) Implement when DefaultDnsRpc is available. Created issue #595. return null; } } @@ -60,11 +72,13 @@ private DnsOptions(Builder builder) { super(DnsFactory.class, DnsRpcFactory.class, builder); } + @SuppressWarnings("unchecked") @Override protected DnsFactory defaultServiceFactory() { return DefaultDnsFactory.INSTANCE; } + @SuppressWarnings("unchecked") @Override protected DnsRpcFactory defaultRpcFactory() { return null; @@ -72,10 +86,10 @@ protected DnsRpcFactory defaultRpcFactory() { @Override protected Set scopes() { - // TODO(mderka) Verify. - return Sets.newHashSet("ndev.clouddns.readwrite"); + return SCOPES; } + @SuppressWarnings("unchecked") @Override public Builder toBuilder() { return new Builder(this); From adf5c1cda7b849d7e1064dba7dae24e1fea5061d Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 1 Feb 2016 09:12:51 -0800 Subject: [PATCH 31/74] Added test for AbstractOption. --- .../main/java/com/google/gcloud/dns/Dns.java | 2 +- .../google/gcloud/dns/AbstractOptionTest.java | 70 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 737ec1a38699..76b11972bb7e 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -193,7 +193,7 @@ enum SortingOrder { DESCENDING, ASCENDING; public String selector() { - return this.name().toLowerCase(); + return name().toLowerCase(); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java new file mode 100644 index 000000000000..3c578c53d0d1 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java @@ -0,0 +1,70 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.fail; + +import com.google.gcloud.spi.DnsRpc; + +import org.junit.Test; + +public class AbstractOptionTest { + + private static final DnsRpc.Option RPC_OPTION = DnsRpc.Option.DNS_TYPE; + private static final DnsRpc.Option ANOTHER_RPC_OPTION = DnsRpc.Option.DNS_NAME; + private static final String VALUE = "some value"; + private static final String OTHER_VALUE = "another value"; + private static final AbstractOption OPTION = new AbstractOption(RPC_OPTION, VALUE) { + }; + private static final AbstractOption OPTION_EQUALS = new AbstractOption(RPC_OPTION, VALUE) { + }; + private static final AbstractOption OPTION_NOT_EQUALS1 = + new AbstractOption(RPC_OPTION, OTHER_VALUE) { + }; + private static final AbstractOption OPTION_NOT_EQUALS2 = + new AbstractOption(ANOTHER_RPC_OPTION, VALUE) { + }; + + @Test + public void testEquals() { + assertEquals(OPTION, OPTION_EQUALS); + assertNotEquals(OPTION, OPTION_NOT_EQUALS1); + assertNotEquals(OPTION, OPTION_NOT_EQUALS2); + } + + @Test + public void testHashCode() { + assertEquals(OPTION.hashCode(), OPTION_EQUALS.hashCode()); + } + + @Test + public void testConstructor() { + assertEquals(RPC_OPTION, OPTION.rpcOption()); + assertEquals(VALUE, OPTION.value()); + try { + new AbstractOption(null, VALUE) { + }; + fail("Cannot build with empty option."); + } catch (NullPointerException e) { + // expected + } + new AbstractOption(RPC_OPTION, null) { + }; // null value is ok + } +} From a9cc927e002277face656af9f059175192d31c3d Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 1 Feb 2016 14:20:33 -0800 Subject: [PATCH 32/74] Implemented comments by @aozarov. Added test for option accessors. --- .../main/java/com/google/gcloud/dns/Dns.java | 86 ++++------- .../com/google/gcloud/dns/DnsOptions.java | 3 +- .../java/com/google/gcloud/spi/DnsRpc.java | 1 - .../java/com/google/gcloud/dns/DnsTest.java | 141 ++++++++++++++++++ 4 files changed, 173 insertions(+), 58 deletions(-) create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 76b11972bb7e..352c7791e18d 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -31,12 +31,14 @@ */ public interface Dns extends Service { + + /** * The fields of a project. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#getProjectInfo(ProjectGetOption...)}. Project ID is always returned, even if - * not specified. + * {@code Dns#getProjectInfo(ProjectGetOption...)}. Project ID is always returned, even if not + * specified. */ enum ProjectField { PROJECT_ID("id"), @@ -67,8 +69,8 @@ static String selector(ProjectField... fields) { * The fields of a zone. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#getZone(BigInteger, ZoneFieldOption...)} or {@code Dns#getZone(String, - * ZoneFieldOption...)}. The ID is always returned, even if not specified. + * {@code Dns#getZone(BigInteger, ZoneOption...)} or {@code Dns#getZone(String, ZoneOption...)}. + * The ID is always returned, even if not specified. */ enum ZoneField { CREATION_TIME("creationTime"), @@ -104,8 +106,8 @@ static String selector(ZoneField... fields) { * *

These values can be used to specify the fields to include in a partial response when calling * {@code Dns#listDnsRecords(BigInteger, DnsRecordListOption...)} or {@code - * Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if - * not selected. + * Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if not + * selected. */ enum DnsRecordField { DNS_RECORDS("rrdatas"), @@ -137,9 +139,9 @@ static String selector(DnsRecordField... fields) { * The fields of a change request. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#applyChangeRequest(ChangeRequest, BigInteger, ChangeRequestOption...)} - * or {@code Dns#applyChangeRequest(ChangeRequest, String, ChangeRequestOption...)} - * The ID is always returned even if not selected. + * {@code Dns#applyChangeRequest(ChangeRequest, BigInteger, ChangeRequestOption...)} or {@code + * Dns#applyChangeRequest(ChangeRequest, String, ChangeRequestOption...)} The ID is always + * returned even if not selected. */ enum ChangeRequestField { ID("id"), @@ -168,24 +170,6 @@ static String selector(ChangeRequestField... fields) { } } - /** - * The sorting keys for listing change requests. The only currently supported sorting key is the - * when the change request was created. - */ - enum ChangeRequestSortingKey { - TIME_CREATED("changeSequence"); - - private final String selector; - - ChangeRequestSortingKey(String selector) { - this.selector = selector; - } - - String selector() { - return selector; - } - } - /** * The sorting order for listing. */ @@ -261,24 +245,23 @@ public static DnsRecordListOption type(DnsRecord.Type type) { /** * Class for specifying zone field options. */ - class ZoneFieldOption extends AbstractOption implements Serializable { + class ZoneOption extends AbstractOption implements Serializable { private static final long serialVersionUID = -8065564464895945037L; - ZoneFieldOption(DnsRpc.Option option, Object value) { + ZoneOption(DnsRpc.Option option, Object value) { super(option, value); } /** * Returns an option to specify the zones's fields to be returned by the RPC call. * - *

If this option is not provided all zone fields are returned. {@code - * ZoneFieldOption.fields} can be used to specify only the fields of interest. Zone ID is always - * returned, even if not specified. {@link ZoneField} provides a list of fields that can be - * used. + *

If this option is not provided all zone fields are returned. {@code ZoneOption.fields} can + * be used to specify only the fields of interest. Zone ID is always returned, even if not + * specified. {@link ZoneField} provides a list of fields that can be used. */ - public static ZoneFieldOption fields(ZoneField... fields) { - return new ZoneFieldOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); + public static ZoneOption fields(ZoneField... fields) { + return new ZoneOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); } } @@ -296,10 +279,9 @@ class ZoneListOption extends AbstractOption implements Serializable { /** * Returns an option to specify the zones's fields to be returned by the RPC call. * - *

If this option is not provided all zone fields are returned. {@code - * ZoneFieldOption.fields} can be used to specify only the fields of interest. Zone ID is always - * returned, even if not specified. {@link ZoneField} provides a list of fields that can be - * used. + *

If this option is not provided all zone fields are returned. {@code ZoneOption.fields} can + * be used to specify only the fields of interest. Zone ID is always returned, even if not + * specified. {@link ZoneField} provides a list of fields that can be used. */ public static ZoneListOption fields(ZoneField... fields) { return new ZoneListOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); @@ -366,9 +348,9 @@ class ChangeRequestOption extends AbstractOption implements Serializable { * service. * *

If this option is not provided all change request fields are returned. {@code - * ChangeRequestOption.fields} can be used to specify only the fields of interest. The ID - * of the change request is always returned, even if not specified. {@link ChangeRequestField} - * provides a list of fields that can be used. + * ChangeRequestOption.fields} can be used to specify only the fields of interest. The ID of the + * change request is always returned, even if not specified. {@link ChangeRequestField} provides + * a list of fields that can be used. */ public static ChangeRequestOption fields(ChangeRequestField... fields) { return new ChangeRequestOption( @@ -394,9 +376,9 @@ class ChangeRequestListOption extends AbstractOption implements Serializable { * service. * *

If this option is not provided all change request fields are returned. {@code - * ChangeRequestOption.fields} can be used to specify only the fields of interest. The ID - * of the change request is always returned, even if not specified. {@link ChangeRequestField} - * provides a list of fields that can be used. + * ChangeRequestOption.fields} can be used to specify only the fields of interest. The ID of the + * change request is always returned, even if not specified. {@link ChangeRequestField} provides + * a list of fields that can be used. */ public static ChangeRequestListOption fields(ChangeRequestField... fields) { return new ChangeRequestListOption( @@ -427,16 +409,10 @@ public static ChangeRequestListOption pageSize(int pageSize) { } /** - * Returns an option for specifying the sorting criterion of change requests. Note the the only - * currently supported criterion is the change sequence. - */ - public static ChangeRequestListOption sortBy(ChangeRequestSortingKey key) { - return new ChangeRequestListOption(DnsRpc.Option.SORTING_KEY, key.selector()); - } - - /** - * Returns an option to specify whether the the change requests should be listed in ascending or - * descending order. + * Returns an option to specify whether the the change requests should be listed in ascending + * (most-recent last) or descending (most-recent first) order with respect to when the change + * request was accepted by the server. If this option is not provided, the listing order is + * undefined. */ public static ChangeRequestListOption sortOrder(SortingOrder order) { return new ChangeRequestListOption(DnsRpc.Option.SORTING_ORDER, order.selector()); 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 a5c689f4c719..1845467c2537 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 @@ -28,8 +28,7 @@ public class DnsOptions private static final long serialVersionUID = -519128051411747771L; private static final String GC_DNS_RW = "https://www.googleapis.com/auth/ndev.clouddns.readwrite"; - private static final String GC_DNS_R = "https://www.googleapis.com/auth/ndev.clouddns.readonly"; - private static final Set SCOPES = ImmutableSet.of(GC_DNS_RW, GC_DNS_R); + private static final Set SCOPES = ImmutableSet.of(GC_DNS_RW); public static class DefaultDnsFactory implements DnsFactory { private static final DnsFactory INSTANCE = new DefaultDnsFactory(); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java index 02afb7309c6a..f6a0f330a327 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java @@ -26,7 +26,6 @@ enum Option { PAGE_TOKEN("pageToken"), DNS_NAME("dnsName"), DNS_TYPE("type"), - SORTING_KEY("sortBy"), SORTING_ORDER("sortOrder"); private final String value; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java new file mode 100644 index 000000000000..2e98dbd46de4 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -0,0 +1,141 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gcloud.spi.DnsRpc; + +import org.junit.Test; + +public class DnsTest { + + private static final Integer PAGE_SIZE = 20; + private static final String PAGE_TOKEN = "page token"; + + @Test + public void testDnsRecordListOption() { + // dns name + String dnsName = "some name"; + Dns.DnsRecordListOption dnsRecordListOption = Dns.DnsRecordListOption.dnsName(dnsName); + assertEquals(dnsName, dnsRecordListOption.value()); + assertEquals(DnsRpc.Option.DNS_NAME, dnsRecordListOption.rpcOption()); + // page token + dnsRecordListOption = Dns.DnsRecordListOption.pageToken(PAGE_TOKEN); + assertEquals(PAGE_TOKEN, dnsRecordListOption.value()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, dnsRecordListOption.rpcOption()); + // page size + dnsRecordListOption = Dns.DnsRecordListOption.pageSize(PAGE_SIZE); + assertEquals(PAGE_SIZE, dnsRecordListOption.value()); + assertEquals(DnsRpc.Option.PAGE_SIZE, dnsRecordListOption.rpcOption()); + // record type + DnsRecord.Type recordType = DnsRecord.Type.AAAA; + dnsRecordListOption = Dns.DnsRecordListOption.type(recordType); + assertEquals(recordType, dnsRecordListOption.value()); + assertEquals(DnsRpc.Option.DNS_TYPE, dnsRecordListOption.rpcOption()); + // fields + dnsRecordListOption = Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME, + Dns.DnsRecordField.TTL); + assertEquals(DnsRpc.Option.FIELDS, dnsRecordListOption.rpcOption()); + assertTrue(dnsRecordListOption.value() instanceof String); + assertTrue(((String) dnsRecordListOption.value()).contains( + Dns.DnsRecordField.NAME.selector())); + assertTrue(((String) dnsRecordListOption.value()).contains( + Dns.DnsRecordField.TTL.selector())); + assertTrue(((String) dnsRecordListOption.value()).contains( + Dns.DnsRecordField.NAME.selector())); + } + + @Test + public void testZoneOption() { + Dns.ZoneOption fields = Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME, + Dns.ZoneField.DESCRIPTION); + assertEquals(DnsRpc.Option.FIELDS, fields.rpcOption()); + assertTrue(fields.value() instanceof String); + assertTrue(((String) fields.value()).contains(Dns.ZoneField.CREATION_TIME.selector())); + assertTrue(((String) fields.value()).contains(Dns.ZoneField.DESCRIPTION.selector())); + } + + @Test + public void testZoneList() { + // fields + Dns.ZoneListOption fields = Dns.ZoneListOption.fields(Dns.ZoneField.CREATION_TIME, + Dns.ZoneField.DESCRIPTION); + assertEquals(DnsRpc.Option.FIELDS, fields.rpcOption()); + assertTrue(fields.value() instanceof String); + assertTrue(((String) fields.value()).contains(Dns.ZoneField.CREATION_TIME.selector())); + assertTrue(((String) fields.value()).contains(Dns.ZoneField.DESCRIPTION.selector())); + assertTrue(((String) fields.value()).contains(Dns.ZoneField.ZONE_ID.selector())); + // page token + Dns.ZoneListOption option = Dns.ZoneListOption.pageToken(PAGE_TOKEN); + assertEquals(PAGE_TOKEN, option.value()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, option.rpcOption()); + // page size + option = Dns.ZoneListOption.pageSize(PAGE_SIZE); + assertEquals(PAGE_SIZE, option.value()); + assertEquals(DnsRpc.Option.PAGE_SIZE, option.rpcOption()); + } + + @Test + public void testProjectGetOption() { + // fields + Dns.ProjectGetOption fields = Dns.ProjectGetOption.fields(Dns.ProjectField.QUOTA); + assertEquals(DnsRpc.Option.FIELDS, fields.rpcOption()); + assertTrue(fields.value() instanceof String); + assertTrue(((String) fields.value()).contains(Dns.ProjectField.QUOTA.selector())); + assertTrue(((String) fields.value()).contains(Dns.ProjectField.PROJECT_ID.selector())); + } + + @Test + public void testChangeRequestOption() { + // fields + Dns.ChangeRequestOption fields = Dns.ChangeRequestOption.fields( + Dns.ChangeRequestField.START_TIME, Dns.ChangeRequestField.STATUS); + assertEquals(DnsRpc.Option.FIELDS, fields.rpcOption()); + assertTrue(fields.value() instanceof String); + assertTrue(((String) fields.value()).contains( + Dns.ChangeRequestField.START_TIME.selector())); + assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.ID.selector())); + } + + @Test + public void testChangeRequestListOption() { + // fields + Dns.ChangeRequestListOption fields = Dns.ChangeRequestListOption.fields( + Dns.ChangeRequestField.START_TIME, Dns.ChangeRequestField.STATUS); + assertEquals(DnsRpc.Option.FIELDS, fields.rpcOption()); + assertTrue(fields.value() instanceof String); + assertTrue(((String) fields.value()).contains( + Dns.ChangeRequestField.START_TIME.selector())); + assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.ID.selector())); + // page token + Dns.ChangeRequestListOption option = Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN); + assertEquals(PAGE_TOKEN, option.value()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, option.rpcOption()); + // page size + option = Dns.ChangeRequestListOption.pageSize(PAGE_SIZE); + assertEquals(PAGE_SIZE, option.value()); + assertEquals(DnsRpc.Option.PAGE_SIZE, option.rpcOption()); + // sort order + option = Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING); + assertEquals(DnsRpc.Option.SORTING_ORDER, option.rpcOption()); + assertEquals(Dns.SortingOrder.ASCENDING.selector(), option.value()); + } +} From 6ecde35c355ca8e38e726044e9a0012f5a3935ab Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 1 Feb 2016 16:07:24 -0800 Subject: [PATCH 33/74] Comments by @aozarov second round. --- .../main/java/com/google/gcloud/dns/Dns.java | 15 ++++++----- .../google/gcloud/dns/AbstractOptionTest.java | 26 +++++++------------ 2 files changed, 18 insertions(+), 23 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 352c7791e18d..28e79104cf58 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -24,6 +24,8 @@ import java.io.Serializable; import java.util.Set; +import static com.google.gcloud.dns.Dns.ZoneField.selector; + /** * An interface for the Google Cloud DNS service. * @@ -31,8 +33,6 @@ */ public interface Dns extends Service { - - /** * The fields of a project. * @@ -284,7 +284,9 @@ class ZoneListOption extends AbstractOption implements Serializable { * specified. {@link ZoneField} provides a list of fields that can be used. */ public static ZoneListOption fields(ZoneField... fields) { - return new ZoneListOption(DnsRpc.Option.FIELDS, ZoneField.selector(fields)); + StringBuilder builder = new StringBuilder(); + builder.append("managedZones(").append(selector(fields)).append(')'); + return new ZoneListOption(DnsRpc.Option.FIELDS, builder.toString()); } /** @@ -381,10 +383,9 @@ class ChangeRequestListOption extends AbstractOption implements Serializable { * a list of fields that can be used. */ public static ChangeRequestListOption fields(ChangeRequestField... fields) { - return new ChangeRequestListOption( - DnsRpc.Option.FIELDS, - ChangeRequestField.selector(fields) - ); + StringBuilder builder = new StringBuilder(); + builder.append("changes(").append(ChangeRequestField.selector(fields)).append(')'); + return new ChangeRequestListOption(DnsRpc.Option.FIELDS, builder.toString()); } /** diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java index 3c578c53d0d1..e3f2896bd10b 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java @@ -16,30 +16,26 @@ package com.google.gcloud.dns; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; - import com.google.gcloud.spi.DnsRpc; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.fail; + public class AbstractOptionTest { private static final DnsRpc.Option RPC_OPTION = DnsRpc.Option.DNS_TYPE; private static final DnsRpc.Option ANOTHER_RPC_OPTION = DnsRpc.Option.DNS_NAME; private static final String VALUE = "some value"; private static final String OTHER_VALUE = "another value"; - private static final AbstractOption OPTION = new AbstractOption(RPC_OPTION, VALUE) { - }; - private static final AbstractOption OPTION_EQUALS = new AbstractOption(RPC_OPTION, VALUE) { - }; + private static final AbstractOption OPTION = new AbstractOption(RPC_OPTION, VALUE) {}; + private static final AbstractOption OPTION_EQUALS = new AbstractOption(RPC_OPTION, VALUE) {}; private static final AbstractOption OPTION_NOT_EQUALS1 = - new AbstractOption(RPC_OPTION, OTHER_VALUE) { - }; + new AbstractOption(RPC_OPTION, OTHER_VALUE) {}; private static final AbstractOption OPTION_NOT_EQUALS2 = - new AbstractOption(ANOTHER_RPC_OPTION, VALUE) { - }; + new AbstractOption(ANOTHER_RPC_OPTION, VALUE) {}; @Test public void testEquals() { @@ -58,13 +54,11 @@ public void testConstructor() { assertEquals(RPC_OPTION, OPTION.rpcOption()); assertEquals(VALUE, OPTION.value()); try { - new AbstractOption(null, VALUE) { - }; + new AbstractOption(null, VALUE) {}; fail("Cannot build with empty option."); } catch (NullPointerException e) { // expected } - new AbstractOption(RPC_OPTION, null) { - }; // null value is ok + new AbstractOption(RPC_OPTION, null) {}; // null value is ok } } From a69101a80df1637361b02a93233d0ad3e5d69098 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 1 Feb 2016 16:18:16 -0800 Subject: [PATCH 34/74] Added Dns methods. Fixes #596. Added Zone and ZoneTest --- .../main/java/com/google/gcloud/dns/Dns.java | 194 ++++- .../main/java/com/google/gcloud/dns/Zone.java | 256 ++++++ .../google/gcloud/dns/AbstractOptionTest.java | 8 +- .../java/com/google/gcloud/dns/ZoneTest.java | 750 ++++++++++++++++++ 4 files changed, 1200 insertions(+), 8 deletions(-) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 28e79104cf58..b48e4b0a90f2 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -18,14 +18,14 @@ import com.google.common.base.Joiner; import com.google.common.collect.Sets; +import com.google.gcloud.Page; import com.google.gcloud.Service; import com.google.gcloud.spi.DnsRpc; import java.io.Serializable; +import java.math.BigInteger; import java.util.Set; -import static com.google.gcloud.dns.Dns.ZoneField.selector; - /** * An interface for the Google Cloud DNS service. * @@ -285,7 +285,7 @@ class ZoneListOption extends AbstractOption implements Serializable { */ public static ZoneListOption fields(ZoneField... fields) { StringBuilder builder = new StringBuilder(); - builder.append("managedZones(").append(selector(fields)).append(')'); + builder.append("managedZones(").append(ZoneField.selector(fields)).append(')'); return new ZoneListOption(DnsRpc.Option.FIELDS, builder.toString()); } @@ -420,5 +420,191 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { } } - // TODO(mderka) Add methods. Created issue #596. + /** + * Creates a new zone. + * + * @return ZoneInfo object representing the new zone's metadata. In addition to the name, dns name + * and description (supplied by the user within the {@code zoneInfo} parameter, the returned + * object will include the following read-only fields supplied by the server: creation time, id, + * and list of name servers. + * @throws DnsException upon failure + * @see Cloud DNS Managed Zones: + * create + */ + ZoneInfo create(ZoneInfo zoneInfo); + + /** + * Retrieves the zone by the specified zone name. Returns {@code null} is the zone is not found. + * The returned fields can be optionally restricted by specifying {@code ZoneFieldOptions}. + * + * @throws DnsException upon failure + * @see Cloud DNS Managed Zones: + * get + */ + ZoneInfo getZone(String zoneName, ZoneOption... options); + + /** + * Retrieves the zone by the specified zone name. Returns {@code null} is the zone is not found. + * The returned fields can be optionally restricted by specifying {@code ZoneFieldOptions}. + * + * @throws DnsException upon failure + * @see Cloud DNS Managed Zones: + * get + */ + ZoneInfo getZone(BigInteger zoneId, ZoneOption... options); + + /** + * Lists the zoned inside the project. + * + *

This method returns zone in an unspecified order. New zones do not necessarily appear at the + * end of the list. Use {@link ZoneListOption} to restrict the listing to a domain name, set page + * size, and set page tokens. + * + * @return {@code Page}, a page of zones + * @throws DnsException upon failure + * @see Cloud DNS Managed Zones: + * list + */ + Page listZones(ZoneListOption... options); + + /** + * Deletes an existing zone identified by name. Returns true if the zone was successfully deleted + * and false otherwise. + * + * @return {@code true} if zone was found and deleted and false otherwise + * @throws DnsException upon failure + * @see Cloud DNS Managed Zones: + * delete + */ + boolean delete(String zoneName); // delete does not admit any options + + /** + * Deletes an existing zone identified by id. Returns true if the zone was successfully deleted + * and false otherwise. + * + * @return {@code true} if zone was found and deleted and false otherwise + * @throws DnsException upon failure + * @see Cloud DNS Managed Zones: + * delete + */ + boolean delete(BigInteger zoneId); // delete does not admit any options + + /** + * Lists the DNS records in the zone identified by name. + * + *

The fields to be returned, page size and page tokens can be specified using {@code + * DnsRecordOptions}. Returns null if the zone cannot be found. + * + * @throws DnsException upon failure + * @see Cloud DNS + * ResourceRecordSets: list + */ + Page listDnsRecords(String zoneName, DnsRecordListOption... options); + + /** + * Lists the DNS records in the zone identified by ID. + * + *

The fields to be returned, page size and page tokens can be specified using {@code + * DnsRecordOptions}. Returns null if the zone cannot be found. + * + * @throws DnsException upon failure + * @see Cloud DNS + * ResourceRecordSets: list + */ + Page listDnsRecords(BigInteger zoneId, DnsRecordListOption... options); + + /** + * Retrieves the metadata about the current project. The returned fields can be optionally + * restricted by specifying {@code ProjectOptions}. + * + * @throws DnsException upon failure + * @see Cloud DNS Projects: get + */ + ProjectInfo getProjectInfo(ProjectGetOption... fields); + + /** + * Returns the current project id. + */ + String getProjectId(); + + /** + * Returns the current project number. + */ + BigInteger getProjectNumber(); + + /** + * Submits a change requests for applying to the zone identified by ID to the service. The + * returned object contains the following read-only fields supplied by the server: id, start time + * and status. time, id, and list of name servers. The returned fields can be modified by {@code + * ChangeRequestFieldOptions}. Returns null if the zone is not found. + * + * @return ChangeRequest object representing the new change request or null if zone is not found + * @throws DnsException upon failure + * @see Cloud DNS Changes: create + */ + ChangeRequest applyChangeRequest(ChangeRequest changeRequest, BigInteger zoneId, + ChangeRequestOption... options); + + /** + * Submits a change requests for applying to the zone identified by name to the service. The + * returned object contains the following read-only fields supplied by the server: id, start time + * and status. time, id, and list of name servers. The returned fields can be modified by {@code + * ChangeRequestFieldOptions}. Returns null if the zone is not found. + * + * @return ChangeRequest object representing the new change request or null if zone is not found + * @throws DnsException upon failure + * @see Cloud DNS Changes: create + */ + ChangeRequest applyChangeRequest(ChangeRequest changeRequest, String zoneName, + ChangeRequestOption... options); + + /** + * Retrieves updated information about a change request previously submitted for a zone identified + * by ID. Returns null if the zone or request cannot be found. + * + *

The fields to be returned using {@code ChangeRequestFieldOptions}. + * + * @throws DnsException upon failure + * @see Cloud DNS Chages: get + */ + ChangeRequest getChangeRequest(ChangeRequest changeRequest, BigInteger zoneId, + ChangeRequestOption... options); + + /** + * Retrieves updated information about a change request previously submitted for a zone identified + * by name. Returns null if the zone or request cannot be found. + * + *

The fields to be returned using {@code ChangeRequestFieldOptions}. + * + * @throws DnsException upon failure + * @see Cloud DNS Chages: get + */ + ChangeRequest getChangeRequest(ChangeRequest changeRequest, String zoneName, + ChangeRequestOption... options); + + /** + * Lists the change requests for the zone identified by ID that were submitted to the service. + * + *

The sorting key for changes, fields to be returned, page and page tokens can be specified + * using {@code ChangeRequestListOptions}. Note that the only sorting key currently supported is + * the timestamp of submitting the change request to the service. + * + * @return {@code Page}, a page of change requests + * @throws DnsException upon failure + * @see Cloud DNS Chages: list + */ + Page listChangeRequests(BigInteger zoneId, ChangeRequestListOption... options); + + /** + * Lists the change requests for the zone identified by name that were submitted to the service. + * + *

The sorting key for changes, fields to be returned, page and page tokens can be specified + * using {@code ChangeRequestListOptions}. Note that the only sorting key currently supported is + * the timestamp of submitting the change request to the service. + * + * @return {@code Page}, a page of change requests + * @throws DnsException upon failure + * @see Cloud DNS Chages: list + */ + Page listChangeRequests(String zoneName, ChangeRequestListOption... options); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java new file mode 100644 index 000000000000..f4d9702ba12f --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -0,0 +1,256 @@ +/* + * 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.dns; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.gcloud.Page; + +import java.io.Serializable; +import java.math.BigInteger; + +/** + * A Google Cloud DNS Zone object. + * + *

A zone is the container for all of your DNS records that share the same DNS name prefix, for + * example, example.com. Zones are automatically assigned a set of name servers when they are + * created to handle responding to DNS queries for that zone. A zone has quotas for the number of + * resource records that it can include. + * + * @see Google Cloud DNS managed zone + * documentation + */ +public class Zone implements Serializable { + + // TODO(mderka) Zone and zoneInfo to be merged. Opened issue #605. + + private static final long serialVersionUID = -4012581571095484813L; + private final ZoneInfo zoneInfo; + private final Dns dns; + + /** + * Constructs a {@code Zone} object that contains the given {@code zoneInfo}. + */ + public Zone(Dns dns, ZoneInfo zoneInfo) { + this.zoneInfo = checkNotNull(zoneInfo); + this.dns = checkNotNull(dns); + } + + /** + * Constructs a {@code Zone} object that contains meta information received from the Google Cloud + * DNS service for the provided zoneName. + * + * @param zoneName Name of the zone to be searched for + * @param options Optional restriction on what fields should be returned by the service + * @return Zone object containing metadata or null if not not found + * @throws DnsException upon failure + */ + public static Zone get(Dns dnsService, String zoneName, + Dns.ZoneOption... options) { + checkNotNull(zoneName); + checkNotNull(dnsService); + ZoneInfo zoneInfo = dnsService.getZone(zoneName, options); + return zoneInfo == null ? null : new Zone(dnsService, zoneInfo); + } + + /** + * Constructs a {@code Zone} object that contains meta information received from the Google Cloud + * DNS service for the provided zoneName. + * + * @param zoneId ID of the zone to be searched for + * @param options Optional restriction on what fields should be returned by the service + * @return Zone object containing metadata or null if not not found + * @throws DnsException upon failure + */ + public static Zone get(Dns dnsService, BigInteger zoneId, + Dns.ZoneOption... options) { + checkNotNull(zoneId); + checkNotNull(dnsService); + ZoneInfo zoneInfo = dnsService.getZone(zoneId, options); + return zoneInfo == null ? null : new Zone(dnsService, zoneInfo); + } + + /** + * Retrieves the latest information about the zone. The method first attempts to retrieve the zone + * by ID and if not set or zone is not found, it searches by name. + * + * @param options Optional restriction on what fields should be fetched + * @return Zone object containing updated metadata or null if not not found + * @throws DnsException upon failure + * @throws NullPointerException if both zone ID and name are not initialized + */ + public Zone reload(Dns.ZoneOption... options) { + checkNameOrIdNotNull(); + Zone zone = null; + if (zoneInfo.id() != null) { + zone = Zone.get(dns, zoneInfo.id(), options); + } + if (zone == null && zoneInfo.name() != null) { + // zone was not found by id or id is not set at all + zone = Zone.get(dns, zoneInfo.name(), options); + } + return zone; + } + + /** + * Deletes the zone. The method first attempts to delete the zone by ID. If the zone is not found + * or id is not set, it attempts to delete by name. + * + * @return true is zone was found and deleted and false otherwise + * @throws DnsException upon failure + * @throws NullPointerException if both zone ID and name are not initialized + */ + public boolean delete() { + checkNameOrIdNotNull(); + boolean deleted = false; + if (zoneInfo.id() != null) { + deleted = dns.delete(zoneInfo.id()); + } + if (!deleted && zoneInfo.name() != null) { + // zone was not found by id or id is not set at all + deleted = dns.delete(zoneInfo.name()); + } + return deleted; + } + + /** + * Lists all {@link DnsRecord}s associated with this zone. First searches for zone by ID and if + * not found then by name. + * + * @param options Optional restriction on listing and on what fields of {@link DnsRecord} should + * be returned by the service + * @return {@code Page}, a page of DNS records, or null if the zone is not found + * @throws DnsException upon failure + * @throws NullPointerException if both zone ID and name are not initialized + */ + public Page listDnsRecords(Dns.DnsRecordListOption... options) { + checkNameOrIdNotNull(); + Page page = null; + if (zoneInfo.id() != null) { + page = dns.listDnsRecords(zoneInfo.id(), options); + } + if (page == null && zoneInfo.name() != null) { + // zone was not found by id or id is not set at all + page = dns.listDnsRecords(zoneInfo.name(), options); + } + return page; + } + + /** + * Submits {@link ChangeRequest} to the service for it to applied to this zone. First searches for + * the zone by ID and if not found then by name. Returns a {@link ChangeRequest} with + * server-assigned ID or null if the zone was not found. + * + * @param options Optional restriction on what fields of {@link ChangeRequest} should be returned + * by the service + * @return ChangeRequest with server-assigned ID or null if the zone was not found. + * @throws DnsException upon failure + * @throws NullPointerException if both zone ID and name are not initialized + */ + public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, + Dns.ChangeRequestOption... options) { + checkNameOrIdNotNull(); + checkNotNull(changeRequest); + ChangeRequest updated = null; + if (zoneInfo.id() != null) { + updated = dns.applyChangeRequest(changeRequest, zoneInfo.id(), options); + } + if (updated == null && zoneInfo.name() != null) { + // zone was not found by id or id is not set at all + updated = dns.applyChangeRequest(changeRequest, zoneInfo.name(), options); + } + return updated; + } + + /** + * Retrieves an updated information about a change request previously submitted to be applied to + * this zone. First searches for the zone by ID and if not found then by name. Returns a {@link + * ChangeRequest} if found and null is the zone or the change request was not found. + * + * @param options Optional restriction on what fields of {@link ChangeRequest} should be returned + * by the service + * @return ChangeRequest with updated information of null if the change request or zone was not + * found. + * @throws DnsException upon failure + * @throws NullPointerException if both zone ID and name are not initialized + * @throws NullPointerException if the change request does not have initialized id + */ + public ChangeRequest getChangeRequest(ChangeRequest changeRequest, + Dns.ChangeRequestOption... options) { + checkNameOrIdNotNull(); + checkNotNull(changeRequest); + checkNotNull(changeRequest.id()); + ChangeRequest updated = null; + if (zoneInfo.id() != null) { + updated = dns.getChangeRequest(changeRequest, zoneInfo.id(), options); + } + if (updated == null && zoneInfo.name() != null) { + // zone was not found by id or id is not set at all + updated = dns.getChangeRequest(changeRequest, zoneInfo.name(), options); + } + return updated; + } + + /** + * Retrieves all change requests for this zone. First searches for the zone by ID and if not found + * then by name. Returns a page of {@link ChangeRequest}s or null if the zone is not found. + * + * @param options Optional restriction on listing and on what fields of {@link ChangeRequest}s + * should be returned by the service + * @return {@code Page}, a page of change requests, or null if the zone is not + * found + * @throws DnsException upon failure + * @throws NullPointerException if both zone ID and name are not initialized + */ + public Page listChangeRequests(Dns.ChangeRequestListOption... options) { + checkNameOrIdNotNull(); + Page changeRequests = null; + if (zoneInfo.id() != null) { + changeRequests = dns.listChangeRequests(zoneInfo.id(), options); + } + if (changeRequests == null && zoneInfo.name() != null) { + // zone was not found by id or id is not set at all + changeRequests = dns.listChangeRequests(zoneInfo.name(), options); + } + return changeRequests; + } + + /** + * Check that at least one of name and ID are initialized and throw and exception if not. + */ + private void checkNameOrIdNotNull() { + if (zoneInfo != null && zoneInfo.id() == null && zoneInfo.name() == null) { + throw new NullPointerException("Both zoneInfo.id and zoneInfo.name are null. " + + "This is an inconsistent state which should never happen."); + } + } + + /** + * Returns the {@link ZoneInfo} object containing meta information about this managed zone. + */ + public ZoneInfo info() { + return this.zoneInfo; + } + + /** + * Returns the {@link Dns} service object associated with this managed zone. + */ + public Dns dns() { + return this.dns; + } + +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java index e3f2896bd10b..09e35527879b 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java @@ -16,14 +16,14 @@ package com.google.gcloud.dns; -import com.google.gcloud.spi.DnsRpc; - -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; +import com.google.gcloud.spi.DnsRpc; + +import org.junit.Test; + public class AbstractOptionTest { private static final DnsRpc.Option RPC_OPTION = DnsRpc.Option.DNS_TYPE; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java new file mode 100644 index 000000000000..5f9d119e6150 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -0,0 +1,750 @@ +/* + * 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.dns; + +import static org.easymock.EasyMock.createStrictMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gcloud.Page; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.math.BigInteger; + +public class ZoneTest { + + private static final String ZONE_NAME = "dns-zone-name"; + private static final BigInteger ZONE_ID = new BigInteger("123"); + private static final ZoneInfo ZONE_INFO = ZoneInfo.builder(ZONE_NAME, ZONE_ID) + .dnsName("example.com") + .creationTimeMillis(123478946464L) + .build(); + private static final ZoneInfo NO_ID_INFO = ZoneInfo.builder(ZONE_NAME) + .dnsName("anoter-example.com") + .creationTimeMillis(893123464L) + .build(); + private static final ZoneInfo NO_NAME_INFO = ZoneInfo.builder(ZONE_ID) + .dnsName("one-more-example.com") + .creationTimeMillis(875221546464L) + .build(); + private static final Dns.ZoneOption ZONE_FIELD_OPTIONS = + Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); + private static final Dns.DnsRecordListOption DNS_RECORD_OPTIONS = + Dns.DnsRecordListOption.dnsName("some-dns"); + private static final Dns.ChangeRequestOption CHANGE_REQUEST_FIELD_OPTIONS = + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME); + private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTIONS = + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME); + private static final ChangeRequest CHANGE_REQUEST = ChangeRequest.builder().id("someid").build(); + private static final ChangeRequest CHANGE_REQUEST_AFTER = CHANGE_REQUEST.toBuilder() + .startTimeMillis(123465L).build(); + private static final ChangeRequest CHANGE_REQUEST_NO_ID = ChangeRequest.builder().build(); + + private Dns dns; + private Zone zone; + private Zone zoneNoName; + private Zone zoneNoId; + + @Before + public void setUp() throws Exception { + dns = createStrictMock(Dns.class); + zone = new Zone(dns, ZONE_INFO); + zoneNoId = new Zone(dns, NO_ID_INFO); + zoneNoName = new Zone(dns, NO_NAME_INFO); + } + + @After + public void tearDown() throws Exception { + verify(dns); + } + + @Test + public void testConstructor() { + replay(dns); + assertNotNull(zone.info()); + assertEquals(ZONE_INFO, zone.info()); + assertNotNull(zone.dns()); + assertEquals(dns, zone.dns()); + } + + @Test + public void testGetById() { + expect(dns.getZone(ZONE_ID)).andReturn(ZONE_INFO); + expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(ZONE_INFO); // for options + replay(dns); + Zone retrieved = Zone.get(dns, ZONE_ID); + assertSame(dns, retrieved.dns()); + assertEquals(ZONE_INFO, retrieved.info()); + BigInteger id = null; + try { + Zone.get(dns, id); + fail("Cannot get null zone."); + } catch (NullPointerException e) { + // expected + } + try { + Zone.get(null, id); + fail("Cannot get null zone."); + } catch (NullPointerException e) { + // expected + } + // test passing options + Zone.get(dns, ZONE_ID, ZONE_FIELD_OPTIONS); + } + + @Test + public void testGetByName() { + expect(dns.getZone(ZONE_NAME)).andReturn(ZONE_INFO); + expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(ZONE_INFO); // for options + replay(dns); + Zone retrieved = Zone.get(dns, ZONE_NAME); + assertSame(dns, retrieved.dns()); + assertEquals(ZONE_INFO, retrieved.info()); + String name = null; + try { + Zone.get(dns, name); + fail("Cannot get null zone."); + } catch (NullPointerException e) { + // expected + } + try { + Zone.get(null, name); + fail("Cannot get null zone."); + } catch (NullPointerException e) { + // expected + } + // test passing options + Zone.get(dns, ZONE_ID, ZONE_FIELD_OPTIONS); + } + + @Test + public void deleteByIdAndFound() { + expect(dns.delete(ZONE_ID)).andReturn(true); + replay(dns); + boolean result = zone.delete(); + assertTrue(result); + } + + @Test + public void deleteByIdAndNotFoundAndNameSetAndFound() { + expect(dns.delete(ZONE_ID)).andReturn(false); + expect(dns.delete(ZONE_NAME)).andReturn(true); + replay(dns); + boolean result = zone.delete(); + assertTrue(result); + } + + @Test + public void deleteByIdAndNotFoundAndNameSetAndNotFound() { + expect(dns.delete(ZONE_ID)).andReturn(false); + expect(dns.delete(ZONE_NAME)).andReturn(false); + replay(dns); + boolean result = zone.delete(); + assertFalse(result); + } + + @Test + public void deleteByIdAndNotFoundAndNameNotSet() { + expect(dns.delete(ZONE_ID)).andReturn(false); + replay(dns); + boolean result = zoneNoName.delete(); + assertFalse(result); + } + + @Test + public void deleteByNameAndFound() { + expect(dns.delete(ZONE_NAME)).andReturn(true); + replay(dns); + boolean result = zoneNoId.delete(); + assertTrue(result); + } + + @Test + public void deleteByNameAndNotFound() { + expect(dns.delete(ZONE_NAME)).andReturn(true); + replay(dns); + boolean result = zoneNoId.delete(); + assertTrue(result); + } + + @Test + public void listDnsRecordsByIdAndFound() { + Page pageMock = createStrictMock(Page.class); + replay(pageMock); + expect(dns.listDnsRecords(ZONE_ID)).andReturn(pageMock); + // again for options + expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(pageMock); + replay(dns); + Page result = zone.listDnsRecords(); + assertSame(pageMock, result); + verify(pageMock); + // verify options + zone.listDnsRecords(DNS_RECORD_OPTIONS); + } + + @Test + public void listDnsRecordsByIdAndNotFoundAndNameSetAndFound() { + Page pageMock = createStrictMock(Page.class); + replay(pageMock); + expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); + expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); + // again for options + expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(null); + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); + replay(dns); + Page result = zone.listDnsRecords(); + assertSame(pageMock, result); + verify(pageMock); + // verify options + zone.listDnsRecords(DNS_RECORD_OPTIONS); + } + + @Test + public void listDnsRecordsByIdAndNotFoundAndNameSetAndNotFound() { + expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); + expect(dns.listDnsRecords(ZONE_NAME)).andReturn(null); + // again for options + expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(null); + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(null); + replay(dns); + Page result = zone.listDnsRecords(); + assertNull(result); + // check options + zone.listDnsRecords(DNS_RECORD_OPTIONS); + } + + @Test + public void listDnsRecordsByIdAndNotFoundAndNameNotSet() { + expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); + expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(null); // for options + replay(dns); + Page result = zoneNoName.listDnsRecords(); + assertNull(result); + zoneNoName.listDnsRecords(DNS_RECORD_OPTIONS); // check options + } + + @Test + public void listDnsRecordsByNameAndFound() { + Page pageMock = createStrictMock(Page.class); + replay(pageMock); + expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); + // again for options + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); + replay(dns); + Page result = zoneNoId.listDnsRecords(); + assertSame(pageMock, result); + verify(pageMock); + zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + } + + @Test + public void listDnsRecordsByNameAndNotFound() { + expect(dns.listDnsRecords(ZONE_NAME)).andReturn(null); + // again for options + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(null); + replay(dns); + Page result = zoneNoId.listDnsRecords(); + assertNull(result); + zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + } + + @Test + public void reloadByIdAndFound() { + expect(dns.getZone(ZONE_ID)).andReturn(zone.info()); + expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(zone.info()); // for options + replay(dns); + Zone result = zone.reload(); + assertSame(zone.dns(), result.dns()); + assertEquals(zone.info(), result.info()); + zone.reload(ZONE_FIELD_OPTIONS); // for options + } + + @Test + public void reloadByIdAndNotFoundAndNameSetAndFound() { + expect(dns.getZone(ZONE_ID)).andReturn(null); + expect(dns.getZone(ZONE_NAME)).andReturn(zone.info()); + // again for options + expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(null); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone.info()); + replay(dns); + Zone result = zone.reload(); + assertSame(zone.dns(), result.dns()); + assertEquals(zone.info(), result.info()); + zone.reload(ZONE_FIELD_OPTIONS); // for options + } + + @Test + public void reloadByIdAndNotFoundAndNameSetAndNotFound() { + expect(dns.getZone(ZONE_ID)).andReturn(null); + expect(dns.getZone(ZONE_NAME)).andReturn(null); + // again with options + expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(null); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); + replay(dns); + Zone result = zone.reload(); + assertNull(result); + // again for options + zone.reload(ZONE_FIELD_OPTIONS); + } + + @Test + public void reloadByIdAndNotFoundAndNameNotSet() { + expect(dns.getZone(ZONE_ID)).andReturn(null); + expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(null); // for options + replay(dns); + Zone result = zoneNoName.reload(); + assertNull(result); + zoneNoName.reload(ZONE_FIELD_OPTIONS); // for options + } + + @Test + public void reloadByNameAndFound() { + expect(dns.getZone(ZONE_NAME)).andReturn(zoneNoId.info()); + // again for options + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zoneNoId.info()); + replay(dns); + Zone result = zoneNoId.reload(); + assertSame(zoneNoId.dns(), result.dns()); + assertEquals(zoneNoId.info(), result.info()); + zoneNoId.reload(ZONE_FIELD_OPTIONS); // check options + } + + @Test + public void reloadByNameAndNotFound() { + expect(dns.getZone(ZONE_NAME)).andReturn(null); + // again for options + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); + replay(dns); + Zone result = zoneNoId.reload(); + assertNull(result); + zoneNoId.reload(ZONE_FIELD_OPTIONS); // for options + } + + @Test + public void applyChangeByIdAndFound() { + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(CHANGE_REQUEST_AFTER); + // again for options + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); + replay(dns); + ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + // for options + result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + } + + @Test + public void applyChangeByIdAndNotFoundAndNameSetAndFound() { + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + .andReturn(CHANGE_REQUEST_AFTER); + // again for options + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); + replay(dns); + ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + // for options + result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + } + + @Test + public void applyChangeIdAndNotFoundAndNameSetAndNotFound() { + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + // again with options + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + replay(dns); + ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); + assertNull(result); + // again for options + result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNull(result); + } + + @Test + public void applyChangeRequestByIdAndNotFoundAndNameNotSet() { + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); // for options + replay(dns); + ChangeRequest result = zoneNoName.applyChangeRequest(CHANGE_REQUEST); + assertNull(result); + // again for options + result = zoneNoName.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNull(result); + } + + @Test + public void applyChangeByNameAndFound() { + // ID is not set + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + .andReturn(CHANGE_REQUEST_AFTER); + // again for options + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); + replay(dns); + ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); + assertEquals(CHANGE_REQUEST_AFTER, result); + // check options + result = zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertEquals(CHANGE_REQUEST_AFTER, result); + } + + @Test + public void applyChangeByNameAndNotFound() { + // ID is not set + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + // again for options + expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + replay(dns); + ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); + assertNull(result); + // check options + result = zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNull(result); + } + + @Test + public void applyNullChangeRequest() { + replay(dns); // no calls expected + try { + zone.applyChangeRequest(null); + fail("Cannot apply null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zone.applyChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot apply null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoId.applyChangeRequest(null); + fail("Cannot apply null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoId.applyChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot apply null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoName.applyChangeRequest(null); + fail("Cannot apply null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoName.applyChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot apply null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + } + + @Test + public void getChangeByIdAndFound() { + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(CHANGE_REQUEST_AFTER); + // again for options + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); + replay(dns); + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + // for options + result = zone.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + // test no id + } + + @Test + public void getChangeByIdAndNotFoundAndNameSetAndFound() { + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + .andReturn(CHANGE_REQUEST_AFTER); + // again for options + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); + replay(dns); + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + // for options + result = zone.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNotEquals(CHANGE_REQUEST, result); + assertEquals(CHANGE_REQUEST_AFTER, result); + } + + @Test + public void getChangeIdAndNotFoundAndNameSetAndNotFound() { + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + // again with options + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + replay(dns); + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST); + assertNull(result); + // again for options + result = zone.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNull(result); + } + + @Test + public void getChangeRequestByIdAndNotFoundAndNameNotSet() { + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); // for options + replay(dns); + ChangeRequest result = zoneNoName.getChangeRequest(CHANGE_REQUEST); + assertNull(result); + // again for options + result = zoneNoName.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNull(result); + } + + @Test + public void getChangeByNameAndFound() { + // ID is not set + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + .andReturn(CHANGE_REQUEST_AFTER); + // again for options + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); + replay(dns); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST); + assertEquals(CHANGE_REQUEST_AFTER, result); + // check options + result = zoneNoId.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertEquals(CHANGE_REQUEST_AFTER, result); + } + + @Test + public void getChangeByNameAndNotFound() { + // ID is not set + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + // again for options + expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); + replay(dns); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST); + assertNull(result); + // check options + result = zoneNoId.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertNull(result); + } + + @Test + public void getNullChangeRequest() { + replay(dns); // no calls expected + try { + zone.getChangeRequest(null); + fail("Cannot get null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zone.getChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoId.getChangeRequest(null); + fail("Cannot get null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoId.getChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoName.getChangeRequest(null); + fail("Cannot get null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoName.getChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get null ChangeRequest."); + } catch (NullPointerException e) { + // expected + } + } + + @Test + public void getChangeRequestWithNoId() { + replay(dns); // no calls expected + try { + zone.getChangeRequest(CHANGE_REQUEST_NO_ID); + fail("Cannot get ChangeRequest with no id."); + } catch (NullPointerException e) { + // expected + } + try { + zone.getChangeRequest(CHANGE_REQUEST_NO_ID, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get ChangeRequest with no id."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID); + fail("Cannot get ChangeRequest with no id."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get ChangeRequest with no id."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID); + fail("Cannot get ChangeRequest with no id."); + } catch (NullPointerException e) { + // expected + } + try { + zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get ChangeRequest with no id."); + } catch (NullPointerException e) { + // expected + } + } + + @Test + public void listChangeRequestsByIdAndFound() { + Page pageMock = createStrictMock(Page.class); + replay(pageMock); + expect(dns.listChangeRequests(ZONE_ID)).andReturn(pageMock); + // again for options + expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(pageMock); + replay(dns); + Page result = zone.listChangeRequests(); + assertSame(pageMock, result); + verify(pageMock); + // verify options + zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); + } + + @Test + public void listChangeRequestsByIdAndNotFoundAndNameSetAndFound() { + Page pageMock = createStrictMock(Page.class); + replay(pageMock); + expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); + // again for options + expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) + .andReturn(pageMock); + replay(dns); + Page result = zone.listChangeRequests(); + assertSame(pageMock, result); + verify(pageMock); + // verify options + zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); + } + + @Test + public void listChangeRequestsByIdAndNotFoundAndNameSetAndNotFound() { + expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(null); + // again for options + expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); + replay(dns); + Page result = zone.listChangeRequests(); + assertNull(result); + // check options + zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); + } + + @Test + public void listChangeRequestsByIdAndNotFoundAndNameNotSet() { + expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); + // again for options + expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); + replay(dns); + Page result = zoneNoName.listChangeRequests(); + assertNull(result); + zoneNoName.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + } + + @Test + public void listChangeRequestsByNameAndFound() { + Page pageMock = createStrictMock(Page.class); + replay(pageMock); + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); + // again for options + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) + .andReturn(pageMock); + replay(dns); + Page result = zoneNoId.listChangeRequests(); + assertSame(pageMock, result); + verify(pageMock); + zoneNoId.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + } + + @Test + public void listChangeRequestsByNameAndNotFound() { + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(null); + // again for options + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); + replay(dns); + Page result = zoneNoId.listChangeRequests(); + assertNull(result); + zoneNoId.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + } +} From e083dfd87052a3231067cf0b0535e899d279d5c3 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 2 Feb 2016 12:39:08 -0800 Subject: [PATCH 35/74] Fixed documentation and some code formatting. Declared exceptions to be thrown when parent objects do not exist. Changed contracts of applyChangeRequest and getChangeRequest methods. Adjusted tests. --- .../main/java/com/google/gcloud/dns/Dns.java | 147 +++++++++--------- .../main/java/com/google/gcloud/dns/Zone.java | 92 +++++------ .../java/com/google/gcloud/dns/DnsTest.java | 2 +- .../java/com/google/gcloud/dns/ZoneTest.java | 112 ++++++------- 4 files changed, 171 insertions(+), 182 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index b48e4b0a90f2..130e8bb99f5e 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -37,7 +37,7 @@ public interface Dns extends Service { * The fields of a project. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#getProjectInfo(ProjectGetOption...)}. Project ID is always returned, even if not + * {@link Dns#getProjectInfo(ProjectOption...)}. Project ID is always returned, even if not * specified. */ enum ProjectField { @@ -69,7 +69,7 @@ static String selector(ProjectField... fields) { * The fields of a zone. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#getZone(BigInteger, ZoneOption...)} or {@code Dns#getZone(String, ZoneOption...)}. + * {@link Dns#getZone(BigInteger, ZoneOption...)} or {@link Dns#getZone(String, ZoneOption...)}. * The ID is always returned, even if not specified. */ enum ZoneField { @@ -105,7 +105,7 @@ static String selector(ZoneField... fields) { * The fields of a DNS record. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#listDnsRecords(BigInteger, DnsRecordListOption...)} or {@code + * {@link Dns#listDnsRecords(BigInteger, DnsRecordListOption...)} or {@link * Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if not * selected. */ @@ -139,8 +139,8 @@ static String selector(DnsRecordField... fields) { * The fields of a change request. * *

These values can be used to specify the fields to include in a partial response when calling - * {@code Dns#applyChangeRequest(ChangeRequest, BigInteger, ChangeRequestOption...)} or {@code - * Dns#applyChangeRequest(ChangeRequest, String, ChangeRequestOption...)} The ID is always + * {@link Dns#applyChangeRequest(BigInteger, ChangeRequest, ChangeRequestOption...)} or {@link + * Dns#applyChangeRequest(String, ChangeRequest, ChangeRequestOption...)} The ID is always * returned even if not selected. */ enum ChangeRequestField { @@ -313,11 +313,11 @@ public static ZoneListOption pageSize(int pageSize) { /** * Class for specifying project options. */ - class ProjectGetOption extends AbstractOption implements Serializable { + class ProjectOption extends AbstractOption implements Serializable { private static final long serialVersionUID = 6817937338218847748L; - ProjectGetOption(DnsRpc.Option option, Object value) { + ProjectOption(DnsRpc.Option option, Object value) { super(option, value); } @@ -325,12 +325,12 @@ class ProjectGetOption extends AbstractOption implements Serializable { * Returns an option to specify the project's fields to be returned by the RPC call. * *

If this option is not provided all project fields are returned. {@code - * ProjectGetOption.fields} can be used to specify only the fields of interest. Project ID is + * ProjectOption.fields} can be used to specify only the fields of interest. Project ID is * always returned, even if not specified. {@link ProjectField} provides a list of fields that * can be used. */ - public static ProjectGetOption fields(ProjectField... fields) { - return new ProjectGetOption(DnsRpc.Option.FIELDS, ProjectField.selector(fields)); + public static ProjectOption fields(ProjectField... fields) { + return new ProjectOption(DnsRpc.Option.FIELDS, ProjectField.selector(fields)); } } @@ -423,10 +423,11 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { /** * Creates a new zone. * - * @return ZoneInfo object representing the new zone's metadata. In addition to the name, dns name - * and description (supplied by the user within the {@code zoneInfo} parameter, the returned - * object will include the following read-only fields supplied by the server: creation time, id, - * and list of name servers. + *

Returns {@link ZoneInfo} object representing the new zone's information. In addition to the + * name, dns name and description (supplied by the user within the {@code zoneInfo} parameter), + * the returned object will include the following read-only fields supplied by the server: + * creation time, id, and list of name servers. + * * @throws DnsException upon failure * @see Cloud DNS Managed Zones: * create @@ -434,8 +435,8 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { ZoneInfo create(ZoneInfo zoneInfo); /** - * Retrieves the zone by the specified zone name. Returns {@code null} is the zone is not found. - * The returned fields can be optionally restricted by specifying {@code ZoneFieldOptions}. + * Returns the zone by the specified zone name. Returns {@code null} if the zone is not found. The + * returned fields can be optionally restricted by specifying {@link ZoneOption}s. * * @throws DnsException upon failure * @see Cloud DNS Managed Zones: @@ -444,8 +445,8 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { ZoneInfo getZone(String zoneName, ZoneOption... options); /** - * Retrieves the zone by the specified zone name. Returns {@code null} is the zone is not found. - * The returned fields can be optionally restricted by specifying {@code ZoneFieldOptions}. + * Returns the zone by the specified zone id. Returns {@code null} if the zone is not found. The + * returned fields can be optionally restricted by specifying {@link ZoneOption}s. * * @throws DnsException upon failure * @see Cloud DNS Managed Zones: @@ -454,13 +455,13 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { ZoneInfo getZone(BigInteger zoneId, ZoneOption... options); /** - * Lists the zoned inside the project. + * Lists the zones inside the project. * - *

This method returns zone in an unspecified order. New zones do not necessarily appear at the - * end of the list. Use {@link ZoneListOption} to restrict the listing to a domain name, set page - * size, and set page tokens. + *

This method returns zones in an unspecified order. New zones do not necessarily appear at + * the end of the list. Use {@link ZoneListOption} to restrict the listing to a domain name, set + * page size, and set page token. * - * @return {@code Page}, a page of zones + * @return a page of zones * @throws DnsException upon failure * @see Cloud DNS Managed Zones: * list @@ -468,10 +469,10 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { Page listZones(ZoneListOption... options); /** - * Deletes an existing zone identified by name. Returns true if the zone was successfully deleted - * and false otherwise. + * Deletes an existing zone identified by name. Returns {@code true} if the zone was successfully + * deleted and {@code false} otherwise. * - * @return {@code true} if zone was found and deleted and false otherwise + * @return {@code true} if zone was found and deleted and {@code false} otherwise * @throws DnsException upon failure * @see Cloud DNS Managed Zones: * delete @@ -479,10 +480,10 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { boolean delete(String zoneName); // delete does not admit any options /** - * Deletes an existing zone identified by id. Returns true if the zone was successfully deleted - * and false otherwise. + * Deletes an existing zone identified by id. Returns {@code true} if the zone was successfully + * deleted and {@code false} otherwise. * - * @return {@code true} if zone was found and deleted and false otherwise + * @return {@code true} if zone was found and deleted and {@code false} otherwise * @throws DnsException upon failure * @see Cloud DNS Managed Zones: * delete @@ -492,10 +493,10 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { /** * Lists the DNS records in the zone identified by name. * - *

The fields to be returned, page size and page tokens can be specified using {@code - * DnsRecordOptions}. Returns null if the zone cannot be found. + *

The fields to be returned, page size and page tokens can be specified using {@link + * DnsRecordListOption}s. * - * @throws DnsException upon failure + * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS * ResourceRecordSets: list */ @@ -504,23 +505,23 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { /** * Lists the DNS records in the zone identified by ID. * - *

The fields to be returned, page size and page tokens can be specified using {@code - * DnsRecordOptions}. Returns null if the zone cannot be found. + *

The fields to be returned, page size and page tokens can be specified using {@link + * DnsRecordListOption}s. * - * @throws DnsException upon failure + * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS * ResourceRecordSets: list */ Page listDnsRecords(BigInteger zoneId, DnsRecordListOption... options); /** - * Retrieves the metadata about the current project. The returned fields can be optionally - * restricted by specifying {@code ProjectOptions}. + * Retrieves the information about the current project. The returned fields can be optionally + * restricted by specifying {@link ProjectOption}s. * * @throws DnsException upon failure * @see Cloud DNS Projects: get */ - ProjectInfo getProjectInfo(ProjectGetOption... fields); + ProjectInfo getProjectInfo(ProjectOption... fields); /** * Returns the current project id. @@ -533,64 +534,61 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { BigInteger getProjectNumber(); /** - * Submits a change requests for applying to the zone identified by ID to the service. The - * returned object contains the following read-only fields supplied by the server: id, start time - * and status. time, id, and list of name servers. The returned fields can be modified by {@code - * ChangeRequestFieldOptions}. Returns null if the zone is not found. + * Submits a change request for the specified zone. The returned object contains the following + * read-only fields supplied by the server: id, start time and status. time, id, and list of name + * servers. The fields to be returned can be selected by {@link ChangeRequestOption}s. * - * @return ChangeRequest object representing the new change request or null if zone is not found + * @return the new {@link ChangeRequest} or {@code null} if zone is not found * @throws DnsException upon failure * @see Cloud DNS Changes: create */ - ChangeRequest applyChangeRequest(ChangeRequest changeRequest, BigInteger zoneId, - ChangeRequestOption... options); + ChangeRequest applyChangeRequest(BigInteger zoneId, ChangeRequest changeRequest, + ChangeRequestOption... options); /** - * Submits a change requests for applying to the zone identified by name to the service. The - * returned object contains the following read-only fields supplied by the server: id, start time - * and status. time, id, and list of name servers. The returned fields can be modified by {@code - * ChangeRequestFieldOptions}. Returns null if the zone is not found. + * Submits a change request for the specified zone. The returned object contains the following + * read-only fields supplied by the server: id, start time and status. time, id, and list of name + * servers. The fields to be returned can be selected by {@link ChangeRequestOption}s. * - * @return ChangeRequest object representing the new change request or null if zone is not found - * @throws DnsException upon failure + * @return the new {@link ChangeRequest} + * @throws DnsException upon failure if zone is not found * @see Cloud DNS Changes: create */ - ChangeRequest applyChangeRequest(ChangeRequest changeRequest, String zoneName, - ChangeRequestOption... options); + ChangeRequest applyChangeRequest(String zoneName, ChangeRequest changeRequest, + ChangeRequestOption... options); /** * Retrieves updated information about a change request previously submitted for a zone identified - * by ID. Returns null if the zone or request cannot be found. - * - *

The fields to be returned using {@code ChangeRequestFieldOptions}. + * by ID. Returns {@code null} if the request cannot be found and throws an exception if the zone + * does not exist. The fields to be returned using can be specified using {@link + * ChangeRequestOption}s. * - * @throws DnsException upon failure + * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS Chages: get */ - ChangeRequest getChangeRequest(ChangeRequest changeRequest, BigInteger zoneId, - ChangeRequestOption... options); + ChangeRequest getChangeRequest(String changeRequestId, BigInteger zoneId, + ChangeRequestOption... options); /** * Retrieves updated information about a change request previously submitted for a zone identified - * by name. Returns null if the zone or request cannot be found. - * - *

The fields to be returned using {@code ChangeRequestFieldOptions}. + * by ID. Returns {@code null} if the request cannot be found and throws an exception if the zone + * does not exist. The fields to be returned using can be specified using {@link + * ChangeRequestOption}s. * - * @throws DnsException upon failure + * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS Chages: get */ - ChangeRequest getChangeRequest(ChangeRequest changeRequest, String zoneName, - ChangeRequestOption... options); + ChangeRequest getChangeRequest(String changeRequestId, String zoneName, + ChangeRequestOption... options); /** * Lists the change requests for the zone identified by ID that were submitted to the service. * - *

The sorting key for changes, fields to be returned, page and page tokens can be specified - * using {@code ChangeRequestListOptions}. Note that the only sorting key currently supported is - * the timestamp of submitting the change request to the service. + *

The sorting order for changes (based on when they were received by the server), fields to be + * returned, page size and page token can be specified using {@link ChangeRequestListOption}s. * - * @return {@code Page}, a page of change requests - * @throws DnsException upon failure + * @return A page of change requests + * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS Chages: list */ Page listChangeRequests(BigInteger zoneId, ChangeRequestListOption... options); @@ -598,12 +596,11 @@ ChangeRequest getChangeRequest(ChangeRequest changeRequest, String zoneName, /** * Lists the change requests for the zone identified by name that were submitted to the service. * - *

The sorting key for changes, fields to be returned, page and page tokens can be specified - * using {@code ChangeRequestListOptions}. Note that the only sorting key currently supported is - * the timestamp of submitting the change request to the service. + *

The sorting order for changes (based on when they were received by the server), fields to be + * returned, page size and page token can be specified using {@link ChangeRequestListOption}s. * - * @return {@code Page}, a page of change requests - * @throws DnsException upon failure + * @return A page of change requests + * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS Chages: list */ Page listChangeRequests(String zoneName, ChangeRequestListOption... options); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index f4d9702ba12f..dc0be8b94b44 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -16,6 +16,7 @@ package com.google.gcloud.dns; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.gcloud.Page; @@ -52,15 +53,14 @@ public Zone(Dns dns, ZoneInfo zoneInfo) { /** * Constructs a {@code Zone} object that contains meta information received from the Google Cloud - * DNS service for the provided zoneName. + * DNS service for the provided {@code zoneName}. * - * @param zoneName Name of the zone to be searched for - * @param options Optional restriction on what fields should be returned by the service - * @return Zone object containing metadata or null if not not found + * @param zoneName name of the zone to be searched for + * @param options optional restriction on what fields should be returned by the service + * @return zone object containing metadata or {@code null} if not not found * @throws DnsException upon failure */ - public static Zone get(Dns dnsService, String zoneName, - Dns.ZoneOption... options) { + public static Zone get(Dns dnsService, String zoneName, Dns.ZoneOption... options) { checkNotNull(zoneName); checkNotNull(dnsService); ZoneInfo zoneInfo = dnsService.getZone(zoneName, options); @@ -68,16 +68,15 @@ public static Zone get(Dns dnsService, String zoneName, } /** - * Constructs a {@code Zone} object that contains meta information received from the Google Cloud - * DNS service for the provided zoneName. + * Constructs a {@code Zone} object that contains information received from the Google Cloud DNS + * service for the provided {@code zoneId}. * * @param zoneId ID of the zone to be searched for - * @param options Optional restriction on what fields should be returned by the service - * @return Zone object containing metadata or null if not not found + * @param options optional restriction on what fields should be returned by the service + * @return zone object containing zone's information or {@code null} if not not found * @throws DnsException upon failure */ - public static Zone get(Dns dnsService, BigInteger zoneId, - Dns.ZoneOption... options) { + public static Zone get(Dns dnsService, BigInteger zoneId, Dns.ZoneOption... options) { checkNotNull(zoneId); checkNotNull(dnsService); ZoneInfo zoneInfo = dnsService.getZone(zoneId, options); @@ -88,8 +87,8 @@ public static Zone get(Dns dnsService, BigInteger zoneId, * Retrieves the latest information about the zone. The method first attempts to retrieve the zone * by ID and if not set or zone is not found, it searches by name. * - * @param options Optional restriction on what fields should be fetched - * @return Zone object containing updated metadata or null if not not found + * @param options optional restriction on what fields should be fetched + * @return zone object containing updated information or {@code null} if not not found * @throws DnsException upon failure * @throws NullPointerException if both zone ID and name are not initialized */ @@ -110,7 +109,7 @@ public Zone reload(Dns.ZoneOption... options) { * Deletes the zone. The method first attempts to delete the zone by ID. If the zone is not found * or id is not set, it attempts to delete by name. * - * @return true is zone was found and deleted and false otherwise + * @return {@code true} is zone was found and deleted and {@code false} otherwise * @throws DnsException upon failure * @throws NullPointerException if both zone ID and name are not initialized */ @@ -131,10 +130,10 @@ public boolean delete() { * Lists all {@link DnsRecord}s associated with this zone. First searches for zone by ID and if * not found then by name. * - * @param options Optional restriction on listing and on what fields of {@link DnsRecord} should + * @param options optional restriction on listing and on what fields of {@link DnsRecord} should * be returned by the service - * @return {@code Page}, a page of DNS records, or null if the zone is not found - * @throws DnsException upon failure + * @return a page of DNS records + * @throws DnsException upon failure or if the zone is not found * @throws NullPointerException if both zone ID and name are not initialized */ public Page listDnsRecords(Dns.DnsRecordListOption... options) { @@ -153,25 +152,24 @@ public Page listDnsRecords(Dns.DnsRecordListOption... options) { /** * Submits {@link ChangeRequest} to the service for it to applied to this zone. First searches for * the zone by ID and if not found then by name. Returns a {@link ChangeRequest} with - * server-assigned ID or null if the zone was not found. + * server-assigned ID or {@code null} if the zone was not found. * - * @param options Optional restriction on what fields of {@link ChangeRequest} should be returned - * by the service - * @return ChangeRequest with server-assigned ID or null if the zone was not found. - * @throws DnsException upon failure + * @param options optional restriction on what fields of {@link ChangeRequest} should be returned + * @return ChangeRequest with server-assigned ID + * @throws DnsException upon failure or if the zone is not found * @throws NullPointerException if both zone ID and name are not initialized */ public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, - Dns.ChangeRequestOption... options) { + Dns.ChangeRequestOption... options) { checkNameOrIdNotNull(); checkNotNull(changeRequest); ChangeRequest updated = null; if (zoneInfo.id() != null) { - updated = dns.applyChangeRequest(changeRequest, zoneInfo.id(), options); + updated = dns.applyChangeRequest(zoneInfo.id(), changeRequest, options); } if (updated == null && zoneInfo.name() != null) { // zone was not found by id or id is not set at all - updated = dns.applyChangeRequest(changeRequest, zoneInfo.name(), options); + updated = dns.applyChangeRequest(zoneInfo.name(), changeRequest, options); } return updated; } @@ -179,41 +177,38 @@ public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, /** * Retrieves an updated information about a change request previously submitted to be applied to * this zone. First searches for the zone by ID and if not found then by name. Returns a {@link - * ChangeRequest} if found and null is the zone or the change request was not found. + * ChangeRequest} if found and {@code null} is the zone or the change request was not found. * - * @param options Optional restriction on what fields of {@link ChangeRequest} should be returned - * by the service - * @return ChangeRequest with updated information of null if the change request or zone was not - * found. - * @throws DnsException upon failure + * @param options optional restriction on what fields of {@link ChangeRequest} should be returned + * @return updated ChangeRequest + * @throws DnsException upon failure or if the zone is not found * @throws NullPointerException if both zone ID and name are not initialized * @throws NullPointerException if the change request does not have initialized id */ - public ChangeRequest getChangeRequest(ChangeRequest changeRequest, - Dns.ChangeRequestOption... options) { + public ChangeRequest getChangeRequest(String changeRequestId, + Dns.ChangeRequestOption... options) { checkNameOrIdNotNull(); - checkNotNull(changeRequest); - checkNotNull(changeRequest.id()); + checkNotNull(changeRequestId); ChangeRequest updated = null; if (zoneInfo.id() != null) { - updated = dns.getChangeRequest(changeRequest, zoneInfo.id(), options); + updated = dns.getChangeRequest(changeRequestId, zoneInfo.id(), options); } if (updated == null && zoneInfo.name() != null) { // zone was not found by id or id is not set at all - updated = dns.getChangeRequest(changeRequest, zoneInfo.name(), options); + updated = dns.getChangeRequest(changeRequestId, zoneInfo.name(), options); } return updated; } /** * Retrieves all change requests for this zone. First searches for the zone by ID and if not found - * then by name. Returns a page of {@link ChangeRequest}s or null if the zone is not found. + * then by name. Returns a page of {@link ChangeRequest}s or {@code null} if the zone is not + * found. * - * @param options Optional restriction on listing and on what fields of {@link ChangeRequest}s + * @param options optional restriction on listing and on what fields of {@link ChangeRequest}s * should be returned by the service - * @return {@code Page}, a page of change requests, or null if the zone is not - * found - * @throws DnsException upon failure + * @return a page of change requests + * @throws DnsException upon failure or if the zone is not found * @throws NullPointerException if both zone ID and name are not initialized */ public Page listChangeRequests(Dns.ChangeRequestListOption... options) { @@ -233,24 +228,21 @@ public Page listChangeRequests(Dns.ChangeRequestListOption... opt * Check that at least one of name and ID are initialized and throw and exception if not. */ private void checkNameOrIdNotNull() { - if (zoneInfo != null && zoneInfo.id() == null && zoneInfo.name() == null) { - throw new NullPointerException("Both zoneInfo.id and zoneInfo.name are null. " - + "This is an inconsistent state which should never happen."); - } + checkArgument(zoneInfo != null && (zoneInfo.id() != null || zoneInfo.name() != null), + "Both zoneInfo.id and zoneInfo.name are null. This is should never happen."); } /** - * Returns the {@link ZoneInfo} object containing meta information about this managed zone. + * Returns the {@link ZoneInfo} object containing information about this zone. */ public ZoneInfo info() { return this.zoneInfo; } /** - * Returns the {@link Dns} service object associated with this managed zone. + * Returns the {@link Dns} service object associated with this zone. */ public Dns dns() { return this.dns; } - } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index 2e98dbd46de4..a60cae1d1793 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -94,7 +94,7 @@ public void testZoneList() { @Test public void testProjectGetOption() { // fields - Dns.ProjectGetOption fields = Dns.ProjectGetOption.fields(Dns.ProjectField.QUOTA); + Dns.ProjectOption fields = Dns.ProjectOption.fields(Dns.ProjectField.QUOTA); assertEquals(DnsRpc.Option.FIELDS, fields.rpcOption()); assertTrue(fields.value() instanceof String); assertTrue(((String) fields.value()).contains(Dns.ProjectField.QUOTA.selector())); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 5f9d119e6150..a87bb969855b 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -348,9 +348,9 @@ public void reloadByNameAndNotFound() { @Test public void applyChangeByIdAndFound() { - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(CHANGE_REQUEST_AFTER); + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); @@ -364,13 +364,13 @@ public void applyChangeByIdAndFound() { @Test public void applyChangeByIdAndNotFoundAndNameSetAndFound() { - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(null); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); @@ -384,12 +384,12 @@ public void applyChangeByIdAndNotFoundAndNameSetAndFound() { @Test public void applyChangeIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(null); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andReturn(null); // again with options - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); @@ -401,8 +401,8 @@ public void applyChangeIdAndNotFoundAndNameSetAndNotFound() { @Test public void applyChangeRequestByIdAndNotFoundAndNameNotSet() { - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(null); + expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); // for options replay(dns); ChangeRequest result = zoneNoName.applyChangeRequest(CHANGE_REQUEST); @@ -415,10 +415,10 @@ public void applyChangeRequestByIdAndNotFoundAndNameNotSet() { @Test public void applyChangeByNameAndFound() { // ID is not set - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); @@ -431,9 +431,9 @@ public void applyChangeByNameAndFound() { @Test public void applyChangeByNameAndNotFound() { // ID is not set - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andReturn(null); // again for options - expect(dns.applyChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); @@ -486,16 +486,16 @@ public void applyNullChangeRequest() { @Test public void getChangeByIdAndFound() { - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(CHANGE_REQUEST_AFTER); + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST); + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); assertNotEquals(CHANGE_REQUEST, result); assertEquals(CHANGE_REQUEST_AFTER, result); // for options - result = zone.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertNotEquals(CHANGE_REQUEST, result); assertEquals(CHANGE_REQUEST_AFTER, result); // test no id @@ -503,82 +503,82 @@ public void getChangeByIdAndFound() { @Test public void getChangeByIdAndNotFoundAndNameSetAndFound() { - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST); + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); assertNotEquals(CHANGE_REQUEST, result); assertEquals(CHANGE_REQUEST_AFTER, result); // for options - result = zone.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertNotEquals(CHANGE_REQUEST, result); assertEquals(CHANGE_REQUEST_AFTER, result); } @Test public void getChangeIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)).andReturn(null); // again with options - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST); + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); assertNull(result); // again for options - result = zone.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertNull(result); } @Test public void getChangeRequestByIdAndNotFoundAndNameNotSet() { - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID)).andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); // for options replay(dns); - ChangeRequest result = zoneNoName.getChangeRequest(CHANGE_REQUEST); + ChangeRequest result = zoneNoName.getChangeRequest(CHANGE_REQUEST.id()); assertNull(result); // again for options - result = zoneNoName.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + result = zoneNoName.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertNull(result); } @Test public void getChangeByNameAndFound() { // ID is not set - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); assertEquals(CHANGE_REQUEST_AFTER, result); // check options - result = zoneNoId.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertEquals(CHANGE_REQUEST_AFTER, result); } @Test public void getChangeByNameAndNotFound() { // ID is not set - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME)).andReturn(null); + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)).andReturn(null); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST, ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); assertNull(result); // check options - result = zoneNoId.getChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertNull(result); } @@ -627,38 +627,38 @@ public void getNullChangeRequest() { public void getChangeRequestWithNoId() { replay(dns); // no calls expected try { - zone.getChangeRequest(CHANGE_REQUEST_NO_ID); - fail("Cannot get ChangeRequest with no id."); + zone.getChangeRequest(CHANGE_REQUEST_NO_ID.id()); + fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST_NO_ID, CHANGE_REQUEST_FIELD_OPTIONS); - fail("Cannot get ChangeRequest with no id."); + zone.getChangeRequest(CHANGE_REQUEST_NO_ID.id(), CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID); - fail("Cannot get ChangeRequest with no id."); + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.id()); + fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID, CHANGE_REQUEST_FIELD_OPTIONS); - fail("Cannot get ChangeRequest with no id."); + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.id(), CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID); - fail("Cannot get ChangeRequest with no id."); + zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID.id()); + fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID, CHANGE_REQUEST_FIELD_OPTIONS); - fail("Cannot get ChangeRequest with no id."); + zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID.id(), CHANGE_REQUEST_FIELD_OPTIONS); + fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } From d6daf0956ff0975bed3115f9b09a1381bc1cf137 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 2 Feb 2016 16:17:31 -0800 Subject: [PATCH 36/74] Adjusted documentation, removed getProjectId and getProjectNumber --- .../main/java/com/google/gcloud/dns/Dns.java | 14 +---- .../main/java/com/google/gcloud/dns/Zone.java | 12 ++-- .../java/com/google/gcloud/dns/ZoneTest.java | 56 ++++++++++--------- 3 files changed, 37 insertions(+), 45 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 130e8bb99f5e..644814fa201b 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -523,16 +523,6 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { */ ProjectInfo getProjectInfo(ProjectOption... fields); - /** - * Returns the current project id. - */ - String getProjectId(); - - /** - * Returns the current project number. - */ - BigInteger getProjectNumber(); - /** * Submits a change request for the specified zone. The returned object contains the following * read-only fields supplied by the server: id, start time and status. time, id, and list of name @@ -566,7 +556,7 @@ ChangeRequest applyChangeRequest(String zoneName, ChangeRequest changeRequest, * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS Chages: get */ - ChangeRequest getChangeRequest(String changeRequestId, BigInteger zoneId, + ChangeRequest getChangeRequest(BigInteger zoneId, String changeRequestId, ChangeRequestOption... options); /** @@ -578,7 +568,7 @@ ChangeRequest getChangeRequest(String changeRequestId, BigInteger zoneId, * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS Chages: get */ - ChangeRequest getChangeRequest(String changeRequestId, String zoneName, + ChangeRequest getChangeRequest(String zoneName, String changeRequestId, ChangeRequestOption... options); /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index dc0be8b94b44..86fc86bc3688 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -130,8 +130,7 @@ public boolean delete() { * Lists all {@link DnsRecord}s associated with this zone. First searches for zone by ID and if * not found then by name. * - * @param options optional restriction on listing and on what fields of {@link DnsRecord} should - * be returned by the service + * @param options optional restriction on listing and fields of {@link DnsRecord}s returned * @return a page of DNS records * @throws DnsException upon failure or if the zone is not found * @throws NullPointerException if both zone ID and name are not initialized @@ -191,11 +190,11 @@ public ChangeRequest getChangeRequest(String changeRequestId, checkNotNull(changeRequestId); ChangeRequest updated = null; if (zoneInfo.id() != null) { - updated = dns.getChangeRequest(changeRequestId, zoneInfo.id(), options); + updated = dns.getChangeRequest(zoneInfo.id(), changeRequestId, options); } if (updated == null && zoneInfo.name() != null) { // zone was not found by id or id is not set at all - updated = dns.getChangeRequest(changeRequestId, zoneInfo.name(), options); + updated = dns.getChangeRequest(zoneInfo.name(), changeRequestId, options); } return updated; } @@ -205,8 +204,7 @@ public ChangeRequest getChangeRequest(String changeRequestId, * then by name. Returns a page of {@link ChangeRequest}s or {@code null} if the zone is not * found. * - * @param options optional restriction on listing and on what fields of {@link ChangeRequest}s - * should be returned by the service + * @param options optional restriction on listing and fields to be returned * @return a page of change requests * @throws DnsException upon failure or if the zone is not found * @throws NullPointerException if both zone ID and name are not initialized @@ -236,7 +234,7 @@ private void checkNameOrIdNotNull() { * Returns the {@link ZoneInfo} object containing information about this zone. */ public ZoneInfo info() { - return this.zoneInfo; + return zoneInfo; } /** diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index a87bb969855b..c746140ce599 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -101,16 +101,15 @@ public void testGetById() { Zone retrieved = Zone.get(dns, ZONE_ID); assertSame(dns, retrieved.dns()); assertEquals(ZONE_INFO, retrieved.info()); - BigInteger id = null; try { - Zone.get(dns, id); - fail("Cannot get null zone."); + Zone.get(dns, (BigInteger) null); + fail("Cannot get by null id."); } catch (NullPointerException e) { // expected } try { - Zone.get(null, id); - fail("Cannot get null zone."); + Zone.get(null, new BigInteger("12")); + fail("Cannot get anything from null service."); } catch (NullPointerException e) { // expected } @@ -126,16 +125,15 @@ public void testGetByName() { Zone retrieved = Zone.get(dns, ZONE_NAME); assertSame(dns, retrieved.dns()); assertEquals(ZONE_INFO, retrieved.info()); - String name = null; try { - Zone.get(dns, name); - fail("Cannot get null zone."); + Zone.get(dns, (String) null); + fail("Cannot get by null name."); } catch (NullPointerException e) { // expected } try { - Zone.get(null, name); - fail("Cannot get null zone."); + Zone.get(null, "Not null"); + fail("Cannot get anything from null service."); } catch (NullPointerException e) { // expected } @@ -195,6 +193,7 @@ public void deleteByNameAndNotFound() { @Test public void listDnsRecordsByIdAndFound() { + @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); expect(dns.listDnsRecords(ZONE_ID)).andReturn(pageMock); @@ -210,6 +209,7 @@ public void listDnsRecordsByIdAndFound() { @Test public void listDnsRecordsByIdAndNotFoundAndNameSetAndFound() { + @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); @@ -251,6 +251,7 @@ public void listDnsRecordsByIdAndNotFoundAndNameNotSet() { @Test public void listDnsRecordsByNameAndFound() { + @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); @@ -486,9 +487,9 @@ public void applyNullChangeRequest() { @Test public void getChangeByIdAndFound() { - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(CHANGE_REQUEST_AFTER); + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); @@ -503,13 +504,13 @@ public void getChangeByIdAndFound() { @Test public void getChangeByIdAndNotFoundAndNameSetAndFound() { - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)) + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); @@ -523,12 +524,12 @@ public void getChangeByIdAndNotFoundAndNameSetAndFound() { @Test public void getChangeIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)).andReturn(null); + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); // again with options - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); @@ -540,8 +541,8 @@ public void getChangeIdAndNotFoundAndNameSetAndNotFound() { @Test public void getChangeRequestByIdAndNotFoundAndNameNotSet() { - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID)).andReturn(null); - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_ID, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(null); + expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); // for options replay(dns); ChangeRequest result = zoneNoName.getChangeRequest(CHANGE_REQUEST.id()); @@ -554,10 +555,10 @@ public void getChangeRequestByIdAndNotFoundAndNameNotSet() { @Test public void getChangeByNameAndFound() { // ID is not set - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); @@ -570,9 +571,9 @@ public void getChangeByNameAndFound() { @Test public void getChangeByNameAndNotFound() { // ID is not set - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME)).andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); // again for options - expect(dns.getChangeRequest(CHANGE_REQUEST.id(), ZONE_NAME, CHANGE_REQUEST_FIELD_OPTIONS)) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); @@ -666,6 +667,7 @@ public void getChangeRequestWithNoId() { @Test public void listChangeRequestsByIdAndFound() { + @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); expect(dns.listChangeRequests(ZONE_ID)).andReturn(pageMock); @@ -681,6 +683,7 @@ public void listChangeRequestsByIdAndFound() { @Test public void listChangeRequestsByIdAndNotFoundAndNameSetAndFound() { + @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); @@ -724,6 +727,7 @@ public void listChangeRequestsByIdAndNotFoundAndNameNotSet() { @Test public void listChangeRequestsByNameAndFound() { + @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); From 0338ead2661b9099da81adb11ebb6e18553ef2e4 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 3 Feb 2016 09:01:39 -0800 Subject: [PATCH 37/74] Completes DnsRpc interface by adding methods and doc. Closes #594. --- .../java/com/google/gcloud/spi/DnsRpc.java | 117 +++++++++++++++++- 1 file changed, 116 insertions(+), 1 deletion(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java index f6a0f330a327..9c0f7f3809df 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java @@ -16,6 +16,12 @@ package com.google.gcloud.spi; +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.Project; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.gcloud.dns.DnsException; + import java.util.Map; public interface DnsRpc { @@ -52,5 +58,114 @@ Integer getInt(Map options) { } } - //TODO(mderka) add supported operations. Created issue #594. + class Tuple { + + private final X x; + private final Y y; + + private Tuple(X x, Y y) { + this.x = x; + this.y = y; + } + + public static Tuple of(X x, Y y) { + return new Tuple<>(x, y); + } + + public X x() { + return x; + } + + public Y y() { + return y; + } + } + + /** + * Creates a new zone. + * + * @param zone a zone to be created + * @return Updated {@link ManagedZone} object + * @throws DnsException upon failure + */ + ManagedZone create(ManagedZone zone) throws DnsException; + + /** + * Retrieves and returns an existing zone. + * + * @param zoneName name of the zone to be returned + * @param options a map of options for the service call + * @return a zone or {@code null} if not found + * @throws DnsException upon failure + */ + ManagedZone getZone(String zoneName, Map options) throws DnsException; + + /** + * Lists the zones that exist within the project. + * + * @param options a map of options for the service call + * @throws DnsException upon failure + */ + Tuple> listZones(Map options) throws DnsException; + + /** + * Deletes the zone identified by the name. + * + * @return {@code true} if the zone was deleted and {@code false} otherwise + * @throws DnsException upon failure + */ + boolean deleteZone(String zoneName) throws DnsException; + + /** + * Lists DNS records for a given zone. + * + * @param zoneName name of the zone to be listed + * @param options a map of options for the service call + * @throws DnsException upon failure or if zone not found + */ + Tuple> listDnsRecords(String zoneName, + Map options) throws DnsException; + + /** + * Returns information about the current project. + * + * @param options a map of options for the service call + * @return up-to-date project information + * @throws DnsException upon failure + */ + Project getProject(Map options) throws DnsException; + + /** + * Applies change request to a zone. + * + * @param zoneName the name of a zone to which the {@link Change} should be applied + * @param changeRequest change to be applied + * @param options a map of options for the service call + * @return updated change object with server-assigned ID + * @throws DnsException upon failure or if zone not found + */ + Change applyChangeRequest(String zoneName, Change changeRequest, Map options) + throws DnsException; + + /** + * Returns an existing change request. + * + * @param zoneName the name of a zone to which the {@link Change} was be applied + * @param changeRequestId the unique id assigned to the change by the server + * @param options a map of options for the service call + * @return up-to-date change object + * @throws DnsException upon failure or if zone not found + */ + Change getChangeRequest(String zoneName, String changeRequestId, Map options) + throws DnsException; + + /** + * List an existing change requests for a zone. + * + * @param zoneName the name of a zone to which the {@link Change}s were be applied + * @param options a map of options for the service call + * @throws DnsException upon failure or if zone not found + */ + Tuple> listChangeRequests(String zoneName, Map options) + throws DnsException; } From bc4b8204093d92782d04319c8efda9aae424b9cc Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 3 Feb 2016 10:46:44 -0800 Subject: [PATCH 38/74] Implements DefaultDnsRpc. Progress in #595. --- .../com/google/gcloud/dns/DnsException.java | 4 +- .../com/google/gcloud/dns/DnsOptions.java | 6 +- .../com/google/gcloud/spi/DefaultDnsRpc.java | 178 ++++++++++++++++++ 3 files changed, 183 insertions(+), 5 deletions(-) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java index d18f6163a881..73c546759260 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java @@ -27,8 +27,8 @@ public class DnsException extends BaseServiceException { private static final long serialVersionUID = 490302380416260252L; - public DnsException(IOException exception, boolean idempotent) { - super(exception, idempotent); + public DnsException(IOException exception) { + super(exception, true); } //TODO(mderka) Add translation and retry functionality. Created issue #593. 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 1845467c2537..248fd164a55f 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 @@ -18,6 +18,7 @@ import com.google.common.collect.ImmutableSet; import com.google.gcloud.ServiceOptions; +import com.google.gcloud.spi.DefaultDnsRpc; import com.google.gcloud.spi.DnsRpc; import com.google.gcloud.spi.DnsRpcFactory; @@ -46,8 +47,7 @@ public static class DefaultDnsRpcFactory implements DnsRpcFactory { @Override public DnsRpc create(DnsOptions options) { - // TODO(mderka) Implement when DefaultDnsRpc is available. Created issue #595. - return null; + return new DefaultDnsRpc(options); } } @@ -80,7 +80,7 @@ protected DnsFactory defaultServiceFactory() { @SuppressWarnings("unchecked") @Override protected DnsRpcFactory defaultRpcFactory() { - return null; + return DefaultDnsRpcFactory.INSTANCE; } @Override diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java new file mode 100644 index 000000000000..77eb36e3b5ed --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -0,0 +1,178 @@ +package com.google.gcloud.spi; + +import static com.google.gcloud.spi.DnsRpc.Option.DNS_NAME; +import static com.google.gcloud.spi.DnsRpc.Option.DNS_TYPE; +import static com.google.gcloud.spi.DnsRpc.Option.FIELDS; +import static com.google.gcloud.spi.DnsRpc.Option.PAGE_SIZE; +import static com.google.gcloud.spi.DnsRpc.Option.PAGE_TOKEN; +import static com.google.gcloud.spi.DnsRpc.Option.SORTING_ORDER; +import static java.net.HttpURLConnection.HTTP_NOT_FOUND; + +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.json.jackson.JacksonFactory; +import com.google.api.services.dns.Dns; +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ChangesListResponse; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.ManagedZonesListResponse; +import com.google.api.services.dns.model.Project; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.api.services.dns.model.ResourceRecordSetsListResponse; +import com.google.gcloud.dns.DnsException; +import com.google.gcloud.dns.DnsOptions; + +import java.io.IOException; +import java.util.Map; + +/** + * A default implementation of the DnsRpc interface. + */ +public class DefaultDnsRpc implements DnsRpc { + + private final Dns dns; + private final DnsOptions options; + + private static DnsException translate(IOException exception) { + return new DnsException(exception); + } + + /** + * Constructs an instance of this rpc client with provided {@link DnsOptions}. + */ + public DefaultDnsRpc(DnsOptions options) { + HttpTransport transport = options.httpTransportFactory().create(); + HttpRequestInitializer initializer = options.httpRequestInitializer(); + this.dns = new Dns.Builder(transport, new JacksonFactory(), initializer) + .setRootUrl(options.host()) + .setApplicationName(options.applicationName()) + .build(); + this.options = options; + } + + @Override + public ManagedZone create(ManagedZone zone) throws DnsException { + try { + return dns.managedZones().create(this.options.projectId(), zone).execute(); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public ManagedZone getZone(String zoneName, Map options) throws DnsException { + // just fields option + try { + return dns.managedZones().get(this.options.projectId(), zoneName) + .setFields(FIELDS.getString(options)).execute(); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public Tuple> listZones(Map options) + throws DnsException { + // fields, page token, page size + try { + ManagedZonesListResponse zoneList = dns.managedZones().list(this.options.projectId()) + .setFields(FIELDS.getString(options)) + .setMaxResults(PAGE_SIZE.getInt(options)) + .setPageToken(PAGE_TOKEN.getString(options)) + .execute(); + return Tuple.>of(zoneList.getNextPageToken(), + zoneList.getManagedZones()); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public boolean deleteZone(String zoneName) throws DnsException { + try { + dns.managedZones().delete(this.options.projectId(), zoneName).execute(); + return true; + } catch (IOException ex) { + DnsException serviceException = translate(ex); + if (serviceException.code() == HTTP_NOT_FOUND) { + return false; + } + throw serviceException; + } + } + + @Override + public Tuple> listDnsRecords(String zoneName, + Map options) throws DnsException { + // options are fields, page token, dns name, type + try { + ResourceRecordSetsListResponse response = dns.resourceRecordSets() + .list(this.options.projectId(), zoneName) + .setFields(FIELDS.getString(options)) + .setPageToken(PAGE_TOKEN.getString(options)) + .setMaxResults(PAGE_SIZE.getInt(options)) + .setName(DNS_NAME.getString(options)) + .setType(DNS_TYPE.getString(options)) + .execute(); + return Tuple.>of(response.getNextPageToken(), + response.getRrsets()); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public Project getProject(Map options) throws DnsException { + try { + return dns.projects().get(this.options.projectId()) + .setFields(FIELDS.getString(options)).execute(); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public Change applyChangeRequest(String zoneName, Change changeRequest, Map options) + throws DnsException { + try { + return dns.changes().create(this.options.projectId(), zoneName, changeRequest) + .setFields(FIELDS.getString(options)) + .execute(); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public Change getChangeRequest(String zoneName, String changeRequestId, Map options) + throws DnsException { + try { + return dns.changes().get(this.options.projectId(), zoneName, changeRequestId) + .setFields(FIELDS.getString(options)) + .execute(); + } catch (IOException ex) { + throw translate(ex); + } + } + + @Override + public Tuple> listChangeRequests(String zoneName, Map options) + throws DnsException { + // options are fields, page token, page size, sort order + try { + Dns.Changes.List request = dns.changes().list(this.options.projectId(), zoneName) + .setFields(FIELDS.getString(options)) + .setMaxResults(PAGE_SIZE.getInt(options)) + .setPageToken(PAGE_TOKEN.getString(options)); + if (SORTING_ORDER.getString(options) != null) { + // this needs to be checked and changed if more sorting options are implemented, issue #604 + String key = "changeSequence"; + request = request.setSortBy(key).setSortOrder(SORTING_ORDER.getString(options)); + } + ChangesListResponse response = request.execute(); + return Tuple.>of(response.getNextPageToken(), response.getChanges()); + } catch (IOException ex) { + throw translate(ex); + } + } +} From 896de75d1cad86e1b2cc2e82bb20700c240fd4ec Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 3 Feb 2016 14:34:38 -0800 Subject: [PATCH 39/74] Fixed documentation and null returns from rpc. --- .../com/google/gcloud/spi/DefaultDnsRpc.java | 26 ++++++++++++++----- .../java/com/google/gcloud/spi/DnsRpc.java | 22 ++++++++-------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index 77eb36e3b5ed..85783d0fdcb6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -30,6 +30,7 @@ */ public class DefaultDnsRpc implements DnsRpc { + private static final String SORTING_KEY = "changeSequence"; private final Dns dns; private final DnsOptions options; @@ -64,9 +65,14 @@ public ManagedZone getZone(String zoneName, Map options) throws DnsEx // just fields option try { return dns.managedZones().get(this.options.projectId(), zoneName) - .setFields(FIELDS.getString(options)).execute(); + .setFields(FIELDS.getString(options)) + .execute(); } catch (IOException ex) { - throw translate(ex); + DnsException serviceException = translate(ex); + if (serviceException.code() == HTTP_NOT_FOUND) { + return null; + } + throw serviceException; } } @@ -151,7 +157,16 @@ public Change getChangeRequest(String zoneName, String changeRequestId, Map> listChangeRequests(String zoneName, Map>of(response.getNextPageToken(), response.getChanges()); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java index 9c0f7f3809df..bff396dedfab 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java @@ -85,7 +85,7 @@ public Y y() { * Creates a new zone. * * @param zone a zone to be created - * @return Updated {@link ManagedZone} object + * @return Updated {@code ManagedZone} object * @throws DnsException upon failure */ ManagedZone create(ManagedZone zone) throws DnsException; @@ -121,7 +121,7 @@ public Y y() { * * @param zoneName name of the zone to be listed * @param options a map of options for the service call - * @throws DnsException upon failure or if zone not found + * @throws DnsException upon failure or if zone was not found */ Tuple> listDnsRecords(String zoneName, Map options) throws DnsException; @@ -131,18 +131,18 @@ Tuple> listDnsRecords(String zoneName, * * @param options a map of options for the service call * @return up-to-date project information - * @throws DnsException upon failure + * @throws DnsException upon failure or if the project is not found */ Project getProject(Map options) throws DnsException; /** * Applies change request to a zone. * - * @param zoneName the name of a zone to which the {@link Change} should be applied + * @param zoneName the name of a zone to which the {@code Change} should be applied * @param changeRequest change to be applied * @param options a map of options for the service call * @return updated change object with server-assigned ID - * @throws DnsException upon failure or if zone not found + * @throws DnsException upon failure or if zone was not found */ Change applyChangeRequest(String zoneName, Change changeRequest, Map options) throws DnsException; @@ -150,21 +150,21 @@ Change applyChangeRequest(String zoneName, Change changeRequest, Map /** * Returns an existing change request. * - * @param zoneName the name of a zone to which the {@link Change} was be applied + * @param zoneName the name of a zone to which the {@code Change} was be applied * @param changeRequestId the unique id assigned to the change by the server * @param options a map of options for the service call - * @return up-to-date change object - * @throws DnsException upon failure or if zone not found + * @return up-to-date change object or {@code null} if change was not found + * @throws DnsException upon failure or if zone was not found */ Change getChangeRequest(String zoneName, String changeRequestId, Map options) throws DnsException; /** - * List an existing change requests for a zone. + * List existing change requests for a zone. * - * @param zoneName the name of a zone to which the {@link Change}s were be applied + * @param zoneName the name of a zone to which the {@code Change}s were be applied * @param options a map of options for the service call - * @throws DnsException upon failure or if zone not found + * @throws DnsException upon failure or if zone was not found */ Tuple> listChangeRequests(String zoneName, Map options) throws DnsException; From 3ae0f215d990f21b0c95fa1da07bbd8f8594fe1b Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 4 Feb 2016 09:11:09 -0800 Subject: [PATCH 40/74] Change Tuple into ListResult, added NAME option. --- .../main/java/com/google/gcloud/dns/Dns.java | 2 +- .../com/google/gcloud/spi/DefaultDnsRpc.java | 29 ++++++------ .../java/com/google/gcloud/spi/DnsRpc.java | 44 ++++++++++--------- .../java/com/google/gcloud/dns/DnsTest.java | 2 +- 4 files changed, 39 insertions(+), 38 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 644814fa201b..1227a9e3b323 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -230,7 +230,7 @@ public static DnsRecordListOption pageSize(int pageSize) { * Restricts the list to only DNS records with this fully qualified domain name. */ public static DnsRecordListOption dnsName(String dnsName) { - return new DnsRecordListOption(DnsRpc.Option.DNS_NAME, dnsName); + return new DnsRecordListOption(DnsRpc.Option.NAME, dnsName); } /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index 85783d0fdcb6..73e6ab4036ec 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -1,6 +1,8 @@ package com.google.gcloud.spi; +import static com.google.gcloud.spi.DnsRpc.ListResult.of; import static com.google.gcloud.spi.DnsRpc.Option.DNS_NAME; +import static com.google.gcloud.spi.DnsRpc.Option.NAME; import static com.google.gcloud.spi.DnsRpc.Option.DNS_TYPE; import static com.google.gcloud.spi.DnsRpc.Option.FIELDS; import static com.google.gcloud.spi.DnsRpc.Option.PAGE_SIZE; @@ -30,7 +32,7 @@ */ public class DefaultDnsRpc implements DnsRpc { - private static final String SORTING_KEY = "changeSequence"; + private static final String SORT_BY = "changeSequence"; private final Dns dns; private final DnsOptions options; @@ -77,17 +79,16 @@ public ManagedZone getZone(String zoneName, Map options) throws DnsEx } @Override - public Tuple> listZones(Map options) - throws DnsException { + public ListResult listZones(Map options) throws DnsException { // fields, page token, page size try { ManagedZonesListResponse zoneList = dns.managedZones().list(this.options.projectId()) .setFields(FIELDS.getString(options)) .setMaxResults(PAGE_SIZE.getInt(options)) + .setDnsName(DNS_NAME.getString(options)) .setPageToken(PAGE_TOKEN.getString(options)) .execute(); - return Tuple.>of(zoneList.getNextPageToken(), - zoneList.getManagedZones()); + return of(zoneList.getNextPageToken(), zoneList.getManagedZones()); } catch (IOException ex) { throw translate(ex); } @@ -108,8 +109,8 @@ public boolean deleteZone(String zoneName) throws DnsException { } @Override - public Tuple> listDnsRecords(String zoneName, - Map options) throws DnsException { + public ListResult listDnsRecords(String zoneName, Map options) + throws DnsException { // options are fields, page token, dns name, type try { ResourceRecordSetsListResponse response = dns.resourceRecordSets() @@ -117,11 +118,10 @@ public Tuple> listDnsRecords(String zoneName .setFields(FIELDS.getString(options)) .setPageToken(PAGE_TOKEN.getString(options)) .setMaxResults(PAGE_SIZE.getInt(options)) - .setName(DNS_NAME.getString(options)) + .setName(NAME.getString(options)) .setType(DNS_TYPE.getString(options)) .execute(); - return Tuple.>of(response.getNextPageToken(), - response.getRrsets()); + return of(response.getNextPageToken(), response.getRrsets()); } catch (IOException ex) { throw translate(ex); } @@ -159,8 +159,7 @@ public Change getChangeRequest(String zoneName, String changeRequestId, Map> listChangeRequests(String zoneName, Map options) + public ListResult listChangeRequests(String zoneName, Map options) throws DnsException { // options are fields, page token, page size, sort order try { @@ -181,10 +180,10 @@ public Tuple> listChangeRequests(String zoneName, Map>of(response.getNextPageToken(), response.getChanges()); + return ListResult.of(response.getNextPageToken(), response.getChanges()); } catch (IOException ex) { throw translate(ex); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java index bff396dedfab..c3cd3c690177 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java @@ -20,6 +20,7 @@ import com.google.api.services.dns.model.ManagedZone; import com.google.api.services.dns.model.Project; import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.collect.ImmutableList; import com.google.gcloud.dns.DnsException; import java.util.Map; @@ -28,9 +29,10 @@ public interface DnsRpc { enum Option { FIELDS("fields"), - PAGE_SIZE("maxSize"), + PAGE_SIZE("maxResults"), PAGE_TOKEN("pageToken"), DNS_NAME("dnsName"), + NAME("name"), DNS_TYPE("type"), SORTING_ORDER("sortOrder"); @@ -58,26 +60,26 @@ Integer getInt(Map options) { } } - class Tuple { + class ListResult { - private final X x; - private final Y y; + private final Iterable results; + private final String pageToken; - private Tuple(X x, Y y) { - this.x = x; - this.y = y; + public ListResult(String pageToken, Iterable results) { + this.results = ImmutableList.copyOf(results); + this.pageToken = pageToken; } - public static Tuple of(X x, Y y) { - return new Tuple<>(x, y); + public static ListResult of(String pageToken, Iterable list) { + return new ListResult<>(pageToken, list); } - public X x() { - return x; + public Iterable results() { + return results; } - public Y y() { - return y; + public String pageToken() { + return pageToken; } } @@ -106,7 +108,7 @@ public Y y() { * @param options a map of options for the service call * @throws DnsException upon failure */ - Tuple> listZones(Map options) throws DnsException; + ListResult listZones(Map options) throws DnsException; /** * Deletes the zone identified by the name. @@ -123,12 +125,12 @@ public Y y() { * @param options a map of options for the service call * @throws DnsException upon failure or if zone was not found */ - Tuple> listDnsRecords(String zoneName, - Map options) throws DnsException; + ListResult listDnsRecords(String zoneName, Map options) + throws DnsException; /** * Returns information about the current project. - * + * * @param options a map of options for the service call * @return up-to-date project information * @throws DnsException upon failure or if the project is not found @@ -136,7 +138,7 @@ Tuple> listDnsRecords(String zoneName, Project getProject(Map options) throws DnsException; /** - * Applies change request to a zone. + * Applies change request to a zone. * * @param zoneName the name of a zone to which the {@code Change} should be applied * @param changeRequest change to be applied @@ -144,7 +146,7 @@ Tuple> listDnsRecords(String zoneName, * @return updated change object with server-assigned ID * @throws DnsException upon failure or if zone was not found */ - Change applyChangeRequest(String zoneName, Change changeRequest, Map options) + Change applyChangeRequest(String zoneName, Change changeRequest, Map options) throws DnsException; /** @@ -156,7 +158,7 @@ Change applyChangeRequest(String zoneName, Change changeRequest, Map * @return up-to-date change object or {@code null} if change was not found * @throws DnsException upon failure or if zone was not found */ - Change getChangeRequest(String zoneName, String changeRequestId, Map options) + Change getChangeRequest(String zoneName, String changeRequestId, Map options) throws DnsException; /** @@ -166,6 +168,6 @@ Change getChangeRequest(String zoneName, String changeRequestId, Map * @param options a map of options for the service call * @throws DnsException upon failure or if zone was not found */ - Tuple> listChangeRequests(String zoneName, Map options) + ListResult listChangeRequests(String zoneName, Map options) throws DnsException; } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index a60cae1d1793..c2be251cea9e 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -34,7 +34,7 @@ public void testDnsRecordListOption() { String dnsName = "some name"; Dns.DnsRecordListOption dnsRecordListOption = Dns.DnsRecordListOption.dnsName(dnsName); assertEquals(dnsName, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.DNS_NAME, dnsRecordListOption.rpcOption()); + assertEquals(DnsRpc.Option.NAME, dnsRecordListOption.rpcOption()); // page token dnsRecordListOption = Dns.DnsRecordListOption.pageToken(PAGE_TOKEN); assertEquals(PAGE_TOKEN, dnsRecordListOption.value()); From 71f5ae22187569bf20461bcb6021761bc9864856 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 4 Feb 2016 13:54:44 -0800 Subject: [PATCH 41/74] Makes name of Zone mandatory and removes id-based methods. Also makes id a read-only string instead of BigInteger. Includes rewriting testsfor Zone. --- .../main/java/com/google/gcloud/dns/Dns.java | 81 +-- .../main/java/com/google/gcloud/dns/Zone.java | 127 +--- .../java/com/google/gcloud/dns/ZoneInfo.java | 35 +- .../com/google/gcloud/spi/DefaultDnsRpc.java | 2 +- .../com/google/gcloud/dns/ZoneInfoTest.java | 44 +- .../java/com/google/gcloud/dns/ZoneTest.java | 608 +++++------------- 6 files changed, 223 insertions(+), 674 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 1227a9e3b323..af0868ec17d6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -23,7 +23,6 @@ import com.google.gcloud.spi.DnsRpc; import java.io.Serializable; -import java.math.BigInteger; import java.util.Set; /** @@ -69,8 +68,7 @@ static String selector(ProjectField... fields) { * The fields of a zone. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#getZone(BigInteger, ZoneOption...)} or {@link Dns#getZone(String, ZoneOption...)}. - * The ID is always returned, even if not specified. + * {@link Dns#getZone(String, ZoneOption...)}. The ID is always returned, even if not specified. */ enum ZoneField { CREATION_TIME("creationTime"), @@ -105,9 +103,8 @@ static String selector(ZoneField... fields) { * The fields of a DNS record. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#listDnsRecords(BigInteger, DnsRecordListOption...)} or {@link - * Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if not - * selected. + * {@link Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if + * not selected. */ enum DnsRecordField { DNS_RECORDS("rrdatas"), @@ -139,8 +136,7 @@ static String selector(DnsRecordField... fields) { * The fields of a change request. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#applyChangeRequest(BigInteger, ChangeRequest, ChangeRequestOption...)} or {@link - * Dns#applyChangeRequest(String, ChangeRequest, ChangeRequestOption...)} The ID is always + * {@link Dns#applyChangeRequest(String, ChangeRequest, ChangeRequestOption...)} The ID is always * returned even if not selected. */ enum ChangeRequestField { @@ -444,16 +440,6 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { */ ZoneInfo getZone(String zoneName, ZoneOption... options); - /** - * Returns the zone by the specified zone id. Returns {@code null} if the zone is not found. The - * returned fields can be optionally restricted by specifying {@link ZoneOption}s. - * - * @throws DnsException upon failure - * @see Cloud DNS Managed Zones: - * get - */ - ZoneInfo getZone(BigInteger zoneId, ZoneOption... options); - /** * Lists the zones inside the project. * @@ -479,17 +465,6 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { */ boolean delete(String zoneName); // delete does not admit any options - /** - * Deletes an existing zone identified by id. Returns {@code true} if the zone was successfully - * deleted and {@code false} otherwise. - * - * @return {@code true} if zone was found and deleted and {@code false} otherwise - * @throws DnsException upon failure - * @see Cloud DNS Managed Zones: - * delete - */ - boolean delete(BigInteger zoneId); // delete does not admit any options - /** * Lists the DNS records in the zone identified by name. * @@ -502,18 +477,6 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { */ Page listDnsRecords(String zoneName, DnsRecordListOption... options); - /** - * Lists the DNS records in the zone identified by ID. - * - *

The fields to be returned, page size and page tokens can be specified using {@link - * DnsRecordListOption}s. - * - * @throws DnsException upon failure or if the zone cannot be found - * @see Cloud DNS - * ResourceRecordSets: list - */ - Page listDnsRecords(BigInteger zoneId, DnsRecordListOption... options); - /** * Retrieves the information about the current project. The returned fields can be optionally * restricted by specifying {@link ProjectOption}s. @@ -523,18 +486,6 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { */ ProjectInfo getProjectInfo(ProjectOption... fields); - /** - * Submits a change request for the specified zone. The returned object contains the following - * read-only fields supplied by the server: id, start time and status. time, id, and list of name - * servers. The fields to be returned can be selected by {@link ChangeRequestOption}s. - * - * @return the new {@link ChangeRequest} or {@code null} if zone is not found - * @throws DnsException upon failure - * @see Cloud DNS Changes: create - */ - ChangeRequest applyChangeRequest(BigInteger zoneId, ChangeRequest changeRequest, - ChangeRequestOption... options); - /** * Submits a change request for the specified zone. The returned object contains the following * read-only fields supplied by the server: id, start time and status. time, id, and list of name @@ -547,18 +498,6 @@ ChangeRequest applyChangeRequest(BigInteger zoneId, ChangeRequest changeRequest, ChangeRequest applyChangeRequest(String zoneName, ChangeRequest changeRequest, ChangeRequestOption... options); - /** - * Retrieves updated information about a change request previously submitted for a zone identified - * by ID. Returns {@code null} if the request cannot be found and throws an exception if the zone - * does not exist. The fields to be returned using can be specified using {@link - * ChangeRequestOption}s. - * - * @throws DnsException upon failure or if the zone cannot be found - * @see Cloud DNS Chages: get - */ - ChangeRequest getChangeRequest(BigInteger zoneId, String changeRequestId, - ChangeRequestOption... options); - /** * Retrieves updated information about a change request previously submitted for a zone identified * by ID. Returns {@code null} if the request cannot be found and throws an exception if the zone @@ -571,18 +510,6 @@ ChangeRequest getChangeRequest(BigInteger zoneId, String changeRequestId, ChangeRequest getChangeRequest(String zoneName, String changeRequestId, ChangeRequestOption... options); - /** - * Lists the change requests for the zone identified by ID that were submitted to the service. - * - *

The sorting order for changes (based on when they were received by the server), fields to be - * returned, page size and page token can be specified using {@link ChangeRequestListOption}s. - * - * @return A page of change requests - * @throws DnsException upon failure or if the zone cannot be found - * @see Cloud DNS Chages: list - */ - Page listChangeRequests(BigInteger zoneId, ChangeRequestListOption... options); - /** * Lists the change requests for the zone identified by name that were submitted to the service. * diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 86fc86bc3688..04edf332115d 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -16,13 +16,11 @@ package com.google.gcloud.dns; -import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.gcloud.Page; import java.io.Serializable; -import java.math.BigInteger; /** * A Google Cloud DNS Zone object. @@ -39,7 +37,7 @@ public class Zone implements Serializable { // TODO(mderka) Zone and zoneInfo to be merged. Opened issue #605. - private static final long serialVersionUID = -4012581571095484813L; + private static final long serialVersionUID = 6847890192129375500L; private final ZoneInfo zoneInfo; private final Dns dns; @@ -68,166 +66,81 @@ public static Zone get(Dns dnsService, String zoneName, Dns.ZoneOption... option } /** - * Constructs a {@code Zone} object that contains information received from the Google Cloud DNS - * service for the provided {@code zoneId}. - * - * @param zoneId ID of the zone to be searched for - * @param options optional restriction on what fields should be returned by the service - * @return zone object containing zone's information or {@code null} if not not found - * @throws DnsException upon failure - */ - public static Zone get(Dns dnsService, BigInteger zoneId, Dns.ZoneOption... options) { - checkNotNull(zoneId); - checkNotNull(dnsService); - ZoneInfo zoneInfo = dnsService.getZone(zoneId, options); - return zoneInfo == null ? null : new Zone(dnsService, zoneInfo); - } - - /** - * Retrieves the latest information about the zone. The method first attempts to retrieve the zone - * by ID and if not set or zone is not found, it searches by name. + * Retrieves the latest information about the zone. The method retrieves the zone by name which + * must always be initialized. * * @param options optional restriction on what fields should be fetched * @return zone object containing updated information or {@code null} if not not found * @throws DnsException upon failure - * @throws NullPointerException if both zone ID and name are not initialized */ public Zone reload(Dns.ZoneOption... options) { - checkNameOrIdNotNull(); - Zone zone = null; - if (zoneInfo.id() != null) { - zone = Zone.get(dns, zoneInfo.id(), options); - } - if (zone == null && zoneInfo.name() != null) { - // zone was not found by id or id is not set at all - zone = Zone.get(dns, zoneInfo.name(), options); - } - return zone; + return Zone.get(dns, zoneInfo.name(), options); } /** - * Deletes the zone. The method first attempts to delete the zone by ID. If the zone is not found - * or id is not set, it attempts to delete by name. + * Deletes the zone. The method first deletes the zone by name which must always be initialized. * * @return {@code true} is zone was found and deleted and {@code false} otherwise * @throws DnsException upon failure - * @throws NullPointerException if both zone ID and name are not initialized */ public boolean delete() { - checkNameOrIdNotNull(); - boolean deleted = false; - if (zoneInfo.id() != null) { - deleted = dns.delete(zoneInfo.id()); - } - if (!deleted && zoneInfo.name() != null) { - // zone was not found by id or id is not set at all - deleted = dns.delete(zoneInfo.name()); - } - return deleted; + return dns.delete(zoneInfo.name()); } /** - * Lists all {@link DnsRecord}s associated with this zone. First searches for zone by ID and if - * not found then by name. + * Lists all {@link DnsRecord}s associated with this zone. The method searches for zone by name + * which must always be initialized. * * @param options optional restriction on listing and fields of {@link DnsRecord}s returned * @return a page of DNS records * @throws DnsException upon failure or if the zone is not found - * @throws NullPointerException if both zone ID and name are not initialized */ public Page listDnsRecords(Dns.DnsRecordListOption... options) { - checkNameOrIdNotNull(); - Page page = null; - if (zoneInfo.id() != null) { - page = dns.listDnsRecords(zoneInfo.id(), options); - } - if (page == null && zoneInfo.name() != null) { - // zone was not found by id or id is not set at all - page = dns.listDnsRecords(zoneInfo.name(), options); - } - return page; + return dns.listDnsRecords(zoneInfo.name(), options); } /** - * Submits {@link ChangeRequest} to the service for it to applied to this zone. First searches for - * the zone by ID and if not found then by name. Returns a {@link ChangeRequest} with - * server-assigned ID or {@code null} if the zone was not found. + * Submits {@link ChangeRequest} to the service for it to applied to this zone. The method + * searches for zone by name which must always be initialized. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned * @return ChangeRequest with server-assigned ID * @throws DnsException upon failure or if the zone is not found - * @throws NullPointerException if both zone ID and name are not initialized */ public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, Dns.ChangeRequestOption... options) { - checkNameOrIdNotNull(); checkNotNull(changeRequest); - ChangeRequest updated = null; - if (zoneInfo.id() != null) { - updated = dns.applyChangeRequest(zoneInfo.id(), changeRequest, options); - } - if (updated == null && zoneInfo.name() != null) { - // zone was not found by id or id is not set at all - updated = dns.applyChangeRequest(zoneInfo.name(), changeRequest, options); - } - return updated; + return dns.applyChangeRequest(zoneInfo.name(), changeRequest, options); } /** * Retrieves an updated information about a change request previously submitted to be applied to - * this zone. First searches for the zone by ID and if not found then by name. Returns a {@link - * ChangeRequest} if found and {@code null} is the zone or the change request was not found. + * this zone. The method searches for zone by name which must always be initialized. Returns a + * {@link ChangeRequest} if and {@code null} if the change request was not found. Throws {@link + * DnsException} if the zone is not found. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned * @return updated ChangeRequest * @throws DnsException upon failure or if the zone is not found - * @throws NullPointerException if both zone ID and name are not initialized * @throws NullPointerException if the change request does not have initialized id */ public ChangeRequest getChangeRequest(String changeRequestId, Dns.ChangeRequestOption... options) { - checkNameOrIdNotNull(); checkNotNull(changeRequestId); - ChangeRequest updated = null; - if (zoneInfo.id() != null) { - updated = dns.getChangeRequest(zoneInfo.id(), changeRequestId, options); - } - if (updated == null && zoneInfo.name() != null) { - // zone was not found by id or id is not set at all - updated = dns.getChangeRequest(zoneInfo.name(), changeRequestId, options); - } - return updated; + return dns.getChangeRequest(zoneInfo.name(), changeRequestId, options); } /** - * Retrieves all change requests for this zone. First searches for the zone by ID and if not found - * then by name. Returns a page of {@link ChangeRequest}s or {@code null} if the zone is not - * found. + * Retrieves all change requests for this zone. The method searches for zone by name which must + * always be initialized. Returns a page of {@link ChangeRequest}s. Throws a {@link DnsException} + * if the zone is not found. * * @param options optional restriction on listing and fields to be returned * @return a page of change requests * @throws DnsException upon failure or if the zone is not found - * @throws NullPointerException if both zone ID and name are not initialized */ public Page listChangeRequests(Dns.ChangeRequestListOption... options) { - checkNameOrIdNotNull(); - Page changeRequests = null; - if (zoneInfo.id() != null) { - changeRequests = dns.listChangeRequests(zoneInfo.id(), options); - } - if (changeRequests == null && zoneInfo.name() != null) { - // zone was not found by id or id is not set at all - changeRequests = dns.listChangeRequests(zoneInfo.name(), options); - } - return changeRequests; - } - - /** - * Check that at least one of name and ID are initialized and throw and exception if not. - */ - private void checkNameOrIdNotNull() { - checkArgument(zoneInfo != null && (zoneInfo.id() != null || zoneInfo.name() != null), - "Both zoneInfo.id and zoneInfo.name are null. This is should never happen."); + return dns.listChangeRequests(zoneInfo.name(), options); } /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index 524309eaa8e9..09945fb72138 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -41,7 +41,7 @@ public class ZoneInfo implements Serializable { private static final long serialVersionUID = 201601191647L; private final String name; - private final BigInteger id; + private final String id; private final Long creationTimeMillis; private final String dnsName; private final String description; @@ -53,7 +53,7 @@ public class ZoneInfo implements Serializable { */ public static class Builder { private String name; - private BigInteger id; + private String id; private Long creationTimeMillis; private String dnsName; private String description; @@ -66,19 +66,10 @@ public static class Builder { private Builder() { } - private Builder(BigInteger id) { - this.id = checkNotNull(id); - } - private Builder(String name) { this.name = checkNotNull(name); } - private Builder(String name, BigInteger id) { - this.name = checkNotNull(name); - this.id = checkNotNull(id); - } - /** * Creates a builder from an existing ZoneInfo object. */ @@ -103,7 +94,7 @@ public Builder name(String name) { /** * Sets an id for the zone which is assigned to the zone by the server. */ - Builder id(BigInteger id) { + Builder id(String id) { this.id = id; return this; } @@ -178,20 +169,6 @@ public static Builder builder(String name) { return new Builder(name); } - /** - * Returns a builder for {@code ZoneInfo} with an assigned {@code id}. - */ - public static Builder builder(BigInteger id) { - return new Builder(id); - } - - /** - * Returns a builder for {@code ZoneInfo} with an assigned {@code name} and {@code id}. - */ - public static Builder builder(String name, BigInteger id) { - return new Builder(name, id); - } - /** * Returns the user-defined name of the zone. */ @@ -202,7 +179,7 @@ public String name() { /** * Returns the read-only zone id assigned by the server. */ - public BigInteger id() { + public String id() { return id; } @@ -255,7 +232,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { pb.setDescription(this.description()); pb.setDnsName(this.dnsName()); if (this.id() != null) { - pb.setId(this.id()); + pb.setId(new BigInteger(this.id())); } pb.setName(this.name()); pb.setNameServers(this.nameServers()); @@ -277,7 +254,7 @@ static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { builder.dnsName(pb.getDnsName()); } if (pb.getId() != null) { - builder.id(pb.getId()); + builder.id(pb.getId().toString()); } if (pb.getName() != null) { builder.name(pb.getName()); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index 73e6ab4036ec..12596da02bf6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -2,9 +2,9 @@ import static com.google.gcloud.spi.DnsRpc.ListResult.of; import static com.google.gcloud.spi.DnsRpc.Option.DNS_NAME; -import static com.google.gcloud.spi.DnsRpc.Option.NAME; import static com.google.gcloud.spi.DnsRpc.Option.DNS_TYPE; import static com.google.gcloud.spi.DnsRpc.Option.FIELDS; +import static com.google.gcloud.spi.DnsRpc.Option.NAME; import static com.google.gcloud.spi.DnsRpc.Option.PAGE_SIZE; import static com.google.gcloud.spi.DnsRpc.Option.PAGE_TOKEN; import static com.google.gcloud.spi.DnsRpc.Option.SORTING_ORDER; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java index 2c9fea8f7bde..227916b46f96 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java @@ -26,14 +26,13 @@ import org.junit.Test; -import java.math.BigInteger; import java.util.LinkedList; import java.util.List; public class ZoneInfoTest { private static final String NAME = "mz-example.com"; - private static final BigInteger ID = BigInteger.valueOf(123L); + private static final String ID = "123456"; private static final Long CREATION_TIME_MILLIS = 1123468321321L; private static final String DNS_NAME = "example.com."; private static final String DESCRIPTION = "description for the zone"; @@ -42,8 +41,9 @@ public class ZoneInfoTest { private static final String NS2 = "name server 2"; private static final String NS3 = "name server 3"; private static final List NAME_SERVERS = ImmutableList.of(NS1, NS2, NS3); - private static final ZoneInfo INFO = ZoneInfo.builder(NAME, ID) + private static final ZoneInfo INFO = ZoneInfo.builder(NAME) .creationTimeMillis(CREATION_TIME_MILLIS) + .id(ID) .dnsName(DNS_NAME) .description(DESCRIPTION) .nameServerSet(NAME_SERVER_SET) @@ -52,30 +52,14 @@ public class ZoneInfoTest { @Test public void testDefaultBuilders() { - ZoneInfo withName = ZoneInfo.builder(NAME).build(); - assertTrue(withName.nameServers().isEmpty()); - assertEquals(NAME, withName.name()); - assertNull(withName.id()); - assertNull(withName.creationTimeMillis()); - assertNull(withName.nameServerSet()); - assertNull(withName.description()); - assertNull(withName.dnsName()); - ZoneInfo withId = ZoneInfo.builder(ID).build(); - assertTrue(withId.nameServers().isEmpty()); - assertEquals(ID, withId.id()); - assertNull(withId.name()); - assertNull(withId.creationTimeMillis()); - assertNull(withId.nameServerSet()); - assertNull(withId.description()); - assertNull(withId.dnsName()); - ZoneInfo withBoth = ZoneInfo.builder(NAME, ID).build(); - assertTrue(withBoth.nameServers().isEmpty()); - assertEquals(ID, withBoth.id()); - assertEquals(NAME, withBoth.name()); - assertNull(withBoth.creationTimeMillis()); - assertNull(withBoth.nameServerSet()); - assertNull(withBoth.description()); - assertNull(withBoth.dnsName()); + ZoneInfo zone = ZoneInfo.builder(NAME).build(); + assertTrue(zone.nameServers().isEmpty()); + assertEquals(NAME, zone.name()); + assertNull(zone.id()); + assertNull(zone.creationTimeMillis()); + assertNull(zone.nameServerSet()); + assertNull(zone.description()); + assertNull(zone.dnsName()); } @Test @@ -109,7 +93,7 @@ public void testEqualsAndNotEquals() { assertNotEquals(INFO, clone); clone = INFO.toBuilder().dnsName(differentName).build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().id(INFO.id().add(BigInteger.ONE)).build(); + clone = INFO.toBuilder().id(INFO.id() + "1111").build(); assertNotEquals(INFO, clone); clone = INFO.toBuilder().nameServerSet(INFO.nameServerSet() + "salt").build(); assertNotEquals(INFO, clone); @@ -127,7 +111,7 @@ public void testToBuilder() { assertEquals(INFO, INFO.toBuilder().build()); ZoneInfo partial = ZoneInfo.builder(NAME).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.builder(ID).build(); + partial = ZoneInfo.builder(NAME).id(ID).build(); assertEquals(partial, partial.toBuilder().build()); partial = ZoneInfo.builder(NAME).description(DESCRIPTION).build(); assertEquals(partial, partial.toBuilder().build()); @@ -148,7 +132,7 @@ public void testToAndFromPb() { assertEquals(INFO, ZoneInfo.fromPb(INFO.toPb())); ZoneInfo partial = ZoneInfo.builder(NAME).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.builder(ID).build(); + partial = ZoneInfo.builder(NAME).id(ID).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); partial = ZoneInfo.builder(NAME).description(DESCRIPTION).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index c746140ce599..59cb642167ed 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -22,7 +22,6 @@ import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -35,24 +34,19 @@ import org.junit.Before; import org.junit.Test; -import java.math.BigInteger; - public class ZoneTest { private static final String ZONE_NAME = "dns-zone-name"; - private static final BigInteger ZONE_ID = new BigInteger("123"); - private static final ZoneInfo ZONE_INFO = ZoneInfo.builder(ZONE_NAME, ZONE_ID) + private static final String ZONE_ID = "123"; + private static final ZoneInfo ZONE_INFO = ZoneInfo.builder(ZONE_NAME) + .id(ZONE_ID) .dnsName("example.com") .creationTimeMillis(123478946464L) .build(); private static final ZoneInfo NO_ID_INFO = ZoneInfo.builder(ZONE_NAME) - .dnsName("anoter-example.com") + .dnsName("another-example.com") .creationTimeMillis(893123464L) .build(); - private static final ZoneInfo NO_NAME_INFO = ZoneInfo.builder(ZONE_ID) - .dnsName("one-more-example.com") - .creationTimeMillis(875221546464L) - .build(); private static final Dns.ZoneOption ZONE_FIELD_OPTIONS = Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); private static final Dns.DnsRecordListOption DNS_RECORD_OPTIONS = @@ -65,10 +59,10 @@ public class ZoneTest { private static final ChangeRequest CHANGE_REQUEST_AFTER = CHANGE_REQUEST.toBuilder() .startTimeMillis(123465L).build(); private static final ChangeRequest CHANGE_REQUEST_NO_ID = ChangeRequest.builder().build(); + private static final DnsException EXCEPTION = createStrictMock(DnsException.class); private Dns dns; private Zone zone; - private Zone zoneNoName; private Zone zoneNoId; @Before @@ -76,7 +70,6 @@ public void setUp() throws Exception { dns = createStrictMock(Dns.class); zone = new Zone(dns, ZONE_INFO); zoneNoId = new Zone(dns, NO_ID_INFO); - zoneNoName = new Zone(dns, NO_NAME_INFO); } @After @@ -93,40 +86,18 @@ public void testConstructor() { assertEquals(dns, zone.dns()); } - @Test - public void testGetById() { - expect(dns.getZone(ZONE_ID)).andReturn(ZONE_INFO); - expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(ZONE_INFO); // for options - replay(dns); - Zone retrieved = Zone.get(dns, ZONE_ID); - assertSame(dns, retrieved.dns()); - assertEquals(ZONE_INFO, retrieved.info()); - try { - Zone.get(dns, (BigInteger) null); - fail("Cannot get by null id."); - } catch (NullPointerException e) { - // expected - } - try { - Zone.get(null, new BigInteger("12")); - fail("Cannot get anything from null service."); - } catch (NullPointerException e) { - // expected - } - // test passing options - Zone.get(dns, ZONE_ID, ZONE_FIELD_OPTIONS); - } - @Test public void testGetByName() { expect(dns.getZone(ZONE_NAME)).andReturn(ZONE_INFO); - expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(ZONE_INFO); // for options + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(ZONE_INFO); // for options replay(dns); Zone retrieved = Zone.get(dns, ZONE_NAME); assertSame(dns, retrieved.dns()); assertEquals(ZONE_INFO, retrieved.info()); + // test passing options + Zone.get(dns, ZONE_NAME, ZONE_FIELD_OPTIONS); try { - Zone.get(dns, (String) null); + Zone.get(dns, null); fail("Cannot get by null name."); } catch (NullPointerException e) { // expected @@ -137,311 +108,177 @@ public void testGetByName() { } catch (NullPointerException e) { // expected } - // test passing options - Zone.get(dns, ZONE_ID, ZONE_FIELD_OPTIONS); } @Test - public void deleteByIdAndFound() { - expect(dns.delete(ZONE_ID)).andReturn(true); - replay(dns); - boolean result = zone.delete(); - assertTrue(result); - } - - @Test - public void deleteByIdAndNotFoundAndNameSetAndFound() { - expect(dns.delete(ZONE_ID)).andReturn(false); + public void deleteByNameAndFound() { + expect(dns.delete(ZONE_NAME)).andReturn(true); expect(dns.delete(ZONE_NAME)).andReturn(true); replay(dns); boolean result = zone.delete(); assertTrue(result); - } - - @Test - public void deleteByIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.delete(ZONE_ID)).andReturn(false); - expect(dns.delete(ZONE_NAME)).andReturn(false); - replay(dns); - boolean result = zone.delete(); - assertFalse(result); - } - - @Test - public void deleteByIdAndNotFoundAndNameNotSet() { - expect(dns.delete(ZONE_ID)).andReturn(false); - replay(dns); - boolean result = zoneNoName.delete(); - assertFalse(result); - } - - @Test - public void deleteByNameAndFound() { - expect(dns.delete(ZONE_NAME)).andReturn(true); - replay(dns); - boolean result = zoneNoId.delete(); + result = zoneNoId.delete(); assertTrue(result); } @Test public void deleteByNameAndNotFound() { - expect(dns.delete(ZONE_NAME)).andReturn(true); + expect(dns.delete(ZONE_NAME)).andReturn(false); + expect(dns.delete(ZONE_NAME)).andReturn(false); replay(dns); boolean result = zoneNoId.delete(); - assertTrue(result); - } - - @Test - public void listDnsRecordsByIdAndFound() { - @SuppressWarnings("unchecked") - Page pageMock = createStrictMock(Page.class); - replay(pageMock); - expect(dns.listDnsRecords(ZONE_ID)).andReturn(pageMock); - // again for options - expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(pageMock); - replay(dns); - Page result = zone.listDnsRecords(); - assertSame(pageMock, result); - verify(pageMock); - // verify options - zone.listDnsRecords(DNS_RECORD_OPTIONS); + assertFalse(result); + result = zone.delete(); + assertFalse(result); } @Test - public void listDnsRecordsByIdAndNotFoundAndNameSetAndFound() { + public void listDnsRecordsByNameAndFound() { @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); + expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); // again for options - expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(null); + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); replay(dns); Page result = zone.listDnsRecords(); assertSame(pageMock, result); - verify(pageMock); - // verify options - zone.listDnsRecords(DNS_RECORD_OPTIONS); - } - - @Test - public void listDnsRecordsByIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(null); - // again for options - expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(null); - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(null); - replay(dns); - Page result = zone.listDnsRecords(); - assertNull(result); - // check options - zone.listDnsRecords(DNS_RECORD_OPTIONS); - } - - @Test - public void listDnsRecordsByIdAndNotFoundAndNameNotSet() { - expect(dns.listDnsRecords(ZONE_ID)).andReturn(null); - expect(dns.listDnsRecords(ZONE_ID, DNS_RECORD_OPTIONS)).andReturn(null); // for options - replay(dns); - Page result = zoneNoName.listDnsRecords(); - assertNull(result); - zoneNoName.listDnsRecords(DNS_RECORD_OPTIONS); // check options - } - - @Test - public void listDnsRecordsByNameAndFound() { - @SuppressWarnings("unchecked") - Page pageMock = createStrictMock(Page.class); - replay(pageMock); - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); - // again for options - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); - replay(dns); - Page result = zoneNoId.listDnsRecords(); + result = zoneNoId.listDnsRecords(); assertSame(pageMock, result); verify(pageMock); + zone.listDnsRecords(DNS_RECORD_OPTIONS); // check options zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options } @Test public void listDnsRecordsByNameAndNotFound() { - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(null); - // again for options - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(null); - replay(dns); - Page result = zoneNoId.listDnsRecords(); - assertNull(result); - zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options - } - - @Test - public void reloadByIdAndFound() { - expect(dns.getZone(ZONE_ID)).andReturn(zone.info()); - expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(zone.info()); // for options - replay(dns); - Zone result = zone.reload(); - assertSame(zone.dns(), result.dns()); - assertEquals(zone.info(), result.info()); - zone.reload(ZONE_FIELD_OPTIONS); // for options - } - - @Test - public void reloadByIdAndNotFoundAndNameSetAndFound() { - expect(dns.getZone(ZONE_ID)).andReturn(null); - expect(dns.getZone(ZONE_NAME)).andReturn(zone.info()); - // again for options - expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(null); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone.info()); - replay(dns); - Zone result = zone.reload(); - assertSame(zone.dns(), result.dns()); - assertEquals(zone.info(), result.info()); - zone.reload(ZONE_FIELD_OPTIONS); // for options - } - - @Test - public void reloadByIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.getZone(ZONE_ID)).andReturn(null); - expect(dns.getZone(ZONE_NAME)).andReturn(null); - // again with options - expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(null); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); - replay(dns); - Zone result = zone.reload(); - assertNull(result); + expect(dns.listDnsRecords(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listDnsRecords(ZONE_NAME)).andThrow(EXCEPTION); // again for options - zone.reload(ZONE_FIELD_OPTIONS); - } - - @Test - public void reloadByIdAndNotFoundAndNameNotSet() { - expect(dns.getZone(ZONE_ID)).andReturn(null); - expect(dns.getZone(ZONE_ID, ZONE_FIELD_OPTIONS)).andReturn(null); // for options + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); replay(dns); - Zone result = zoneNoName.reload(); - assertNull(result); - zoneNoName.reload(ZONE_FIELD_OPTIONS); // for options + try { + zoneNoId.listDnsRecords(); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.listDnsRecords(); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.listDnsRecords(DNS_RECORD_OPTIONS); // check options + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } } @Test public void reloadByNameAndFound() { expect(dns.getZone(ZONE_NAME)).andReturn(zoneNoId.info()); + expect(dns.getZone(ZONE_NAME)).andReturn(zone.info()); // again for options expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zoneNoId.info()); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone.info()); replay(dns); Zone result = zoneNoId.reload(); assertSame(zoneNoId.dns(), result.dns()); assertEquals(zoneNoId.info(), result.info()); + result = zone.reload(); + assertSame(zone.dns(), result.dns()); + assertEquals(zone.info(), result.info()); zoneNoId.reload(ZONE_FIELD_OPTIONS); // check options + zone.reload(ZONE_FIELD_OPTIONS); // check options } @Test public void reloadByNameAndNotFound() { + expect(dns.getZone(ZONE_NAME)).andReturn(null); expect(dns.getZone(ZONE_NAME)).andReturn(null); // again for options expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); replay(dns); Zone result = zoneNoId.reload(); assertNull(result); + result = zone.reload(); + assertNull(result); zoneNoId.reload(ZONE_FIELD_OPTIONS); // for options + zone.reload(ZONE_FIELD_OPTIONS); // for options } @Test - public void applyChangeByIdAndFound() { - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(CHANGE_REQUEST_AFTER); - // again for options - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) + public void applyChangeByNameAndFound() { + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) .andReturn(CHANGE_REQUEST_AFTER); - replay(dns); - ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); - assertNotEquals(CHANGE_REQUEST, result); - assertEquals(CHANGE_REQUEST_AFTER, result); - // for options - result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertNotEquals(CHANGE_REQUEST, result); - assertEquals(CHANGE_REQUEST_AFTER, result); - } - - @Test - public void applyChangeByIdAndNotFoundAndNameSetAndFound() { - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(null); expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); - replay(dns); - ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); - assertNotEquals(CHANGE_REQUEST, result); - assertEquals(CHANGE_REQUEST_AFTER, result); - // for options - result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertNotEquals(CHANGE_REQUEST, result); - assertEquals(CHANGE_REQUEST_AFTER, result); - } - - @Test - public void applyChangeIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(null); - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andReturn(null); - // again with options - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); - replay(dns); - ChangeRequest result = zone.applyChangeRequest(CHANGE_REQUEST); - assertNull(result); - // again for options - result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertNull(result); - } - - @Test - public void applyChangeRequestByIdAndNotFoundAndNameNotSet() { - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST)).andReturn(null); - expect(dns.applyChangeRequest(ZONE_ID, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); // for options - replay(dns); - ChangeRequest result = zoneNoName.applyChangeRequest(CHANGE_REQUEST); - assertNull(result); - // again for options - result = zoneNoName.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertNull(result); - } - - @Test - public void applyChangeByNameAndFound() { - // ID is not set - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) - .andReturn(CHANGE_REQUEST_AFTER); - // again for options expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); assertEquals(CHANGE_REQUEST_AFTER, result); + result = zone.applyChangeRequest(CHANGE_REQUEST); + assertEquals(CHANGE_REQUEST_AFTER, result); // check options result = zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); assertEquals(CHANGE_REQUEST_AFTER, result); + result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + assertEquals(CHANGE_REQUEST_AFTER, result); } @Test public void applyChangeByNameAndNotFound() { // ID is not set - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andReturn(null); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION); // again for options expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); + .andThrow(EXCEPTION); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) + .andThrow(EXCEPTION); replay(dns); - ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); - assertNull(result); + try { + zoneNoId.applyChangeRequest(CHANGE_REQUEST); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.applyChangeRequest(CHANGE_REQUEST); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } // check options - result = zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertNull(result); + try { + zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } } @Test @@ -471,116 +308,82 @@ public void applyNullChangeRequest() { } catch (NullPointerException e) { // expected } - try { - zoneNoName.applyChangeRequest(null); - fail("Cannot apply null ChangeRequest."); - } catch (NullPointerException e) { - // expected - } - try { - zoneNoName.applyChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); - fail("Cannot apply null ChangeRequest."); - } catch (NullPointerException e) { - // expected - } } @Test - public void getChangeByIdAndFound() { - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(CHANGE_REQUEST_AFTER); - // again for options - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) + public void getChangeAndZoneFoundByName() { + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) .andReturn(CHANGE_REQUEST_AFTER); - replay(dns); - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); - assertNotEquals(CHANGE_REQUEST, result); - assertEquals(CHANGE_REQUEST_AFTER, result); - // for options - result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertNotEquals(CHANGE_REQUEST, result); - assertEquals(CHANGE_REQUEST_AFTER, result); - // test no id - } - - @Test - public void getChangeByIdAndNotFoundAndNameSetAndFound() { - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(null); expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) .andReturn(CHANGE_REQUEST_AFTER); // again for options - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(CHANGE_REQUEST_AFTER); expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(CHANGE_REQUEST_AFTER); replay(dns); - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); - assertNotEquals(CHANGE_REQUEST, result); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); assertEquals(CHANGE_REQUEST_AFTER, result); - // for options - result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertNotEquals(CHANGE_REQUEST, result); + result = zone.getChangeRequest(CHANGE_REQUEST.id()); + assertEquals(CHANGE_REQUEST_AFTER, result); + // check options + result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); assertEquals(CHANGE_REQUEST_AFTER, result); - } - - @Test - public void getChangeIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(null); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); - // again with options - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); - replay(dns); - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); - assertNull(result); - // again for options result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertNull(result); - } - - @Test - public void getChangeRequestByIdAndNotFoundAndNameNotSet() { - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id())).andReturn(null); - expect(dns.getChangeRequest(ZONE_ID, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); // for options - replay(dns); - ChangeRequest result = zoneNoName.getChangeRequest(CHANGE_REQUEST.id()); - assertNull(result); - // again for options - result = zoneNoName.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertNull(result); + assertEquals(CHANGE_REQUEST_AFTER, result); } @Test - public void getChangeByNameAndFound() { - // ID is not set - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(CHANGE_REQUEST_AFTER); + public void getChangeAndZoneNotFoundByName() { + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION); // again for options expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andThrow(EXCEPTION); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) + .andThrow(EXCEPTION); replay(dns); - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); - assertEquals(CHANGE_REQUEST_AFTER, result); + try { + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } // check options - result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + try { + zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } } @Test - public void getChangeByNameAndNotFound() { - // ID is not set + public void getChangedWhichDoesNotExistZoneFound() { + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); // again for options + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) + .andReturn(null); expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) .andReturn(null); replay(dns); - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); - assertNull(result); - // check options - result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertNull(result); + assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.id())); + assertNull(zone.getChangeRequest(CHANGE_REQUEST.id())); + assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)); + assertNull(zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)); } @Test @@ -610,18 +413,6 @@ public void getNullChangeRequest() { } catch (NullPointerException e) { // expected } - try { - zoneNoName.getChangeRequest(null); - fail("Cannot get null ChangeRequest."); - } catch (NullPointerException e) { - // expected - } - try { - zoneNoName.getChangeRequest(null, CHANGE_REQUEST_FIELD_OPTIONS); - fail("Cannot get null ChangeRequest."); - } catch (NullPointerException e) { - // expected - } } @Test @@ -651,104 +442,61 @@ public void getChangeRequestWithNoId() { } catch (NullPointerException e) { // expected } - try { - zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID.id()); - fail("Cannot get ChangeRequest by null id."); - } catch (NullPointerException e) { - // expected - } - try { - zoneNoName.getChangeRequest(CHANGE_REQUEST_NO_ID.id(), CHANGE_REQUEST_FIELD_OPTIONS); - fail("Cannot get ChangeRequest by null id."); - } catch (NullPointerException e) { - // expected - } - } - - @Test - public void listChangeRequestsByIdAndFound() { - @SuppressWarnings("unchecked") - Page pageMock = createStrictMock(Page.class); - replay(pageMock); - expect(dns.listChangeRequests(ZONE_ID)).andReturn(pageMock); - // again for options - expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(pageMock); - replay(dns); - Page result = zone.listChangeRequests(); - assertSame(pageMock, result); - verify(pageMock); - // verify options - zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); } @Test - public void listChangeRequestsByIdAndNotFoundAndNameSetAndFound() { + public void listChangeRequestsAndZoneFound() { @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); // again for options - expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) .andReturn(pageMock); - replay(dns); - Page result = zone.listChangeRequests(); - assertSame(pageMock, result); - verify(pageMock); - // verify options - zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); - } - - @Test - public void listChangeRequestsByIdAndNotFoundAndNameSetAndNotFound() { - expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(null); - // again for options - expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); - replay(dns); - Page result = zone.listChangeRequests(); - assertNull(result); - // check options - zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); - } - - @Test - public void listChangeRequestsByIdAndNotFoundAndNameNotSet() { - expect(dns.listChangeRequests(ZONE_ID)).andReturn(null); - // again for options - expect(dns.listChangeRequests(ZONE_ID, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); - replay(dns); - Page result = zoneNoName.listChangeRequests(); - assertNull(result); - zoneNoName.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options - } - - @Test - public void listChangeRequestsByNameAndFound() { - @SuppressWarnings("unchecked") - Page pageMock = createStrictMock(Page.class); - replay(pageMock); - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); - // again for options expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) .andReturn(pageMock); replay(dns); Page result = zoneNoId.listChangeRequests(); assertSame(pageMock, result); + result = zone.listChangeRequests(); + assertSame(pageMock, result); verify(pageMock); zoneNoId.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options } @Test - public void listChangeRequestsByNameAndNotFound() { - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(null); + public void listChangeRequestsAndZoneNotFound() { + expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION); // again for options - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andReturn(null); + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION); replay(dns); - Page result = zoneNoId.listChangeRequests(); - assertNull(result); - zoneNoId.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + try { + zoneNoId.listChangeRequests(); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.listChangeRequests(); + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zoneNoId.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } + try { + zone.listChangeRequests(CHANGE_REQUEST_LIST_OPTIONS); // check options + fail("Parent container not found, should throw an exception."); + } catch (DnsException e) { + // expected + } } } From 3183f4a7445dcb5e8992132ec5463bbced65c07b Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 4 Feb 2016 14:04:45 -0800 Subject: [PATCH 42/74] Added field options for zone create method. --- .../src/main/java/com/google/gcloud/dns/Dns.java | 7 ++++--- .../src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java | 7 +++++-- .../src/main/java/com/google/gcloud/spi/DnsRpc.java | 3 ++- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index af0868ec17d6..f6649c28680c 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -421,14 +421,15 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { * *

Returns {@link ZoneInfo} object representing the new zone's information. In addition to the * name, dns name and description (supplied by the user within the {@code zoneInfo} parameter), - * the returned object will include the following read-only fields supplied by the server: - * creation time, id, and list of name servers. + * the returned object can include the following read-only fields supplied by the server: creation + * time, id, and list of name servers. The returned fields can be optionally restricted by + * specifying {@link ZoneOption}s. * * @throws DnsException upon failure * @see Cloud DNS Managed Zones: * create */ - ZoneInfo create(ZoneInfo zoneInfo); + ZoneInfo create(ZoneInfo zoneInfo, ZoneOption... options); /** * Returns the zone by the specified zone name. Returns {@code null} if the zone is not found. The diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index 12596da02bf6..6ed9c7e0f216 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -54,9 +54,12 @@ public DefaultDnsRpc(DnsOptions options) { } @Override - public ManagedZone create(ManagedZone zone) throws DnsException { + public ManagedZone create(ManagedZone zone, Map options) throws DnsException { try { - return dns.managedZones().create(this.options.projectId(), zone).execute(); + return dns.managedZones() + .create(this.options.projectId(), zone) + .setFields(FIELDS.getString(options)) + .execute(); } catch (IOException ex) { throw translate(ex); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java index c3cd3c690177..addb69d24b40 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java @@ -87,10 +87,11 @@ public String pageToken() { * Creates a new zone. * * @param zone a zone to be created + * @param options a map of options for the service call * @return Updated {@code ManagedZone} object * @throws DnsException upon failure */ - ManagedZone create(ManagedZone zone) throws DnsException; + ManagedZone create(ManagedZone zone, Map options) throws DnsException; /** * Retrieves and returns an existing zone. From 4057dcd93d2dee27c0a7f51e51723ca414daa5fd Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 4 Feb 2016 18:19:27 -0800 Subject: [PATCH 43/74] Fixed doc after refactoring. Made zone name mandatory in fields. --- .../src/main/java/com/google/gcloud/dns/Dns.java | 4 ++-- .../src/main/java/com/google/gcloud/dns/Zone.java | 15 ++++++--------- .../main/java/com/google/gcloud/dns/ZoneInfo.java | 11 +---------- .../test/java/com/google/gcloud/dns/DnsTest.java | 2 +- 4 files changed, 10 insertions(+), 22 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index f6649c28680c..040a97e5b253 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -68,7 +68,7 @@ static String selector(ProjectField... fields) { * The fields of a zone. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#getZone(String, ZoneOption...)}. The ID is always returned, even if not specified. + * {@link Dns#getZone(String, ZoneOption...)}. The name is always returned, even if not specified. */ enum ZoneField { CREATION_TIME("creationTime"), @@ -91,7 +91,7 @@ String selector() { static String selector(ZoneField... fields) { Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); - fieldStrings.add(ZONE_ID.selector()); + fieldStrings.add(NAME.selector()); for (ZoneField field : fields) { fieldStrings.add(field.selector()); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 04edf332115d..f5e0a8b4a63b 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -78,7 +78,7 @@ public Zone reload(Dns.ZoneOption... options) { } /** - * Deletes the zone. The method first deletes the zone by name which must always be initialized. + * Deletes the zone. The method deletes the zone by name. * * @return {@code true} is zone was found and deleted and {@code false} otherwise * @throws DnsException upon failure @@ -88,8 +88,7 @@ public boolean delete() { } /** - * Lists all {@link DnsRecord}s associated with this zone. The method searches for zone by name - * which must always be initialized. + * Lists all {@link DnsRecord}s associated with this zone. The method searches for zone by name. * * @param options optional restriction on listing and fields of {@link DnsRecord}s returned * @return a page of DNS records @@ -115,14 +114,13 @@ public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, /** * Retrieves an updated information about a change request previously submitted to be applied to - * this zone. The method searches for zone by name which must always be initialized. Returns a - * {@link ChangeRequest} if and {@code null} if the change request was not found. Throws {@link - * DnsException} if the zone is not found. + * this zone. Returns a {@link ChangeRequest} or {@code null} if the change request was not + * found. Throws {@link DnsException} if the zone is not found. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned * @return updated ChangeRequest * @throws DnsException upon failure or if the zone is not found - * @throws NullPointerException if the change request does not have initialized id + * @throws NullPointerException if {@code changeRequestId} is null */ public ChangeRequest getChangeRequest(String changeRequestId, Dns.ChangeRequestOption... options) { @@ -132,8 +130,7 @@ public ChangeRequest getChangeRequest(String changeRequestId, /** * Retrieves all change requests for this zone. The method searches for zone by name which must - * always be initialized. Returns a page of {@link ChangeRequest}s. Throws a {@link DnsException} - * if the zone is not found. + * always be initialized. Returns a page of {@link ChangeRequest}s. * * @param options optional restriction on listing and fields to be returned * @return a page of change requests diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index 09945fb72138..a15518ae166f 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -60,12 +60,6 @@ public static class Builder { private String nameServerSet; private List nameServers = new LinkedList<>(); - /** - * Returns an empty builder for {@code ZoneInfo}. We use it internally in {@code toPb()}. - */ - private Builder() { - } - private Builder(String name) { this.name = checkNotNull(name); } @@ -246,7 +240,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { } static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { - Builder builder = new Builder(); + Builder builder = new Builder(pb.getName()); if (pb.getDescription() != null) { builder.description(pb.getDescription()); } @@ -256,9 +250,6 @@ static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { if (pb.getId() != null) { builder.id(pb.getId().toString()); } - if (pb.getName() != null) { - builder.name(pb.getName()); - } if (pb.getNameServers() != null) { builder.nameServers(pb.getNameServers()); } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index c2be251cea9e..74faca329884 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -80,7 +80,7 @@ public void testZoneList() { assertTrue(fields.value() instanceof String); assertTrue(((String) fields.value()).contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(((String) fields.value()).contains(Dns.ZoneField.DESCRIPTION.selector())); - assertTrue(((String) fields.value()).contains(Dns.ZoneField.ZONE_ID.selector())); + assertTrue(((String) fields.value()).contains(Dns.ZoneField.NAME.selector())); // page token Dns.ZoneListOption option = Dns.ZoneListOption.pageToken(PAGE_TOKEN); assertEquals(PAGE_TOKEN, option.value()); From d7226350faa112b2f2e5310e7268ba61176729ee Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 5 Feb 2016 08:45:53 -0800 Subject: [PATCH 44/74] Javadoc fixed. --- .../src/main/java/com/google/gcloud/dns/Zone.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index f5e0a8b4a63b..3f4ea8cab3e4 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -66,8 +66,7 @@ public static Zone get(Dns dnsService, String zoneName, Dns.ZoneOption... option } /** - * Retrieves the latest information about the zone. The method retrieves the zone by name which - * must always be initialized. + * Retrieves the latest information about the zone. The method retrieves the zone by name. * * @param options optional restriction on what fields should be fetched * @return zone object containing updated information or {@code null} if not not found @@ -100,7 +99,7 @@ public Page listDnsRecords(Dns.DnsRecordListOption... options) { /** * Submits {@link ChangeRequest} to the service for it to applied to this zone. The method - * searches for zone by name which must always be initialized. + * searches for zone by name. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned * @return ChangeRequest with server-assigned ID @@ -114,8 +113,8 @@ public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, /** * Retrieves an updated information about a change request previously submitted to be applied to - * this zone. Returns a {@link ChangeRequest} or {@code null} if the change request was not - * found. Throws {@link DnsException} if the zone is not found. + * this zone. Returns a {@link ChangeRequest} or {@code null} if the change request was not found. + * Throws {@link DnsException} if the zone is not found. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned * @return updated ChangeRequest @@ -129,8 +128,8 @@ public ChangeRequest getChangeRequest(String changeRequestId, } /** - * Retrieves all change requests for this zone. The method searches for zone by name which must - * always be initialized. Returns a page of {@link ChangeRequest}s. + * Retrieves all change requests for this zone. The method searches for zone by name. Returns a + * page of {@link ChangeRequest}s. * * @param options optional restriction on listing and fields to be returned * @return a page of change requests From 5be58b3e91cade1d349014122484a29e254ba8f3 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Sun, 7 Feb 2016 14:01:52 -0800 Subject: [PATCH 45/74] Makes Zone subclass of ZoneInfo. Fixes #605. --- .../main/java/com/google/gcloud/dns/Dns.java | 2 +- .../main/java/com/google/gcloud/dns/Zone.java | 121 ++++++++++++++---- .../java/com/google/gcloud/dns/ZoneInfo.java | 98 ++++++++------ .../java/com/google/gcloud/dns/ZoneTest.java | 61 +++++++-- 4 files changed, 209 insertions(+), 73 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 040a97e5b253..3ea505b5e09b 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -439,7 +439,7 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { * @see Cloud DNS Managed Zones: * get */ - ZoneInfo getZone(String zoneName, ZoneOption... options); + Zone getZone(String zoneName, ZoneOption... options); /** * Lists the zones inside the project. diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 3f4ea8cab3e4..2da67a8e9a01 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -20,7 +20,8 @@ import com.google.gcloud.Page; -import java.io.Serializable; +import java.util.List; +import java.util.Objects; /** * A Google Cloud DNS Zone object. @@ -33,20 +34,87 @@ * @see Google Cloud DNS managed zone * documentation */ -public class Zone implements Serializable { +public class Zone extends ZoneInfo { - // TODO(mderka) Zone and zoneInfo to be merged. Opened issue #605. + private static final long serialVersionUID = 564454483894599281L; + private transient Dns dns; - private static final long serialVersionUID = 6847890192129375500L; - private final ZoneInfo zoneInfo; - private final Dns dns; + /** + * Builder for {@code Zone}. + */ + public static class Builder extends ZoneInfo.Builder { + private final Dns dns; + private final ZoneInfo.BuilderImpl infoBuilder; + + private Builder(Zone zone) { + this.dns = zone.dns; + this.infoBuilder = new ZoneInfo.BuilderImpl(zone); + } + + @Override + public Builder name(String name) { + infoBuilder.name(name); + return this; + } + + @Override + Builder id(String id) { + infoBuilder.id(id); + return this; + } + + @Override + Builder creationTimeMillis(long creationTimeMillis) { + infoBuilder.creationTimeMillis(creationTimeMillis); + return this; + } + + @Override + public Builder dnsName(String dnsName) { + infoBuilder.dnsName(dnsName); + return this; + } + + @Override + public Builder description(String description) { + infoBuilder.description(description); + return this; + } + + @Override + public Builder nameServerSet(String nameServerSet) { + infoBuilder.nameServerSet(nameServerSet); + return this; + } + + @Override + Builder nameServers(List nameServers) { + infoBuilder.nameServers(nameServers); // infoBuilder makes a copy + return this; + } + + @Override + public Zone build() { + return new Zone(dns, infoBuilder); + } + } + + Zone(Dns dns, ZoneInfo.BuilderImpl infoBuilder) { + super(infoBuilder); + this.dns = dns; + } + + @Override + public Builder toBuilder() { + return new Builder(this); + } /** * Constructs a {@code Zone} object that contains the given {@code zoneInfo}. */ public Zone(Dns dns, ZoneInfo zoneInfo) { - this.zoneInfo = checkNotNull(zoneInfo); - this.dns = checkNotNull(dns); + super(new BuilderImpl(zoneInfo)); + this.dns = dns; } /** @@ -61,8 +129,7 @@ public Zone(Dns dns, ZoneInfo zoneInfo) { public static Zone get(Dns dnsService, String zoneName, Dns.ZoneOption... options) { checkNotNull(zoneName); checkNotNull(dnsService); - ZoneInfo zoneInfo = dnsService.getZone(zoneName, options); - return zoneInfo == null ? null : new Zone(dnsService, zoneInfo); + return dnsService.getZone(zoneName, options); } /** @@ -73,7 +140,7 @@ public static Zone get(Dns dnsService, String zoneName, Dns.ZoneOption... option * @throws DnsException upon failure */ public Zone reload(Dns.ZoneOption... options) { - return Zone.get(dns, zoneInfo.name(), options); + return dns.getZone(name(), options); } /** @@ -83,7 +150,7 @@ public Zone reload(Dns.ZoneOption... options) { * @throws DnsException upon failure */ public boolean delete() { - return dns.delete(zoneInfo.name()); + return dns.delete(name()); } /** @@ -94,7 +161,7 @@ public boolean delete() { * @throws DnsException upon failure or if the zone is not found */ public Page listDnsRecords(Dns.DnsRecordListOption... options) { - return dns.listDnsRecords(zoneInfo.name(), options); + return dns.listDnsRecords(name(), options); } /** @@ -108,7 +175,7 @@ public Page listDnsRecords(Dns.DnsRecordListOption... options) { public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, Dns.ChangeRequestOption... options) { checkNotNull(changeRequest); - return dns.applyChangeRequest(zoneInfo.name(), changeRequest, options); + return dns.applyChangeRequest(name(), changeRequest, options); } /** @@ -124,7 +191,7 @@ public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, public ChangeRequest getChangeRequest(String changeRequestId, Dns.ChangeRequestOption... options) { checkNotNull(changeRequestId); - return dns.getChangeRequest(zoneInfo.name(), changeRequestId, options); + return dns.getChangeRequest(name(), changeRequestId, options); } /** @@ -136,14 +203,7 @@ public ChangeRequest getChangeRequest(String changeRequestId, * @throws DnsException upon failure or if the zone is not found */ public Page listChangeRequests(Dns.ChangeRequestListOption... options) { - return dns.listChangeRequests(zoneInfo.name(), options); - } - - /** - * Returns the {@link ZoneInfo} object containing information about this zone. - */ - public ZoneInfo info() { - return zoneInfo; + return dns.listChangeRequests(name(), options); } /** @@ -152,4 +212,19 @@ public ZoneInfo info() { public Dns dns() { return this.dns; } + + @Override + public boolean equals(Object obj) { + return obj instanceof Zone && Objects.equals(toPb(), ((Zone) obj).toPb()); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + static Zone fromPb(Dns dns, com.google.api.services.dns.model.ManagedZone zone) { + ZoneInfo info = ZoneInfo.fromPb(zone); + return new Zone(dns, info); + } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index a15518ae166f..e397e37a7fbf 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -49,9 +49,55 @@ public class ZoneInfo implements Serializable { private final List nameServers; /** - * A builder for {@code ZoneInfo}. + * Builder for {@code ZoneInfo}. */ - public static class Builder { + public abstract static class Builder { + /** + * Sets a mandatory user-provided name for the zone. It must be unique within the project. + */ + public abstract Builder name(String name); + + /** + * Sets an id for the zone which is assigned to the zone by the server. + */ + abstract Builder id(String id); + + /** + * Sets the time when this zone was created. + */ + abstract Builder creationTimeMillis(long creationTimeMillis); + + /** + * Sets a mandatory DNS name of this zone, for instance "example.com.". + */ + public abstract Builder dnsName(String dnsName); + + /** + * Sets a mandatory description for this zone. The value is a string of at most 1024 characters + * which has no effect on the zone's function. + */ + public abstract Builder description(String description); + + /** + * Optionally specifies the NameServerSet for this zone. A NameServerSet is a set of DNS name + * servers that all host the same zones. Most users will not need to specify this value. + */ + public abstract Builder nameServerSet(String nameServerSet); + // todo(mderka) add more to the doc when questions are answered by the service owner + + /** + * Sets a list of servers that hold the information about the zone. This information is provided + * by Google Cloud DNS and is read only. + */ + abstract Builder nameServers(List nameServers); + + /** + * Builds the instance of {@code ZoneInfo} based on the information set by this builder. + */ + public abstract ZoneInfo build(); + } + + public static class BuilderImpl extends Builder { private String name; private String id; private Long creationTimeMillis; @@ -60,14 +106,14 @@ public static class Builder { private String nameServerSet; private List nameServers = new LinkedList<>(); - private Builder(String name) { + private BuilderImpl(String name) { this.name = checkNotNull(name); } /** * Creates a builder from an existing ZoneInfo object. */ - Builder(ZoneInfo info) { + BuilderImpl(ZoneInfo info) { this.name = info.name; this.id = info.id; this.creationTimeMillis = info.creationTimeMillis; @@ -77,76 +123,56 @@ private Builder(String name) { this.nameServers.addAll(info.nameServers); } - /** - * Sets a mandatory user-provided name for the zone. It must be unique within the project. - */ + @Override public Builder name(String name) { this.name = checkNotNull(name); return this; } - /** - * Sets an id for the zone which is assigned to the zone by the server. - */ + @Override Builder id(String id) { this.id = id; return this; } - /** - * Sets the time when this zone was created. - */ + @Override Builder creationTimeMillis(long creationTimeMillis) { this.creationTimeMillis = creationTimeMillis; return this; } - /** - * Sets a mandatory DNS name of this zone, for instance "example.com.". - */ + @Override public Builder dnsName(String dnsName) { this.dnsName = checkNotNull(dnsName); return this; } - /** - * Sets a mandatory description for this zone. The value is a string of at most 1024 characters - * which has no effect on the zone's function. - */ + @Override public Builder description(String description) { this.description = checkNotNull(description); return this; } - /** - * Optionally specifies the NameServerSet for this zone. A NameServerSet is a set of DNS name - * servers that all host the same zones. Most users will not need to specify this value. - */ + @Override public Builder nameServerSet(String nameServerSet) { - // todo(mderka) add more to the doc when questions are answered by the service owner this.nameServerSet = checkNotNull(nameServerSet); return this; } - /** - * Sets a list of servers that hold the information about the zone. This information is provided - * by Google Cloud DNS and is read only. - */ + @Override Builder nameServers(List nameServers) { checkNotNull(nameServers); this.nameServers = Lists.newLinkedList(nameServers); return this; } - /** - * Builds the instance of {@code ZoneInfo} based on the information set by this builder. - */ + @Override public ZoneInfo build() { return new ZoneInfo(this); } } - private ZoneInfo(Builder builder) { + ZoneInfo(BuilderImpl builder) { this.name = builder.name; this.id = builder.id; this.creationTimeMillis = builder.creationTimeMillis; @@ -160,7 +186,7 @@ private ZoneInfo(Builder builder) { * Returns a builder for {@code ZoneInfo} with an assigned {@code name}. */ public static Builder builder(String name) { - return new Builder(name); + return new BuilderImpl(name); } /** @@ -217,7 +243,7 @@ public List nameServers() { * Returns a builder for {@code ZoneInfo} prepopulated with the metadata of this zone. */ public Builder toBuilder() { - return new Builder(this); + return new BuilderImpl(this); } com.google.api.services.dns.model.ManagedZone toPb() { @@ -240,7 +266,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { } static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { - Builder builder = new Builder(pb.getName()); + Builder builder = new BuilderImpl(pb.getName()); if (pb.getDescription() != null) { builder.description(pb.getDescription()); } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 59cb642167ed..1b09dca715a4 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -22,23 +22,27 @@ import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.google.common.collect.ImmutableList; import com.google.gcloud.Page; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.math.BigInteger; + public class ZoneTest { private static final String ZONE_NAME = "dns-zone-name"; private static final String ZONE_ID = "123"; - private static final ZoneInfo ZONE_INFO = ZoneInfo.builder(ZONE_NAME) + private static final ZoneInfo ZONE_INFO = Zone.builder(ZONE_NAME) .id(ZONE_ID) .dnsName("example.com") .creationTimeMillis(123478946464L) @@ -80,20 +84,19 @@ public void tearDown() throws Exception { @Test public void testConstructor() { replay(dns); - assertNotNull(zone.info()); - assertEquals(ZONE_INFO, zone.info()); + assertEquals(ZONE_INFO.toPb(), zone.toPb()); assertNotNull(zone.dns()); assertEquals(dns, zone.dns()); } @Test public void testGetByName() { - expect(dns.getZone(ZONE_NAME)).andReturn(ZONE_INFO); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(ZONE_INFO); // for options + expect(dns.getZone(ZONE_NAME)).andReturn(zone); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone); // for options replay(dns); Zone retrieved = Zone.get(dns, ZONE_NAME); assertSame(dns, retrieved.dns()); - assertEquals(ZONE_INFO, retrieved.info()); + assertEquals(zone, retrieved); // test passing options Zone.get(dns, ZONE_NAME, ZONE_FIELD_OPTIONS); try { @@ -188,18 +191,18 @@ public void listDnsRecordsByNameAndNotFound() { @Test public void reloadByNameAndFound() { - expect(dns.getZone(ZONE_NAME)).andReturn(zoneNoId.info()); - expect(dns.getZone(ZONE_NAME)).andReturn(zone.info()); + expect(dns.getZone(ZONE_NAME)).andReturn(zone); + expect(dns.getZone(ZONE_NAME)).andReturn(zone); // again for options - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zoneNoId.info()); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone.info()); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zoneNoId); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone); replay(dns); Zone result = zoneNoId.reload(); - assertSame(zoneNoId.dns(), result.dns()); - assertEquals(zoneNoId.info(), result.info()); + assertSame(zone.dns(), result.dns()); + assertEquals(zone, result); result = zone.reload(); assertSame(zone.dns(), result.dns()); - assertEquals(zone.info(), result.info()); + assertEquals(zone, result); zoneNoId.reload(ZONE_FIELD_OPTIONS); // check options zone.reload(ZONE_FIELD_OPTIONS); // check options } @@ -499,4 +502,36 @@ public void listChangeRequestsAndZoneNotFound() { // expected } } + + @Test + public void testFromPb() { + replay(dns); + assertEquals(Zone.fromPb(dns, zone.toPb()), zone); + } + + @Test + public void testEqualsAndToBuilder() { + replay(dns); + assertEquals(zone, zone.toBuilder().build()); + } + + @Test + public void testBuilder() { + replay(dns); + assertNotEquals(zone, zone.toBuilder() + .id((new BigInteger(zone.id())).add(BigInteger.ONE).toString()) + .build()); + assertNotEquals(zone, zone.toBuilder().dnsName(zone.name() + "aaaa").build()); + assertNotEquals(zone, zone.toBuilder().nameServerSet(zone.nameServerSet() + "aaaa").build()); + assertNotEquals(zone, zone.toBuilder().nameServers(ImmutableList.of("nameserverpppp")).build()); + assertNotEquals(zone, zone.toBuilder().dnsName(zone.dnsName() + "aaaa").build()); + assertNotEquals(zone, zone.toBuilder().creationTimeMillis(zone.creationTimeMillis() + 1) + .build()); + Zone.Builder builder = zone.toBuilder(); + builder.id(ZONE_ID) + .dnsName("example.com") + .creationTimeMillis(123478946464L) + .build(); + assertEquals(zone, builder.build()); + } } From d1c45124dffd0a5a3bfdc2a4abe5c6483f32c295 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Sun, 7 Feb 2016 10:32:02 -0800 Subject: [PATCH 46/74] Added implementation of Dns and test. Renamed getProjectInfo. Fixed #619. --- .../main/java/com/google/gcloud/dns/Dns.java | 6 +- .../com/google/gcloud/dns/DnsException.java | 18 + .../java/com/google/gcloud/dns/DnsImpl.java | 335 ++++++++++++++++ .../com/google/gcloud/dns/DnsOptions.java | 2 +- .../com/google/gcloud/dns/DnsImplTest.java | 370 ++++++++++++++++++ 5 files changed, 727 insertions(+), 4 deletions(-) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 3ea505b5e09b..88e0d7a08591 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -36,7 +36,7 @@ public interface Dns extends Service { * The fields of a project. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#getProjectInfo(ProjectOption...)}. Project ID is always returned, even if not + * {@link Dns#getProject(ProjectOption...)}. Project ID is always returned, even if not * specified. */ enum ProjectField { @@ -429,7 +429,7 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { * @see Cloud DNS Managed Zones: * create */ - ZoneInfo create(ZoneInfo zoneInfo, ZoneOption... options); + Zone create(ZoneInfo zoneInfo, ZoneOption... options); /** * Returns the zone by the specified zone name. Returns {@code null} if the zone is not found. The @@ -485,7 +485,7 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { * @throws DnsException upon failure * @see Cloud DNS Projects: get */ - ProjectInfo getProjectInfo(ProjectOption... fields); + ProjectInfo getProject(ProjectOption... fields); /** * Submits a change request for the specified zone. The returned object contains the following diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java index 73c546759260..2092d5909d37 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java @@ -17,6 +17,8 @@ package com.google.gcloud.dns; import com.google.gcloud.BaseServiceException; +import com.google.gcloud.RetryHelper.RetryHelperException; +import com.google.gcloud.RetryHelper.RetryInterruptedException; import java.io.IOException; @@ -31,5 +33,21 @@ public DnsException(IOException exception) { super(exception, true); } + public DnsException(int code, String message) { + super(code, message, null, true); + } + + /** + * Translate RetryHelperException to the DnsException that caused the error. This method will + * always throw an exception. + * + * @throws DnsException when {@code ex} was caused by a {@code DnsException} + * @throws RetryInterruptedException when {@code ex} is a {@code RetryInterruptedException} + */ + static DnsException translateAndThrow(RetryHelperException ex) { + BaseServiceException.translateAndPropagateIfPossible(ex); + throw new DnsException(UNKNOWN_CODE, ex.getMessage()); + } + //TODO(mderka) Add translation and retry functionality. Created issue #593. } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java new file mode 100644 index 000000000000..b3ae73fd7e93 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -0,0 +1,335 @@ +/* + * 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.dns; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.gcloud.RetryHelper.RetryHelperException; +import static com.google.gcloud.RetryHelper.runWithRetries; +import static com.google.gcloud.dns.ChangeRequest.fromPb; + +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; +import com.google.gcloud.BaseService; +import com.google.gcloud.Page; +import com.google.gcloud.PageImpl; +import com.google.gcloud.RetryHelper; +import com.google.gcloud.spi.DnsRpc; + +import java.util.Map; +import java.util.concurrent.Callable; + +/** + * A default implementation of Dns. + */ +final class DnsImpl extends BaseService implements Dns { + + private final DnsRpc dnsRpc; + + private static class ZonePageFetcher implements PageImpl.NextPageFetcher { + + private static final long serialVersionUID = 2158209410430566961L; + private final Map requestOptions; + private final DnsOptions serviceOptions; + + ZonePageFetcher(DnsOptions serviceOptions, String cursor, + Map optionMap) { + this.requestOptions = + PageImpl.nextRequestOptions(DnsRpc.Option.PAGE_TOKEN, cursor, optionMap); + this.serviceOptions = serviceOptions; + } + + @Override + public Page nextPage() { + return listZones(serviceOptions, requestOptions); + } + } + + private static class ChangeRequestPageFetcher implements PageImpl.NextPageFetcher { + + private static final Function PB_TO_CHANGE_REQUEST = + new Function() { + @Override + public ChangeRequest apply(com.google.api.services.dns.model.Change changePb) { + return fromPb(changePb); + } + }; + private static final long serialVersionUID = -8737501076674042014L; + private final String zoneName; + private final Map requestOptions; + private final DnsOptions serviceOptions; + + ChangeRequestPageFetcher(String zoneName, DnsOptions serviceOptions, String cursor, + Map optionMap) { + this.zoneName = zoneName; + this.requestOptions = + PageImpl.nextRequestOptions(DnsRpc.Option.PAGE_TOKEN, cursor, optionMap); + this.serviceOptions = serviceOptions; + } + + @Override + public Page nextPage() { + return listChangeRequests(zoneName, serviceOptions, requestOptions, PB_TO_CHANGE_REQUEST); + } + } + + private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher { + + private static final Function PB_TO_DNS_RECORD = + new Function() { + @Override + public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { + return DnsRecord.fromPb(pb); + } + }; + private static final long serialVersionUID = 670996349097667660L; + private final Map requestOptions; + private final DnsOptions serviceOptions; + private final String zoneName; + + DnsRecordPageFetcher(String zoneName, DnsOptions serviceOptions, String cursor, + Map optionMap) { + this.zoneName = zoneName; + this.requestOptions = + PageImpl.nextRequestOptions(DnsRpc.Option.PAGE_TOKEN, cursor, optionMap); + this.serviceOptions = serviceOptions; + } + + @Override + public Page nextPage() { + return listDnsRecords(zoneName, serviceOptions, requestOptions, PB_TO_DNS_RECORD); + } + } + + private static Page listZones(final DnsOptions serviceOptions, + final Map optionsMap) { + // define transformation function + // this differs from the other list operations since zone is functional and requires dns service + Function pbToZoneFunction = new Function() { + @Override + public Zone apply( + com.google.api.services.dns.model.ManagedZone zonePb) { + return new Zone(serviceOptions.service(), ZoneInfo.fromPb(zonePb)); + } + }; + try { + // get a list of managed zones + DnsRpc.ListResult result = + runWithRetries(new Callable>() { + @Override + public DnsRpc.ListResult call() { + return serviceOptions.rpc().listZones(optionsMap); + } + }, serviceOptions.retryParams(), EXCEPTION_HANDLER); + String cursor = result.pageToken(); + // transform that list into zone objects + Iterable zones = result.results() == null + ? ImmutableList.of() : Iterables.transform(result.results(), pbToZoneFunction); + return new PageImpl<>(new ZonePageFetcher(serviceOptions, cursor, optionsMap), + cursor, zones); + } catch (RetryHelperException e) { + throw DnsException.translateAndThrow(e); + } + } + + private static Page listChangeRequests(final String zoneName, + final DnsOptions serviceOptions, final Map optionsMap, + Function TRANSFORM_FUNCTION) { + try { + // get a list of changes + DnsRpc.ListResult result = runWithRetries(new Callable>() { + @Override + public DnsRpc.ListResult call() { + return serviceOptions.rpc().listChangeRequests(zoneName, optionsMap); + } + }, serviceOptions.retryParams(), EXCEPTION_HANDLER); + String cursor = result.pageToken(); + // transform that list into change request objects + Iterable changes = result.results() == null + ? ImmutableList.of() + : Iterables.transform(result.results(), TRANSFORM_FUNCTION); + return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, + optionsMap), cursor, changes); + } catch (RetryHelperException e) { + throw DnsException.translateAndThrow(e); + } + } + + private static Page listDnsRecords(final String zoneName, + final DnsOptions serviceOptions, final Map optionsMap, + Function TRANSFORM_FUNCTION) { + try { + // get a list of resource record sets + DnsRpc.ListResult result = runWithRetries( + new Callable>() { + @Override + public DnsRpc.ListResult call() { + return serviceOptions.rpc().listDnsRecords(zoneName, optionsMap); + } + }, serviceOptions.retryParams(), EXCEPTION_HANDLER); + String cursor = result.pageToken(); + // transform that list into dns records + Iterable records = result.results() == null + ? ImmutableList.of() + : Iterables.transform(result.results(), TRANSFORM_FUNCTION); + return new PageImpl<>(new DnsRecordPageFetcher(zoneName, serviceOptions, cursor, optionsMap), + cursor, records); + } catch (RetryHelperException e) { + throw DnsException.translateAndThrow(e); + } + } + + DnsImpl(DnsOptions options) { + super(options); + dnsRpc = options.rpc(); + } + + @Override + public Page listZones(ZoneListOption... options) { + return listZones(options(), optionMap(options)); + } + + @Override + public Page listChangeRequests(String zoneName, + ChangeRequestListOption... options) { + return listChangeRequests(zoneName, options(), optionMap(options), + ChangeRequestPageFetcher.PB_TO_CHANGE_REQUEST); + } + + @Override + public Page listDnsRecords(String zoneName, DnsRecordListOption... options) { + return listDnsRecords(zoneName, options(), optionMap(options), + DnsRecordPageFetcher.PB_TO_DNS_RECORD); + } + + @Override + public Zone create(final ZoneInfo zoneInfo, Dns.ZoneOption... options) { + final Map optionsMap = optionMap(options); + try { + com.google.api.services.dns.model.ManagedZone answer = runWithRetries( + new Callable() { + @Override + public com.google.api.services.dns.model.ManagedZone call() { + return dnsRpc.create(zoneInfo.toPb(), optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : Zone.fromPb(this, answer); + } catch (RetryHelper.RetryHelperException ex) { + throw DnsException.translateAndThrow(ex); + } + } + + @Override + public Zone getZone(final String zoneName, Dns.ZoneOption... options) { + final Map optionsMap = optionMap(options); + try { + com.google.api.services.dns.model.ManagedZone answer = runWithRetries( + new Callable() { + @Override + public com.google.api.services.dns.model.ManagedZone call() { + return dnsRpc.getZone(zoneName, optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : Zone.fromPb(this, answer); + } catch (RetryHelper.RetryHelperException ex) { + throw DnsException.translateAndThrow(ex); + } + } + + @Override + public boolean delete(final String zoneName) { + try { + return runWithRetries(new Callable() { + @Override + public Boolean call() { + return dnsRpc.deleteZone(zoneName); + } + }, options().retryParams(), EXCEPTION_HANDLER); + } catch (RetryHelper.RetryHelperException ex) { + throw DnsException.translateAndThrow(ex); + } + } + + @Override + public ProjectInfo getProject(Dns.ProjectOption... fields) { + final Map optionsMap = optionMap(fields); + try { + com.google.api.services.dns.model.Project answer = runWithRetries( + new Callable() { + @Override + public com.google.api.services.dns.model.Project call() { + return dnsRpc.getProject(optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : ProjectInfo.fromPb(answer); // should never be null + } catch (RetryHelper.RetryHelperException ex) { + throw DnsException.translateAndThrow(ex); + } + } + + @Override + public ChangeRequest applyChangeRequest(final String zoneName, final ChangeRequest changeRequest, + Dns.ChangeRequestOption... options) { + final Map optionsMap = optionMap(options); + try { + com.google.api.services.dns.model.Change answer = + runWithRetries( + new Callable() { + @Override + public com.google.api.services.dns.model.Change call() { + return dnsRpc.applyChangeRequest(zoneName, changeRequest.toPb(), optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : fromPb(answer); // should never be null + } catch (RetryHelper.RetryHelperException ex) { + throw DnsException.translateAndThrow(ex); + } + } + + @Override + public ChangeRequest getChangeRequest(final String zoneName, final String changeRequestId, + Dns.ChangeRequestOption... options) { + final Map optionsMap = optionMap(options); + try { + com.google.api.services.dns.model.Change answer = + runWithRetries( + new Callable() { + @Override + public com.google.api.services.dns.model.Change call() { + return dnsRpc.getChangeRequest(zoneName, changeRequestId, optionsMap); + } + }, options().retryParams(), EXCEPTION_HANDLER); + return answer == null ? null : fromPb(answer); // should never be null + } catch (RetryHelper.RetryHelperException ex) { + throw DnsException.translateAndThrow(ex); + } + } + + private Map optionMap(AbstractOption... options) { + Map temp = Maps.newEnumMap(DnsRpc.Option.class); + for (AbstractOption option : options) { + Object prev = temp.put(option.rpcOption(), option.value()); + checkArgument(prev == null, "Duplicate option %s", option); + } + return ImmutableMap.copyOf(temp); + } +} 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 248fd164a55f..1ce4425366e5 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 @@ -37,7 +37,7 @@ public static class DefaultDnsFactory implements DnsFactory { @Override public Dns create(DnsOptions options) { // TODO(mderka) Implement when DnsImpl is available. Created issue #595. - return null; + return new DnsImpl(options); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java new file mode 100644 index 000000000000..8e063c9bb096 --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -0,0 +1,370 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.gcloud.Page; +import com.google.gcloud.RetryParams; +import com.google.gcloud.ServiceOptions; +import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.spi.DnsRpcFactory; + +import org.easymock.Capture; +import org.easymock.EasyMock; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Map; + +public class DnsImplTest { + + // Dns entities + private static final String ZONE_NAME = "some zone name"; + private static final String DNS_NAME = "example.com."; + private static final String CHANGE_ID = "some change id"; + private static final DnsRecord DNS_RECORD1 = DnsRecord.builder("Something", DnsRecord.Type.AAAA) + .build(); + private static final DnsRecord DNS_RECORD2 = DnsRecord.builder("Different", DnsRecord.Type.AAAA) + .build(); + private static final Integer MAX_SIZE = 20; + private static final String PAGE_TOKEN = "some token"; + private static final ZoneInfo ZONE_INFO = ZoneInfo.builder(ZONE_NAME).build(); + private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); + private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder() + .add(DNS_RECORD1) + .build(); + private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() + .add(DNS_RECORD1) + .startTimeMillis(123L) + .status(ChangeRequest.Status.PENDING) + .id(CHANGE_ID) + .build(); + + // Result lists + private static final DnsRpc.ListResult LIST_RESULT_OF_PB_CHANGES = + DnsRpc.ListResult.of("cursor", ImmutableList.of(CHANGE_REQUEST_COMPLETE.toPb(), + CHANGE_REQUEST_PARTIAL.toPb())); + private static final DnsRpc.ListResult LIST_RESULT_OF_PB_ZONES = + DnsRpc.ListResult.of("cursor", ImmutableList.of(ZONE_INFO.toPb())); + private static final DnsRpc.ListResult LIST_OF_PB_DNS_RECORDS = + DnsRpc.ListResult.of("cursor", ImmutableList.of(DNS_RECORD1.toPb(), DNS_RECORD2.toPb())); + + // Field options + private static final Dns.ZoneOption ZONE_FIELDS = + Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); + private static final Dns.ProjectOption PROJECT_FIELDS = + Dns.ProjectOption.fields(Dns.ProjectField.QUOTA); + private static final Dns.ChangeRequestOption CHANGE_GET_FIELDS = + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS); + + // Listing options + private static final Dns.ZoneListOption[] ZONE_LIST_OPTIONS = + {Dns.ZoneListOption.pageSize(MAX_SIZE), Dns.ZoneListOption.pageToken(PAGE_TOKEN), + Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)}; + private static final Dns.ChangeRequestListOption[] CHANGE_LIST_OPTIONS = + {Dns.ChangeRequestListOption.pageSize(MAX_SIZE), + Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)}; + private static final Dns.DnsRecordListOption[] DNS_RECORD_LIST_OPTIONS = + {Dns.DnsRecordListOption.pageSize(MAX_SIZE), + Dns.DnsRecordListOption.pageToken(PAGE_TOKEN), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL), + Dns.DnsRecordListOption.dnsName(DNS_NAME), + Dns.DnsRecordListOption.type(DnsRecord.Type.AAAA)}; + + // Other + private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); + private static final ServiceOptions.Clock TIME_SOURCE = new ServiceOptions.Clock() { + @Override + public long millis() { + return 42000L; + } + }; + + private DnsOptions options; + private DnsRpcFactory rpcFactoryMock; + private DnsRpc dnsRpcMock; + private Dns dns; + + @Before + public void setUp() { + rpcFactoryMock = EasyMock.createMock(DnsRpcFactory.class); + dnsRpcMock = EasyMock.createMock(DnsRpc.class); + EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(DnsOptions.class))) + .andReturn(dnsRpcMock); + EasyMock.replay(rpcFactoryMock); + options = DnsOptions.builder() + .projectId("projectId") + .clock(TIME_SOURCE) + .serviceRpcFactory(rpcFactoryMock) + .retryParams(RetryParams.noRetries()) + .build(); + } + + @After + public void tearDown() throws Exception { + EasyMock.verify(rpcFactoryMock); + } + + @Test + public void testCreateZone() { + EasyMock.expect(dnsRpcMock.create(ZONE_INFO.toPb(), EMPTY_RPC_OPTIONS)) + .andReturn(ZONE_INFO.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ZoneInfo zoneInfo = dns.create(ZONE_INFO); + assertEquals(ZONE_INFO, zoneInfo); + } + + @Test + public void testCreateZoneWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.create(EasyMock.eq(ZONE_INFO.toPb()), + EasyMock.capture(capturedOptions))).andReturn(ZONE_INFO.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Zone zone = dns.create(ZONE_INFO, ZONE_FIELDS); + String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); + assertEquals(ZONE_INFO, zone); + assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + } + + @Test + public void testGetZone() { + EasyMock.expect(dnsRpcMock.getZone(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + .andReturn(ZONE_INFO.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ZoneInfo zoneInfo = dns.getZone(ZONE_INFO.name()); + assertEquals(ZONE_INFO, zoneInfo); + } + + @Test + public void testGetZoneWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.getZone(EasyMock.eq(ZONE_INFO.name()), + EasyMock.capture(capturedOptions))).andReturn(ZONE_INFO.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ZoneInfo zoneInfo = dns.getZone(ZONE_INFO.name(), ZONE_FIELDS); + String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); + assertEquals(ZONE_INFO, zoneInfo); + assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + } + + @Test + public void testDeleteZone() { + EasyMock.expect(dnsRpcMock.deleteZone(ZONE_INFO.name())) + .andReturn(true); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + assertTrue(dns.delete(ZONE_INFO.name())); + } + + @Test + public void testGetProject() { + EasyMock.expect(dnsRpcMock.getProject(EMPTY_RPC_OPTIONS)) + .andReturn(PROJECT_INFO.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ProjectInfo projectInfo = dns.getProject(); + assertEquals(PROJECT_INFO, projectInfo); + } + + @Test + public void testProjectGetWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.getProject(EasyMock.capture(capturedOptions))) + .andReturn(PROJECT_INFO.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ProjectInfo projectInfo = dns.getProject(PROJECT_FIELDS); + String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.rpcOption()); + assertEquals(PROJECT_INFO, projectInfo); + assertTrue(selector.contains(Dns.ProjectField.QUOTA.selector())); + assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.selector())); + } + + @Test + public void testGetChangeRequest() { + EasyMock.expect(dnsRpcMock.getChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_COMPLETE.id(), + EMPTY_RPC_OPTIONS)).andReturn(CHANGE_REQUEST_COMPLETE.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.name(), + CHANGE_REQUEST_COMPLETE.id()); + assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + } + + @Test + public void testGetChangeRequestWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.getChangeRequest(EasyMock.eq(ZONE_INFO.name()), + EasyMock.eq(CHANGE_REQUEST_COMPLETE.id()), EasyMock.capture(capturedOptions))) + .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.name(), + CHANGE_REQUEST_COMPLETE.id(), CHANGE_GET_FIELDS); + String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); + assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + } + + @Test + public void testApplyChangeRequest() { + EasyMock.expect(dnsRpcMock.applyChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_PARTIAL.toPb(), + EMPTY_RPC_OPTIONS)).andReturn(CHANGE_REQUEST_COMPLETE.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.name(), + CHANGE_REQUEST_PARTIAL); + assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + } + + @Test + public void testApplyChangeRequestWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.applyChangeRequest(EasyMock.eq(ZONE_INFO.name()), + EasyMock.eq(CHANGE_REQUEST_PARTIAL.toPb()), EasyMock.capture(capturedOptions))) + .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.name(), + CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); + String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); + assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + } + + // lists + @Test + public void testListChangeRequests() { + EasyMock.expect(dnsRpcMock.listChangeRequests(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + .andReturn(LIST_RESULT_OF_PB_CHANGES); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Page changeRequestPage = dns.listChangeRequests(ZONE_INFO.name()); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_COMPLETE)); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_PARTIAL)); + assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); + } + + @Test + public void testListChangeRequestsWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.listChangeRequests(EasyMock.eq(ZONE_NAME), + EasyMock.capture(capturedOptions))).andReturn(LIST_RESULT_OF_PB_CHANGES); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Page changeRequestPage = dns.listChangeRequests(ZONE_NAME, CHANGE_LIST_OPTIONS); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_COMPLETE)); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_PARTIAL)); + assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); + Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].rpcOption()); + assertEquals(MAX_SIZE, size); + String selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].rpcOption()); + assertEquals(PAGE_TOKEN, selector); + selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].rpcOption()); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].rpcOption()); + assertTrue(selector.contains(Dns.SortingOrder.ASCENDING.selector())); + } + + @Test + public void testListZones() { + EasyMock.expect(dnsRpcMock.listZones(EMPTY_RPC_OPTIONS)) + .andReturn(LIST_RESULT_OF_PB_ZONES); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Page zonePage = dns.listZones(); + assertEquals(1, Lists.newArrayList(zonePage.values()).size()); + assertEquals(ZONE_INFO, Lists.newArrayList(zonePage.values()).get(0)); + } + + @Test + public void testListZonesWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.listZones(EasyMock.capture(capturedOptions))) + .andReturn(LIST_RESULT_OF_PB_ZONES); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Page zonePage = dns.listZones(ZONE_LIST_OPTIONS); + assertEquals(1, Lists.newArrayList(zonePage.values()).size()); + assertEquals(ZONE_INFO, Lists.newArrayList(zonePage.values()).get(0)); + Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].rpcOption()); + assertEquals(MAX_SIZE, size); + String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].rpcOption()); + assertEquals(PAGE_TOKEN, selector); + selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].rpcOption()); + assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.selector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + } + + @Test + public void testListDnsRecords() { + EasyMock.expect(dnsRpcMock.listDnsRecords(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + .andReturn(LIST_OF_PB_DNS_RECORDS); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Page dnsPage = dns.listDnsRecords(ZONE_INFO.name()); + assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); + assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); + assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); + } + + @Test + public void testListDnsRecordsWithOptions() { + Capture> capturedOptions = Capture.newInstance(); + EasyMock.expect(dnsRpcMock.listDnsRecords(EasyMock.eq(ZONE_NAME), + EasyMock.capture(capturedOptions))).andReturn(LIST_OF_PB_DNS_RECORDS); + EasyMock.replay(dnsRpcMock); + dns = options.service(); // creates DnsImpl + Page dnsPage = dns.listDnsRecords(ZONE_NAME, DNS_RECORD_LIST_OPTIONS); + assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); + assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); + assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); + Integer size = (Integer) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[0].rpcOption()); + assertEquals(MAX_SIZE, size); + String selector = (String) capturedOptions.getValue() + .get(DNS_RECORD_LIST_OPTIONS[1].rpcOption()); + assertEquals(PAGE_TOKEN, selector); + selector = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[2].rpcOption()); + assertTrue(selector.contains(Dns.DnsRecordField.NAME.selector())); + assertTrue(selector.contains(Dns.DnsRecordField.TTL.selector())); + selector = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[3].rpcOption()); + assertEquals(DNS_RECORD_LIST_OPTIONS[3].value(), selector); + DnsRecord.Type type = (DnsRecord.Type) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[4] + .rpcOption()); + assertEquals(DNS_RECORD_LIST_OPTIONS[4].value(), type); + } +} From c0c5451d286675248e32fdf3a37c7c9293cd3f4a Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 8 Feb 2016 11:34:41 -0800 Subject: [PATCH 47/74] Included options attribute to Zone. Fixed symmetry of toPb and fromPb. Finished DnsOptions. Fixed #595. --- .../java/com/google/gcloud/dns/DnsImpl.java | 44 +++++++++---------- .../com/google/gcloud/dns/DnsOptions.java | 4 +- .../main/java/com/google/gcloud/dns/Zone.java | 17 +++++-- .../java/com/google/gcloud/dns/ZoneInfo.java | 19 ++++---- .../com/google/gcloud/dns/DnsImplTest.java | 18 ++++---- .../java/com/google/gcloud/dns/ZoneTest.java | 24 +++++++++- 6 files changed, 79 insertions(+), 47 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index b3ae73fd7e93..c93409554dd8 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -120,6 +120,11 @@ public Page nextPage() { } } + @Override + public Page listZones(ZoneListOption... options) { + return listZones(options(), optionMap(options)); + } + private static Page listZones(final DnsOptions serviceOptions, final Map optionsMap) { // define transformation function @@ -151,9 +156,16 @@ public DnsRpc.ListResult call() { } } + @Override + public Page listChangeRequests(String zoneName, + ChangeRequestListOption... options) { + return listChangeRequests(zoneName, options(), optionMap(options), + ChangeRequestPageFetcher.PB_TO_CHANGE_REQUEST); + } + private static Page listChangeRequests(final String zoneName, final DnsOptions serviceOptions, final Map optionsMap, - Function TRANSFORM_FUNCTION) { + Function transformFunction) { try { // get a list of changes DnsRpc.ListResult result = runWithRetries(new Callable>() { @@ -166,7 +178,7 @@ public DnsRpc.ListResult call() { // transform that list into change request objects Iterable changes = result.results() == null ? ImmutableList.of() - : Iterables.transform(result.results(), TRANSFORM_FUNCTION); + : Iterables.transform(result.results(), transformFunction); return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, changes); } catch (RetryHelperException e) { @@ -174,9 +186,15 @@ public DnsRpc.ListResult call() { } } + @Override + public Page listDnsRecords(String zoneName, DnsRecordListOption... options) { + return listDnsRecords(zoneName, options(), optionMap(options), + DnsRecordPageFetcher.PB_TO_DNS_RECORD); + } + private static Page listDnsRecords(final String zoneName, final DnsOptions serviceOptions, final Map optionsMap, - Function TRANSFORM_FUNCTION) { + Function transformFunction) { try { // get a list of resource record sets DnsRpc.ListResult result = runWithRetries( @@ -190,7 +208,7 @@ public DnsRpc.ListResult call() { // transform that list into dns records Iterable records = result.results() == null ? ImmutableList.of() - : Iterables.transform(result.results(), TRANSFORM_FUNCTION); + : Iterables.transform(result.results(), transformFunction); return new PageImpl<>(new DnsRecordPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, records); } catch (RetryHelperException e) { @@ -203,24 +221,6 @@ public DnsRpc.ListResult call() { dnsRpc = options.rpc(); } - @Override - public Page listZones(ZoneListOption... options) { - return listZones(options(), optionMap(options)); - } - - @Override - public Page listChangeRequests(String zoneName, - ChangeRequestListOption... options) { - return listChangeRequests(zoneName, options(), optionMap(options), - ChangeRequestPageFetcher.PB_TO_CHANGE_REQUEST); - } - - @Override - public Page listDnsRecords(String zoneName, DnsRecordListOption... options) { - return listDnsRecords(zoneName, options(), optionMap(options), - DnsRecordPageFetcher.PB_TO_DNS_RECORD); - } - @Override public Zone create(final ZoneInfo zoneInfo, Dns.ZoneOption... options) { final Map optionsMap = optionMap(options); 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 1ce4425366e5..b47532146b3a 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 @@ -24,8 +24,7 @@ import java.util.Set; -public class DnsOptions - extends ServiceOptions { +public class DnsOptions extends ServiceOptions { private static final long serialVersionUID = -519128051411747771L; private static final String GC_DNS_RW = "https://www.googleapis.com/auth/ndev.clouddns.readwrite"; @@ -36,7 +35,6 @@ public static class DefaultDnsFactory implements DnsFactory { @Override public Dns create(DnsOptions options) { - // TODO(mderka) Implement when DnsImpl is available. Created issue #595. return new DnsImpl(options); } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 2da67a8e9a01..d53909b0f084 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -20,6 +20,8 @@ import com.google.gcloud.Page; +import java.io.IOException; +import java.io.ObjectInputStream; import java.util.List; import java.util.Objects; @@ -36,7 +38,8 @@ */ public class Zone extends ZoneInfo { - private static final long serialVersionUID = 564454483894599281L; + private static final long serialVersionUID = -5817771337847861598L; + private final DnsOptions options; private transient Dns dns; /** @@ -102,6 +105,7 @@ public Zone build() { Zone(Dns dns, ZoneInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.dns = dns; + this.options = dns.options(); } @Override @@ -115,6 +119,7 @@ public Builder toBuilder() { public Zone(Dns dns, ZoneInfo zoneInfo) { super(new BuilderImpl(zoneInfo)); this.dns = dns; + this.options = dns.options(); } /** @@ -215,12 +220,18 @@ public Dns dns() { @Override public boolean equals(Object obj) { - return obj instanceof Zone && Objects.equals(toPb(), ((Zone) obj).toPb()); + return obj instanceof Zone && Objects.equals(toPb(), ((Zone) obj).toPb()) + && Objects.equals(options, ((Zone) obj).options); } @Override public int hashCode() { - return super.hashCode(); + return Objects.hash(super.hashCode(), options); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + this.dns = options.service(); } static Zone fromPb(Dns dns, com.google.api.services.dns.model.ManagedZone zone) { diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index e397e37a7fbf..e26dcde70a83 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -27,7 +27,6 @@ import java.io.Serializable; import java.math.BigInteger; -import java.util.LinkedList; import java.util.List; import java.util.Objects; @@ -97,14 +96,14 @@ public abstract static class Builder { public abstract ZoneInfo build(); } - public static class BuilderImpl extends Builder { + static class BuilderImpl extends Builder { private String name; private String id; private Long creationTimeMillis; private String dnsName; private String description; private String nameServerSet; - private List nameServers = new LinkedList<>(); + private List nameServers; private BuilderImpl(String name) { this.name = checkNotNull(name); @@ -120,7 +119,9 @@ private BuilderImpl(String name) { this.dnsName = info.dnsName; this.description = info.description; this.nameServerSet = info.nameServerSet; - this.nameServers.addAll(info.nameServers); + if (info.nameServers != null) { + this.nameServers = ImmutableList.copyOf(info.nameServers); + } } @Override @@ -179,7 +180,8 @@ public ZoneInfo build() { this.dnsName = builder.dnsName; this.description = builder.description; this.nameServerSet = builder.nameServerSet; - this.nameServers = ImmutableList.copyOf(builder.nameServers); + this.nameServers = builder.nameServers == null + ? null : ImmutableList.copyOf(builder.nameServers); } /** @@ -236,7 +238,7 @@ public String nameServerSet() { * The nameservers that the zone should be delegated to. This is defined by the Google DNS cloud. */ public List nameServers() { - return nameServers; + return nameServers == null ? ImmutableList.of() : nameServers; } /** @@ -255,7 +257,7 @@ com.google.api.services.dns.model.ManagedZone toPb() { pb.setId(new BigInteger(this.id())); } pb.setName(this.name()); - pb.setNameServers(this.nameServers()); + pb.setNameServers(this.nameServers); // do use real attribute value which may be null pb.setNameServerSet(this.nameServerSet()); if (this.creationTimeMillis() != null) { pb.setCreationTime(ISODateTimeFormat.dateTime() @@ -290,7 +292,8 @@ static ZoneInfo fromPb(com.google.api.services.dns.model.ManagedZone pb) { @Override public boolean equals(Object obj) { - return obj instanceof ZoneInfo && Objects.equals(toPb(), ((ZoneInfo) obj).toPb()); + return obj != null && obj.getClass().equals(ZoneInfo.class) + && Objects.equals(toPb(), ((ZoneInfo) obj).toPb()); } @Override diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index 8e063c9bb096..62e96b05dda5 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -136,8 +136,8 @@ public void testCreateZone() { .andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - ZoneInfo zoneInfo = dns.create(ZONE_INFO); - assertEquals(ZONE_INFO, zoneInfo); + Zone zone = dns.create(ZONE_INFO); + assertEquals(new Zone(dns, ZONE_INFO), zone); } @Test @@ -149,7 +149,7 @@ public void testCreateZoneWithOptions() { dns = options.service(); // creates DnsImpl Zone zone = dns.create(ZONE_INFO, ZONE_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); - assertEquals(ZONE_INFO, zone); + assertEquals(new Zone(dns, ZONE_INFO), zone); assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); } @@ -160,8 +160,8 @@ public void testGetZone() { .andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - ZoneInfo zoneInfo = dns.getZone(ZONE_INFO.name()); - assertEquals(ZONE_INFO, zoneInfo); + Zone zone = dns.getZone(ZONE_INFO.name()); + assertEquals(new Zone(dns, ZONE_INFO), zone); } @Test @@ -171,9 +171,9 @@ public void testGetZoneWithOptions() { EasyMock.capture(capturedOptions))).andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - ZoneInfo zoneInfo = dns.getZone(ZONE_INFO.name(), ZONE_FIELDS); + Zone zone = dns.getZone(ZONE_INFO.name(), ZONE_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); - assertEquals(ZONE_INFO, zoneInfo); + assertEquals(new Zone(dns, ZONE_INFO), zone); assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); } @@ -308,7 +308,7 @@ public void testListZones() { dns = options.service(); // creates DnsImpl Page zonePage = dns.listZones(); assertEquals(1, Lists.newArrayList(zonePage.values()).size()); - assertEquals(ZONE_INFO, Lists.newArrayList(zonePage.values()).get(0)); + assertEquals(new Zone(dns, ZONE_INFO), Lists.newArrayList(zonePage.values()).get(0)); } @Test @@ -320,7 +320,7 @@ public void testListZonesWithOptions() { dns = options.service(); // creates DnsImpl Page zonePage = dns.listZones(ZONE_LIST_OPTIONS); assertEquals(1, Lists.newArrayList(zonePage.values()).size()); - assertEquals(ZONE_INFO, Lists.newArrayList(zonePage.values()).get(0)); + assertEquals(new Zone(dns, ZONE_INFO), Lists.newArrayList(zonePage.values()).get(0)); Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].rpcOption()); assertEquals(MAX_SIZE, size); String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].rpcOption()); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 1b09dca715a4..b28847a4e046 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -19,6 +19,7 @@ import static org.easymock.EasyMock.createStrictMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -64,16 +65,22 @@ public class ZoneTest { .startTimeMillis(123465L).build(); private static final ChangeRequest CHANGE_REQUEST_NO_ID = ChangeRequest.builder().build(); private static final DnsException EXCEPTION = createStrictMock(DnsException.class); + private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); private Dns dns; private Zone zone; private Zone zoneNoId; + @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + replay(dns); zone = new Zone(dns, ZONE_INFO); zoneNoId = new Zone(dns, NO_ID_INFO); + reset(dns); } @After @@ -347,13 +354,13 @@ public void getChangeAndZoneNotFoundByName() { .andThrow(EXCEPTION); replay(dns); try { - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); + zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - ChangeRequest result = zone.getChangeRequest(CHANGE_REQUEST.id()); + zone.getChangeRequest(CHANGE_REQUEST.id()); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected @@ -505,18 +512,31 @@ public void listChangeRequestsAndZoneNotFound() { @Test public void testFromPb() { + expect(dns.options()).andReturn(OPTIONS); replay(dns); assertEquals(Zone.fromPb(dns, zone.toPb()), zone); } @Test public void testEqualsAndToBuilder() { + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); replay(dns); assertEquals(zone, zone.toBuilder().build()); + assertEquals(zone.hashCode(), zone.toBuilder().build().hashCode()); } @Test public void testBuilder() { + // one for each build() call because it invokes a constructor + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); replay(dns); assertNotEquals(zone, zone.toBuilder() .id((new BigInteger(zone.id())).add(BigInteger.ONE).toString()) From ee5bb8f1db07dd6a3fb125c16acfd27f8e0c7325 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 8 Feb 2016 16:35:07 -0800 Subject: [PATCH 48/74] Removed zone.get() and optimized retries. --- .../com/google/gcloud/dns/ChangeRequest.java | 27 +++----- .../main/java/com/google/gcloud/dns/Dns.java | 2 +- .../java/com/google/gcloud/dns/DnsImpl.java | 61 +++++++------------ .../java/com/google/gcloud/dns/DnsRecord.java | 18 +++++- .../main/java/com/google/gcloud/dns/Zone.java | 26 +------- .../java/com/google/gcloud/dns/ZoneInfo.java | 2 +- .../com/google/gcloud/dns/DnsImplTest.java | 42 +++++++------ .../java/com/google/gcloud/dns/ZoneTest.java | 28 +-------- 8 files changed, 77 insertions(+), 129 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index 582dd2b2e05b..76d231b704c4 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -18,7 +18,7 @@ import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.api.services.dns.model.Change; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; @@ -40,21 +40,14 @@ */ public class ChangeRequest implements Serializable { - private static final Function FROM_PB_FUNCTION = - new Function() { + static final Function FROM_PB_FUNCTION = + new Function() { @Override - public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { - return DnsRecord.fromPb(pb); + public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { + return ChangeRequest.fromPb(pb); } }; - private static final Function TO_PB_FUNCTION = - new Function() { - @Override - public com.google.api.services.dns.model.ResourceRecordSet apply(DnsRecord error) { - return error.toPb(); - } - }; - private static final long serialVersionUID = -8703939628990291682L; + private static final long serialVersionUID = -9027378042756366333L; private final List additions; private final List deletions; private final String id; @@ -274,9 +267,9 @@ com.google.api.services.dns.model.Change toPb() { pb.setStatus(status().name().toLowerCase()); } // set a list of additions - pb.setAdditions(Lists.transform(additions(), TO_PB_FUNCTION)); + pb.setAdditions(Lists.transform(additions(), DnsRecord.TO_PB_FUNCTION)); // set a list of deletions - pb.setDeletions(Lists.transform(deletions(), TO_PB_FUNCTION)); + pb.setDeletions(Lists.transform(deletions(), DnsRecord.TO_PB_FUNCTION)); return pb; } @@ -293,10 +286,10 @@ static ChangeRequest fromPb(com.google.api.services.dns.model.Change pb) { builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); } if (pb.getDeletions() != null) { - builder.deletions(Lists.transform(pb.getDeletions(), FROM_PB_FUNCTION)); + builder.deletions(Lists.transform(pb.getDeletions(), DnsRecord.FROM_PB_FUNCTION)); } if (pb.getAdditions() != null) { - builder.additions(Lists.transform(pb.getAdditions(), FROM_PB_FUNCTION)); + builder.additions(Lists.transform(pb.getAdditions(), DnsRecord.FROM_PB_FUNCTION)); } return builder.build(); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 88e0d7a08591..e724e1cbf1ad 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -419,7 +419,7 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { /** * Creates a new zone. * - *

Returns {@link ZoneInfo} object representing the new zone's information. In addition to the + *

Returns {@link Zone} object representing the new zone's information. In addition to the * name, dns name and description (supplied by the user within the {@code zoneInfo} parameter), * the returned object can include the following read-only fields supplied by the server: creation * time, id, and list of name servers. The returned fields can be optionally restricted by diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index c93409554dd8..17521c13c625 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -66,14 +66,7 @@ public Page nextPage() { private static class ChangeRequestPageFetcher implements PageImpl.NextPageFetcher { - private static final Function PB_TO_CHANGE_REQUEST = - new Function() { - @Override - public ChangeRequest apply(com.google.api.services.dns.model.Change changePb) { - return fromPb(changePb); - } - }; - private static final long serialVersionUID = -8737501076674042014L; + private static final long serialVersionUID = 4473265130673029139L; private final String zoneName; private final Map requestOptions; private final DnsOptions serviceOptions; @@ -88,20 +81,13 @@ public ChangeRequest apply(com.google.api.services.dns.model.Change changePb) { @Override public Page nextPage() { - return listChangeRequests(zoneName, serviceOptions, requestOptions, PB_TO_CHANGE_REQUEST); + return listChangeRequests(zoneName, serviceOptions, requestOptions); } } private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher { - private static final Function PB_TO_DNS_RECORD = - new Function() { - @Override - public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { - return DnsRecord.fromPb(pb); - } - }; - private static final long serialVersionUID = 670996349097667660L; + private static final long serialVersionUID = -6039369212511530846L; private final Map requestOptions; private final DnsOptions serviceOptions; private final String zoneName; @@ -116,10 +102,15 @@ public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { @Override public Page nextPage() { - return listDnsRecords(zoneName, serviceOptions, requestOptions, PB_TO_DNS_RECORD); + return listDnsRecords(zoneName, serviceOptions, requestOptions); } } + DnsImpl(DnsOptions options) { + super(options); + dnsRpc = options.rpc(); + } + @Override public Page listZones(ZoneListOption... options) { return listZones(options(), optionMap(options)); @@ -133,16 +124,17 @@ private static Page listZones(final DnsOptions serviceOptions, @Override public Zone apply( com.google.api.services.dns.model.ManagedZone zonePb) { - return new Zone(serviceOptions.service(), ZoneInfo.fromPb(zonePb)); + return Zone.fromPb(serviceOptions.service(), zonePb); } }; try { // get a list of managed zones + final DnsRpc rpc = serviceOptions.rpc(); DnsRpc.ListResult result = runWithRetries(new Callable>() { @Override public DnsRpc.ListResult call() { - return serviceOptions.rpc().listZones(optionsMap); + return rpc.listZones(optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER); String cursor = result.pageToken(); @@ -159,26 +151,25 @@ public DnsRpc.ListResult call() { @Override public Page listChangeRequests(String zoneName, ChangeRequestListOption... options) { - return listChangeRequests(zoneName, options(), optionMap(options), - ChangeRequestPageFetcher.PB_TO_CHANGE_REQUEST); + return listChangeRequests(zoneName, options(), optionMap(options)); } private static Page listChangeRequests(final String zoneName, - final DnsOptions serviceOptions, final Map optionsMap, - Function transformFunction) { + final DnsOptions serviceOptions, final Map optionsMap) { try { // get a list of changes + final DnsRpc rpc = serviceOptions.rpc(); DnsRpc.ListResult result = runWithRetries(new Callable>() { @Override public DnsRpc.ListResult call() { - return serviceOptions.rpc().listChangeRequests(zoneName, optionsMap); + return rpc.listChangeRequests(zoneName, optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER); String cursor = result.pageToken(); // transform that list into change request objects Iterable changes = result.results() == null ? ImmutableList.of() - : Iterables.transform(result.results(), transformFunction); + : Iterables.transform(result.results(), ChangeRequest.FROM_PB_FUNCTION); return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, changes); } catch (RetryHelperException e) { @@ -188,27 +179,26 @@ public DnsRpc.ListResult call() { @Override public Page listDnsRecords(String zoneName, DnsRecordListOption... options) { - return listDnsRecords(zoneName, options(), optionMap(options), - DnsRecordPageFetcher.PB_TO_DNS_RECORD); + return listDnsRecords(zoneName, options(), optionMap(options)); } private static Page listDnsRecords(final String zoneName, - final DnsOptions serviceOptions, final Map optionsMap, - Function transformFunction) { + final DnsOptions serviceOptions, final Map optionsMap) { try { // get a list of resource record sets + final DnsRpc rpc = serviceOptions.rpc(); DnsRpc.ListResult result = runWithRetries( new Callable>() { @Override public DnsRpc.ListResult call() { - return serviceOptions.rpc().listDnsRecords(zoneName, optionsMap); + return rpc.listDnsRecords(zoneName, optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER); String cursor = result.pageToken(); // transform that list into dns records Iterable records = result.results() == null ? ImmutableList.of() - : Iterables.transform(result.results(), transformFunction); + : Iterables.transform(result.results(), DnsRecord.FROM_PB_FUNCTION); return new PageImpl<>(new DnsRecordPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, records); } catch (RetryHelperException e) { @@ -216,11 +206,6 @@ public DnsRpc.ListResult call() { } } - DnsImpl(DnsOptions options) { - super(options); - dnsRpc = options.rpc(); - } - @Override public Zone create(final ZoneInfo zoneInfo, Dns.ZoneOption... options) { final Map optionsMap = optionMap(options); @@ -318,7 +303,7 @@ public com.google.api.services.dns.model.Change call() { return dnsRpc.getChangeRequest(zoneName, changeRequestId, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); - return answer == null ? null : fromPb(answer); // should never be null + return answer == null ? null : fromPb(answer); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java index 99ca20386419..c4e710bd0365 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java @@ -19,6 +19,8 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @@ -43,7 +45,21 @@ */ public class DnsRecord implements Serializable { - private static final long serialVersionUID = 2016011914302204L; + static final Function FROM_PB_FUNCTION = + new Function() { + @Override + public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { + return DnsRecord.fromPb(pb); + } + }; + static final Function TO_PB_FUNCTION = + new Function() { + @Override + public com.google.api.services.dns.model.ResourceRecordSet apply(DnsRecord error) { + return error.toPb(); + } + }; + private static final long serialVersionUID = 8148009870800115261L; private final String name; private final List rrdatas; private final Integer ttl; // this is in seconds diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index d53909b0f084..323b0eb8c439 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -113,30 +113,6 @@ public Builder toBuilder() { return new Builder(this); } - /** - * Constructs a {@code Zone} object that contains the given {@code zoneInfo}. - */ - public Zone(Dns dns, ZoneInfo zoneInfo) { - super(new BuilderImpl(zoneInfo)); - this.dns = dns; - this.options = dns.options(); - } - - /** - * Constructs a {@code Zone} object that contains meta information received from the Google Cloud - * DNS service for the provided {@code zoneName}. - * - * @param zoneName name of the zone to be searched for - * @param options optional restriction on what fields should be returned by the service - * @return zone object containing metadata or {@code null} if not not found - * @throws DnsException upon failure - */ - public static Zone get(Dns dnsService, String zoneName, Dns.ZoneOption... options) { - checkNotNull(zoneName); - checkNotNull(dnsService); - return dnsService.getZone(zoneName, options); - } - /** * Retrieves the latest information about the zone. The method retrieves the zone by name. * @@ -236,6 +212,6 @@ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundE static Zone fromPb(Dns dns, com.google.api.services.dns.model.ManagedZone zone) { ZoneInfo info = ZoneInfo.fromPb(zone); - return new Zone(dns, info); + return new Zone(dns, new ZoneInfo.BuilderImpl(info)); } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index e26dcde70a83..f02f9f2c5226 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -81,7 +81,7 @@ public abstract static class Builder { * Optionally specifies the NameServerSet for this zone. A NameServerSet is a set of DNS name * servers that all host the same zones. Most users will not need to specify this value. */ - public abstract Builder nameServerSet(String nameServerSet); + abstract Builder nameServerSet(String nameServerSet); // todo(mderka) add more to the doc when questions are answered by the service owner /** diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index 62e96b05dda5..726a455418d8 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -81,20 +81,20 @@ public class DnsImplTest { Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS); // Listing options - private static final Dns.ZoneListOption[] ZONE_LIST_OPTIONS = - {Dns.ZoneListOption.pageSize(MAX_SIZE), Dns.ZoneListOption.pageToken(PAGE_TOKEN), - Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)}; - private static final Dns.ChangeRequestListOption[] CHANGE_LIST_OPTIONS = - {Dns.ChangeRequestListOption.pageSize(MAX_SIZE), - Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)}; - private static final Dns.DnsRecordListOption[] DNS_RECORD_LIST_OPTIONS = - {Dns.DnsRecordListOption.pageSize(MAX_SIZE), - Dns.DnsRecordListOption.pageToken(PAGE_TOKEN), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL), - Dns.DnsRecordListOption.dnsName(DNS_NAME), - Dns.DnsRecordListOption.type(DnsRecord.Type.AAAA)}; + private static final Dns.ZoneListOption[] ZONE_LIST_OPTIONS = { + Dns.ZoneListOption.pageSize(MAX_SIZE), Dns.ZoneListOption.pageToken(PAGE_TOKEN), + Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)}; + private static final Dns.ChangeRequestListOption[] CHANGE_LIST_OPTIONS = { + Dns.ChangeRequestListOption.pageSize(MAX_SIZE), + Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)}; + private static final Dns.DnsRecordListOption[] DNS_RECORD_LIST_OPTIONS = { + Dns.DnsRecordListOption.pageSize(MAX_SIZE), + Dns.DnsRecordListOption.pageToken(PAGE_TOKEN), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL), + Dns.DnsRecordListOption.dnsName(DNS_NAME), + Dns.DnsRecordListOption.type(DnsRecord.Type.AAAA)}; // Other private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); @@ -137,7 +137,7 @@ public void testCreateZone() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl Zone zone = dns.create(ZONE_INFO); - assertEquals(new Zone(dns, ZONE_INFO), zone); + assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); } @Test @@ -149,7 +149,7 @@ public void testCreateZoneWithOptions() { dns = options.service(); // creates DnsImpl Zone zone = dns.create(ZONE_INFO, ZONE_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); - assertEquals(new Zone(dns, ZONE_INFO), zone); + assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); } @@ -161,7 +161,7 @@ public void testGetZone() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl Zone zone = dns.getZone(ZONE_INFO.name()); - assertEquals(new Zone(dns, ZONE_INFO), zone); + assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); } @Test @@ -173,7 +173,7 @@ public void testGetZoneWithOptions() { dns = options.service(); // creates DnsImpl Zone zone = dns.getZone(ZONE_INFO.name(), ZONE_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); - assertEquals(new Zone(dns, ZONE_INFO), zone); + assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); } @@ -308,7 +308,8 @@ public void testListZones() { dns = options.service(); // creates DnsImpl Page zonePage = dns.listZones(); assertEquals(1, Lists.newArrayList(zonePage.values()).size()); - assertEquals(new Zone(dns, ZONE_INFO), Lists.newArrayList(zonePage.values()).get(0)); + assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), + Lists.newArrayList(zonePage.values()).get(0)); } @Test @@ -320,7 +321,8 @@ public void testListZonesWithOptions() { dns = options.service(); // creates DnsImpl Page zonePage = dns.listZones(ZONE_LIST_OPTIONS); assertEquals(1, Lists.newArrayList(zonePage.values()).size()); - assertEquals(new Zone(dns, ZONE_INFO), Lists.newArrayList(zonePage.values()).get(0)); + assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), + Lists.newArrayList(zonePage.values()).get(0)); Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].rpcOption()); assertEquals(MAX_SIZE, size); String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].rpcOption()); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index b28847a4e046..5164dfb6001c 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -78,8 +78,8 @@ public void setUp() throws Exception { expect(dns.options()).andReturn(OPTIONS); expect(dns.options()).andReturn(OPTIONS); replay(dns); - zone = new Zone(dns, ZONE_INFO); - zoneNoId = new Zone(dns, NO_ID_INFO); + zone = new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)); + zoneNoId = new Zone(dns, new ZoneInfo.BuilderImpl(NO_ID_INFO)); reset(dns); } @@ -96,30 +96,6 @@ public void testConstructor() { assertEquals(dns, zone.dns()); } - @Test - public void testGetByName() { - expect(dns.getZone(ZONE_NAME)).andReturn(zone); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone); // for options - replay(dns); - Zone retrieved = Zone.get(dns, ZONE_NAME); - assertSame(dns, retrieved.dns()); - assertEquals(zone, retrieved); - // test passing options - Zone.get(dns, ZONE_NAME, ZONE_FIELD_OPTIONS); - try { - Zone.get(dns, null); - fail("Cannot get by null name."); - } catch (NullPointerException e) { - // expected - } - try { - Zone.get(null, "Not null"); - fail("Cannot get anything from null service."); - } catch (NullPointerException e) { - // expected - } - } - @Test public void deleteByNameAndFound() { expect(dns.delete(ZONE_NAME)).andReturn(true); From db52e09aaae1101fb80e9e6abcfb55233b1ed57b Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 9 Feb 2016 08:37:41 -0800 Subject: [PATCH 49/74] Made nameServerSet read only and setters package private. Adds dnsName filter for Zone listing and tests. Adds serialization test. Fixes #630, #602 and #631. --- .../main/java/com/google/gcloud/dns/Dns.java | 8 ++ .../com/google/gcloud/dns/DnsOptions.java | 10 ++ .../main/java/com/google/gcloud/dns/Zone.java | 2 +- .../java/com/google/gcloud/dns/ZoneInfo.java | 8 +- .../com/google/gcloud/dns/DnsImplTest.java | 5 +- .../java/com/google/gcloud/dns/DnsTest.java | 5 + .../google/gcloud/dns/SerializationTest.java | 118 ++++++++++++++++++ 7 files changed, 150 insertions(+), 6 deletions(-) create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index e724e1cbf1ad..3ad2094ec2e3 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -295,6 +295,14 @@ public static ZoneListOption pageToken(String pageToken) { return new ZoneListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); } + /** + * Restricts the list to only zone with this fully qualified domain name. + */ + public static ZoneListOption dnsName(String dnsName) { + StringBuilder builder = new StringBuilder(); + return new ZoneListOption(DnsRpc.Option.DNS_NAME, dnsName); + } + /** * The maximum number of zones to return per RPC. * 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 b47532146b3a..d9317546cea0 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 @@ -95,4 +95,14 @@ public Builder toBuilder() { public static Builder builder() { return new Builder(); } + + @Override + public boolean equals(Object obj) { + return obj instanceof DnsOptions && baseEquals((DnsOptions) obj); + } + + @Override + public int hashCode() { + return baseHashCode(); + } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 323b0eb8c439..41507647543a 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -85,7 +85,7 @@ public Builder description(String description) { } @Override - public Builder nameServerSet(String nameServerSet) { + Builder nameServerSet(String nameServerSet) { infoBuilder.nameServerSet(nameServerSet); return this; } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index f02f9f2c5226..7dffbcdd365c 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -82,7 +82,7 @@ public abstract static class Builder { * servers that all host the same zones. Most users will not need to specify this value. */ abstract Builder nameServerSet(String nameServerSet); - // todo(mderka) add more to the doc when questions are answered by the service owner + // this should not be included in tooling as per the service owners /** * Sets a list of servers that hold the information about the zone. This information is provided @@ -155,7 +155,7 @@ public Builder description(String description) { } @Override - public Builder nameServerSet(String nameServerSet) { + Builder nameServerSet(String nameServerSet) { this.nameServerSet = checkNotNull(nameServerSet); return this; } @@ -227,10 +227,10 @@ public String description() { } /** - * Returns the optionally specified set of DNS name servers that all host this zone. + * Returns the optionally specified set of DNS name servers that all host this zone. This value is + * set only for specific use cases and is left empty for vast majority of users. */ public String nameServerSet() { - // todo(mderka) update this doc after finding out more about this from the service owners return nameServerSet; } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index 726a455418d8..89ad90f27654 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -83,7 +83,8 @@ public class DnsImplTest { // Listing options private static final Dns.ZoneListOption[] ZONE_LIST_OPTIONS = { Dns.ZoneListOption.pageSize(MAX_SIZE), Dns.ZoneListOption.pageToken(PAGE_TOKEN), - Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)}; + Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION), + Dns.ZoneListOption.dnsName(DNS_NAME)}; private static final Dns.ChangeRequestListOption[] CHANGE_LIST_OPTIONS = { Dns.ChangeRequestListOption.pageSize(MAX_SIZE), Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN), @@ -330,6 +331,8 @@ public void testListZonesWithOptions() { selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].rpcOption()); assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].rpcOption()); + assertEquals(DNS_NAME, selector); } @Test diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index 74faca329884..92a18ad9c1e7 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -27,6 +27,7 @@ public class DnsTest { private static final Integer PAGE_SIZE = 20; private static final String PAGE_TOKEN = "page token"; + private static final String DNS_NAME = "www.example.com."; @Test public void testDnsRecordListOption() { @@ -89,6 +90,10 @@ public void testZoneList() { option = Dns.ZoneListOption.pageSize(PAGE_SIZE); assertEquals(PAGE_SIZE, option.value()); assertEquals(DnsRpc.Option.PAGE_SIZE, option.rpcOption()); + // dnsName filter + option = Dns.ZoneListOption.dnsName(DNS_NAME); + assertEquals(DNS_NAME, option.value()); + assertEquals(DnsRpc.Option.DNS_NAME, option.rpcOption()); } @Test diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java new file mode 100644 index 000000000000..adf5744d854e --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -0,0 +1,118 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; + +import com.google.common.collect.ImmutableList; +import com.google.gcloud.RetryParams; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.math.BigInteger; +import java.util.concurrent.TimeUnit; + +public class SerializationTest { + + private static final ZoneInfo FULL_ZONE_INFO = Zone.builder("some zone name") + .creationTimeMillis(132L) + .description("some descriptions") + .dnsName("www.example.com") + .id("123333") + .nameServers(ImmutableList.of("server 1", "server 2")) + .nameServerSet("specificationstring") + .build(); + private static final ZoneInfo PARTIAL_ZONE_INFO = Zone.builder("some zone name") + .build(); + private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.builder().id("13").build(); + private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.builder() + .id("342") + .number(new BigInteger("2343245")) + .quota(new ProjectInfo.Quota(12, 13, 14, 15, 16, 17)) + .build(); + private static final Dns.ZoneListOption ZONE_LIST_OPTION = + Dns.ZoneListOption.dnsName("www.example.com."); + private static final Dns.DnsRecordListOption DNS_REOCRD_LIST_OPTION = + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL); + private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTION = + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS); + private static final Dns.ZoneOption ZONE_OPTION = + Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); + private static final Dns.ChangeRequestOption CHANGE_REQUEST_OPTION = + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS); + private static final Dns.ProjectOption PROJECT_OPTION = + Dns.ProjectOption.fields(Dns.ProjectField.QUOTA); + private static final DnsOptions OPTIONS = DnsOptions.builder() + .projectId("some-unnecessary-project-ID") + .retryParams(RetryParams.defaultInstance()) + .build(); + private static final Dns DNS = OPTIONS.service(); + private static final Zone FULL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(FULL_ZONE_INFO)); + private static final Zone PARTIAL_ZONE = + new Zone(DNS, new ZoneInfo.BuilderImpl(PARTIAL_ZONE_INFO)); + private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder().build(); + private static final DnsRecord DNS_RECORD_PARTIAL = + DnsRecord.builder("www.www.com", DnsRecord.Type.AAAA).build(); + private static final DnsRecord DNS_RECORD_COMPLETE = + DnsRecord.builder("www.sadfa.com", DnsRecord.Type.A) + .ttl(12, TimeUnit.HOURS) + .addRecord("record") + .build(); + private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() + .add(DNS_RECORD_COMPLETE) + .delete(DNS_RECORD_PARTIAL) + .status(ChangeRequest.Status.PENDING) + .id("some id") + .startTimeMillis(132L) + .build(); + + + @Test + public void testModelAndRequests() throws Exception { + Serializable[] objects = {FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, + DNS_REOCRD_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, + PROJECT_OPTION, PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, OPTIONS, FULL_ZONE, PARTIAL_ZONE, + OPTIONS, CHANGE_REQUEST_PARTIAL, DNS_RECORD_PARTIAL, DNS_RECORD_COMPLETE, + CHANGE_REQUEST_COMPLETE}; + for (Serializable obj : objects) { + Object copy = serializeAndDeserialize(obj); + assertEquals(obj, obj); + assertEquals(obj, copy); + assertNotSame(obj, copy); + assertEquals(copy, copy); + } + } + + @SuppressWarnings("unchecked") + private T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { + output.writeObject(obj); + } + try (ObjectInputStream input = + new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + return (T) input.readObject(); + } + } +} From a1ec7f46c9e4e53ad185039011f49113de48c53a Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 19 Feb 2016 10:32:17 -0800 Subject: [PATCH 50/74] Added local implementation of the service and tests. --- .../google/gcloud/testing/LocalDnsHelper.java | 1426 +++++++++++++++++ .../testing/OptionParsersAndExtractors.java | 279 ++++ .../gcloud/testing/LocalDnsHelperTest.java | 955 +++++++++++ 3 files changed, 2660 insertions(+) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java b/gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java new file mode 100644 index 000000000000..2d30cf9e5d90 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java @@ -0,0 +1,1426 @@ +/* + * 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.testing; + +import static com.google.common.base.Preconditions.checkNotNull; +import static java.net.HttpURLConnection.HTTP_NO_CONTENT; +import static java.net.HttpURLConnection.HTTP_OK; + +import com.google.api.client.json.JsonFactory; +import com.google.api.client.repackaged.com.google.common.base.Joiner; +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.Project; +import com.google.api.services.dns.model.Quota; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.base.Function; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.common.io.ByteStreams; +import com.google.gcloud.dns.DnsOptions; + +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +import org.joda.time.format.ISODateTimeFormat; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.NavigableSet; +import java.util.Objects; +import java.util.Random; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.zip.GZIPInputStream; + +import javax.annotation.Nullable; + +/** + * A utility to create local Google Cloud DNS mock. + * + *

The mock runs in a separate thread, listening for HTTP requests on the local machine at an + * ephemeral port. + * + *

While the mock attempts to simulate the service, there are some differences in the behaviour. + * The mock will accept any project ID and never returns a notFound or another error because of + * project ID. It assumes that all project IDs exists and that the user has all the necessary + * privileges to manipulate any project. Similarly, the local simulation does not work with any + * verification of domain name ownership. Any request for creating a managed zone will be approved. + * The mock does not track quota and will allow the user to exceed it. The mock provides only basic + * validation of the DNS data for records of type A and AAAA. It does not validate any other record + * types. + */ +public class LocalDnsHelper { + + private final ConcurrentSkipListMap projects + = new ConcurrentSkipListMap<>(); + private static final URI BASE_CONTEXT; + private static final Logger log = Logger.getLogger(LocalDnsHelper.class.getName()); + private static final JsonFactory jsonFactory = + new com.google.api.client.json.jackson.JacksonFactory(); + private static final Random ID_GENERATOR = new Random(); + private static final String VERSION = "v1"; + private static final String CONTEXT = "/" + VERSION + "/projects"; + private static final Set SUPPORTED_COMPRESSION_ENCODINGS = + ImmutableSet.of("gzip", "x-gzip"); + private static final List TYPES = ImmutableList.of("A", "AAAA", "CNAME", "MX", "NAPTR", + "NS", "PTR", "SOA", "SPF", "SRV", "TXT"); + + static { + try { + BASE_CONTEXT = new URI(CONTEXT); + } catch (URISyntaxException e) { + throw new RuntimeException( + "Could not initialize LocalDnsHelper due to URISyntaxException.", e); + } + } + + private long delayChange; + private final HttpServer server; + private final int port; + + /** + * For matching URLs to operations. + */ + private enum CallRegex { + CHANGE_CREATE("POST", "/[^/]+/managedZones/[^/]+/changes"), + CHANGE_GET("GET", "/[^/]+/managedZones/[^/]+/changes/[^/]+"), + CHANGE_LIST("GET", "/[^/]+/managedZones/[^/]+/changes"), + ZONE_CREATE("POST", "/[^/]+/managedZones"), + ZONE_DELETE("DELETE", "/[^/]+/managedZones/[^/]+"), + ZONE_GET("GET", "/[^/]+/managedZones/[^/]+"), + ZONE_LIST("GET", "/[^/]+/managedZones"), + PROJECT_GET("GET", "/[^/]+"), + RECORD_LIST("GET", "/[^/]+/managedZones/[^/]+/rrsets"); + + private String method; + private String pathRegex; + + CallRegex(String method, String pathRegex) { + this.pathRegex = pathRegex; + this.method = method; + } + } + + /** + * Wraps DNS data by adding a timestamp and id which is used for paging and listing. + */ + static class RrsetWrapper { + static final Function WRAP_FUNCTION = + new Function() { + @Nullable + @Override + public RrsetWrapper apply(@Nullable ResourceRecordSet input) { + return new RrsetWrapper(input); + } + }; + private final ResourceRecordSet rrset; + private final Long timestamp = System.currentTimeMillis(); + private String id; + + RrsetWrapper(ResourceRecordSet rrset) { + // The constructor creates a copy in order to prevent side effects. + this.rrset = new ResourceRecordSet(); + this.rrset.setName(rrset.getName()); + this.rrset.setTtl(rrset.getTtl()); + this.rrset.setRrdatas(ImmutableList.copyOf(rrset.getRrdatas())); + this.rrset.setType(rrset.getType()); + } + + void setId(String id) { + this.id = id; + } + + String id() { + return id; + } + + /** + * Equals does not care about the listing id and timestamp metadata, just the rrset. + */ + @Override + public boolean equals(Object other) { + return (other instanceof RrsetWrapper) && Objects.equals(rrset, ((RrsetWrapper) other).rrset); + } + + @Override + public int hashCode() { + return Objects.hash(rrset); + } + + ResourceRecordSet rrset() { + return rrset; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("rrset", rrset) + .add("timestamp", timestamp) + .add("id", id) + .toString(); + } + } + + /** + * Associates a project with a collection of ManagedZones. Thread safe. + */ + static class ProjectContainer { + private final Project project; + private final ConcurrentSkipListMap zones = + new ConcurrentSkipListMap<>(); + + ProjectContainer(Project project) { + this.project = project; + } + + Project project() { + return project; + } + + ConcurrentSkipListMap zones() { + return zones; + } + } + + /** + * Associates a zone with a collection of changes and dns record. Thread safe. + */ + static class ZoneContainer { + private final ManagedZone zone; + /** + * DNS records are held in a map to allow for atomic replacement of record sets when applying + * changes. The key for the map is always the zone name. The collection of records is immutable + * and must always exist, i.e., dnsRecords.get(zone.getName()) is never null. + */ + private final ConcurrentSkipListMap> + dnsRecords = new ConcurrentSkipListMap<>(); + private final ConcurrentLinkedQueue changes = new ConcurrentLinkedQueue<>(); + + ZoneContainer(ManagedZone zone) { + this.zone = zone; + this.dnsRecords.put(zone.getName(), ImmutableList.of()); + } + + ManagedZone zone() { + return zone; + } + + ConcurrentSkipListMap> dnsRecords() { + return dnsRecords; + } + + ConcurrentLinkedQueue changes() { + return changes; + } + + Change findChange(String changeId) { + for (Change current : changes) { + if (changeId.equals(current.getId())) { + return current; + } + } + return null; + } + } + + static class Response { + private final int code; + private final String body; + + Response(int code, String body) { + this.code = code; + this.body = body; + } + + int code() { + return code; + } + + String body() { + return body; + } + } + + private enum Error { + REQUIRED(400, "global", "required", "REQUIRED"), + INTERNAL_ERROR(500, "global", "internalError", "INTERNAL_ERROR"), + BAD_REQUEST(400, "global", "badRequest", "BAD_REQUEST"), + INVALID(400, "global", "invalid", "INVALID"), + NOT_AVAILABLE(400, "global", "managedZoneDnsNameNotAvailable", "NOT_AVAILABLE"), + NOT_FOUND(404, "global", "notFound", "NOT_FOUND"), + ALREADY_EXISTS(409, "global", "alreadyExists", "ALREADY_EXISTS"), + CONDITION_NOT_MET(412, "global", "conditionNotMet", "CONDITION_NOT_MET"), + INVALID_ZONE_APEX(400, "global", "invalidZoneApex", "INVALID_ZONE_APEX"); + + private final int code; + private final String domain; + private final String reason; + private final String status; + + Error(int code, String domain, String reason, String status) { + this.code = code; + this.domain = domain; + this.reason = reason; + this.status = status; + } + + Response response(String message) { + try { + return new Response(code, toJson(message)); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response("Error when generating JSON error response."); + } + } + + private String toJson(String message) throws IOException { + Map errors = new HashMap<>(); + errors.put("domain", domain); + errors.put("message", message); + errors.put("reason", reason); + Map args = new HashMap<>(); + args.put("errors", ImmutableList.of(errors)); + args.put("code", code); + args.put("message", message); + args.put("status", status); + return jsonFactory.toString(ImmutableMap.of("error", args)); + } + } + + private class RequestHandler implements HttpHandler { + + /** + * Chooses the proper handler for a request. + */ + private Response pickHandler(HttpExchange exchange, CallRegex regex) { + switch (regex) { + case CHANGE_GET: + return handleChangeGet(exchange); + case CHANGE_LIST: + return handleChangeList(exchange); + case ZONE_GET: + return handleZoneGet(exchange); + case ZONE_DELETE: + return handleZoneDelete(exchange); + case ZONE_LIST: + return handleZoneList(exchange); + case PROJECT_GET: + return handleProjectGet(exchange); + case RECORD_LIST: + return handleDnsRecordList(exchange); + case ZONE_CREATE: + try { + return handleZoneCreate(exchange); + } catch (IOException ex) { + return Error.BAD_REQUEST.response(ex.getMessage()); + } + case CHANGE_CREATE: + try { + return handleChangeCreate(exchange); + } catch (IOException ex) { + return Error.BAD_REQUEST.response(ex.getMessage()); + } + default: + return Error.INTERNAL_ERROR.response("Operation without a handler."); + } + } + + @Override + public void handle(HttpExchange exchange) throws IOException { + String requestMethod = exchange.getRequestMethod(); + String rawPath = exchange.getRequestURI().getRawPath(); + for (CallRegex regex : CallRegex.values()) { + if (requestMethod.equals(regex.method) && rawPath.matches(regex.pathRegex)) { + // there is a match, pass the handling accordingly + Response response = pickHandler(exchange, regex); + writeResponse(exchange, response); + return; // only one match is possible + } + } + // could not be matched, the service returns 404 page not found here + writeResponse(exchange, Error.NOT_FOUND.response("The url does not match any API call.")); + } + + // todo(mderka) Test handlers using gcloud-java-dns. Issue #665. + private Response handleZoneDelete(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String zoneName = tokens[3]; + return deleteZone(projectId, zoneName); + } + + private Response handleZoneGet(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String zoneName = tokens[3]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + String[] fields = OptionParsersAndExtractors.parseGetOptions(query); + return getZone(projectId, zoneName, fields); + } + + private Response handleZoneList(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + Map options = OptionParsersAndExtractors.parseListZonesOptions(query); + return listZones(projectId, options); + } + + private Response handleProjectGet(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + String[] fields = OptionParsersAndExtractors.parseGetOptions(query); + return getProject(projectId, fields); + } + + /** + * @throws IOException if the request cannot be parsed. + */ + private Response handleChangeCreate(HttpExchange exchange) throws IOException { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String zoneName = tokens[3]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + String[] fields = OptionParsersAndExtractors.parseGetOptions(query); + String requestBody = decodeContent(exchange.getRequestHeaders(), exchange.getRequestBody()); + Change change = jsonFactory.fromString(requestBody, Change.class); + return createChange(projectId, zoneName, change, fields); + } + + private Response handleChangeGet(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String zoneName = tokens[3]; + String changeId = tokens[5]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + String[] fields = OptionParsersAndExtractors.parseGetOptions(query); + return getChange(projectId, zoneName, changeId, fields); + } + + private Response handleChangeList(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String zoneName = tokens[3]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + Map options = OptionParsersAndExtractors.parseListChangesOptions(query); + return listChanges(projectId, zoneName, options); + } + + private Response handleDnsRecordList(HttpExchange exchange) { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String zoneName = tokens[3]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + Map options = OptionParsersAndExtractors.parseListDnsRecordsOptions(query); + return listDnsRecords(projectId, zoneName, options); + } + + /** + * @throws IOException if the request cannot be parsed. + */ + private Response handleZoneCreate(HttpExchange exchange) throws IOException { + String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); + String[] tokens = path.split("/"); + String projectId = tokens[1]; + String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); + String[] options = OptionParsersAndExtractors.parseGetOptions(query); + String requestBody = decodeContent(exchange.getRequestHeaders(), exchange.getRequestBody()); + ManagedZone zone; + try { + // IllegalArgumentException if the request body is an empty string + zone = jsonFactory.fromString(requestBody, ManagedZone.class); + } catch (IllegalArgumentException ex) { + return Error.REQUIRED.response( + "The 'entity.managedZone' parameter is required but was missing."); + } + return createZone(projectId, zone, options); + } + } + + private LocalDnsHelper(long delay) { + this.delayChange = delay; // 0 makes this synchronous + try { + server = HttpServer.create(new InetSocketAddress(0), 0); + port = server.getAddress().getPort(); + server.createContext(CONTEXT, new RequestHandler()); + } catch (IOException e) { + throw new RuntimeException("Could not bind the mock DNS server.", e); + } + } + + /** + * Accessor for testing purposes. + */ + ConcurrentSkipListMap projects() { + return projects; + } + + /** + * Creates new {@link LocalDnsHelper} instance that listens to requests on the local machine. This + * instance processes changes separate threads. The parameter determines how long a thread should + * wait before processing a change. If it is set to 0, the threading is turned off and the mock + * will behave synchronously. + * + * @param delay delay for processing changes in ms or 0 for synchronous processing + */ + public static LocalDnsHelper create(Long delay) { + return new LocalDnsHelper(delay); + } + + /** + * Returns a DnsOptions instance that sets the host to use the mock server. + */ + public DnsOptions options() { + return DnsOptions.builder().host("http://localhost:" + port).build(); + } + + /** + * Starts the thread that runs the local DNS server. + */ + public void start() { + server.start(); + } + + /** + * Stops the thread that runs the mock DNS server. + */ + public void stop() { + server.stop(1); + } + + private static void writeResponse(HttpExchange exchange, Response response) { + exchange.getResponseHeaders().set("Content-type", "application/json; charset=UTF-8"); + OutputStream outputStream = exchange.getResponseBody(); + try { + exchange.getResponseHeaders().add("Connection", "close"); + exchange.sendResponseHeaders(response.code(), response.body().length()); + outputStream.write(response.body().getBytes(StandardCharsets.UTF_8)); + outputStream.close(); + } catch (IOException e) { + log.log(Level.WARNING, "IOException encountered when sending response.", e); + } + } + + /** + * Decodes content of the HttpRequest. + */ + private static String decodeContent(Headers headers, InputStream inputStream) throws IOException { + List contentEncoding = headers.get("Content-encoding"); + InputStream input = inputStream; + try { + if (contentEncoding != null && !contentEncoding.isEmpty()) { + String encoding = contentEncoding.get(0); + if (SUPPORTED_COMPRESSION_ENCODINGS.contains(encoding)) { + input = new GZIPInputStream(inputStream); + } else if (!encoding.equals("identity")) { + throw new IOException( + "The request has the following unsupported HTTP content encoding: " + encoding); + } + } + return new String(ByteStreams.toByteArray(input), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IOException("Exception encountered when decoding request content.", e); + } + } + + /** + * Generates a JSON response. Tested. + */ + static Response toListResponse(List serializedObjects, String pageToken, + boolean includePageToken) { + // start building response + StringBuilder responseBody = new StringBuilder(); + responseBody.append("{\"projects\": ["); + Joiner.on(",").appendTo(responseBody, serializedObjects); + responseBody.append("]"); + // add page token only if exists and is asked for + if (pageToken != null && includePageToken) { + responseBody.append(",\"pageToken\": \"").append(pageToken).append("\""); + } + responseBody.append("}"); + return new Response(HTTP_OK, responseBody.toString()); + } + + /** + * Prepares DNS records that are created by default for each zone. + */ + private static ImmutableList defaultRecords(ManagedZone zone) { + ResourceRecordSet soa = new ResourceRecordSet(); + soa.setTtl(21600); + soa.setName(zone.getDnsName()); + soa.setRrdatas(ImmutableList.of( + // taken from the service + "ns-cloud-c1.googledomains.com. cloud-dns-hostmaster.google.com. 0 21600 3600 1209600 312" + )); + soa.setType("SOA"); + ResourceRecordSet ns = new ResourceRecordSet(); + ns.setTtl(21600); + ns.setName(zone.getDnsName()); + ns.setRrdatas(zone.getNameServers()); + ns.setType("NS"); + RrsetWrapper nsWrapper = new RrsetWrapper(ns); + RrsetWrapper soaWrapper = new RrsetWrapper(soa); + ImmutableList results = ImmutableList.of(nsWrapper, soaWrapper); + nsWrapper.setId(getUniqueId(results)); + soaWrapper.setId(getUniqueId(results)); + return results; + } + + /** + * Returns a list of four nameservers randomly chosen from the predefined set. + */ + static List randomNameservers() { + ArrayList nameservers = Lists.newArrayList( + "dns1.googlecloud.com", "dns2.googlecloud.com", "dns3.googlecloud.com", + "dns4.googlecloud.com", "dns5.googlecloud.com", "dns6.googlecloud.com" + ); + while (nameservers.size() != 4) { + int index = ID_GENERATOR.nextInt(nameservers.size()); + nameservers.remove(index); + } + return nameservers; + } + + /** + * Returns a hex string id (used for a dns record) unique withing the set of wrappers. + */ + static String getUniqueId(List wrappers) { + TreeSet ids = Sets.newTreeSet(Lists.transform(wrappers, + new Function() { + @Nullable + @Override + public String apply(@Nullable RrsetWrapper input) { + return input.id() == null ? "null" : input.id(); + } + })); + String id; + do { + id = Long.toHexString(System.currentTimeMillis()) + + Long.toHexString(Math.abs(ID_GENERATOR.nextLong())); + if (!ids.contains(id)) { + return id; + } + } while (ids.contains(id)); + return id; + } + + /** + * Tests if a DNS record matches name and type (if provided). Used for filtering. + */ + static boolean matchesCriteria(ResourceRecordSet record, String name, String type) { + if (type != null && !record.getType().equals(type)) { + return false; + } + if (name != null && !record.getName().equals(name)) { + return false; + } + return true; + } + + /** + * Returns a project container. Never returns null because we assume that all projects exists. + */ + ProjectContainer findProject(String projectId) { + ProjectContainer defaultProject = createProject(projectId); + projects.putIfAbsent(projectId, defaultProject); + return projects.get(projectId); + } + + /** + * Returns a zone container. Returns null if zone does not exist within project. + */ + ZoneContainer findZone(String projectId, String zoneName) { + ProjectContainer projectContainer = findProject(projectId); // never null + return projectContainer.zones().get(zoneName); + } + + /** + * Returns a change found by its id. Returns null if such a change does not exist. + */ + Change findChange(String projectId, String zoneName, String changeId) { + ZoneContainer wrapper = findZone(projectId, zoneName); + return wrapper == null ? null : wrapper.findChange(changeId); + } + + /** + * Returns a response to get change call. + */ + Response getChange(String projectId, String zoneName, String changeId, String[] fields) { + Change change = findChange(projectId, zoneName, changeId); + if (change == null) { + ZoneContainer zone = findZone(projectId, zoneName); + if (zone == null) { + // zone does not exist + return Error.NOT_FOUND.response(String.format( + "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)); + } + // zone exists but change does not + return Error.NOT_FOUND.response(String.format( + "The 'parameters.changeId' resource named '%s' does not exist.", changeId)); + } + Change result = OptionParsersAndExtractors.extractFields(change, fields); + try { + return new Response(HTTP_OK, jsonFactory.toString(result)); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing change %s in managed zone %s in project %s.", + changeId, zoneName, projectId)); + } + // todo(mderka) Test field options within #665. + } + + /** + * Returns a response to get zone call. + */ + Response getZone(String projectId, String zoneName, String[] fields) { + ZoneContainer container = findZone(projectId, zoneName); + if (container == null) { + return Error.NOT_FOUND.response(String.format( + "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)); + } + ManagedZone result = OptionParsersAndExtractors.extractFields(container.zone(), fields); + try { + return new Response(HTTP_OK, jsonFactory.toString(result)); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing managed zone %s in project %s.", zoneName, projectId)); + } + // todo(mderka) Test field options within #665. + } + + /** + * We assume that every project exists. If we do not have it in the collection yet, we just create + * a new default project instance with default quota. + */ + Response getProject(String projectId, String[] fields) { + ProjectContainer defaultProject = createProject(projectId); + projects.putIfAbsent(projectId, defaultProject); + Project project = projects.get(projectId).project(); // project is now guaranteed to exist + Project result = OptionParsersAndExtractors.extractFields(project, fields); + try { + return new Response(HTTP_OK, jsonFactory.toString(result)); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response( + String.format("Error when serializing project %s.", projectId)); + } + // todo(mderka) Test field options within #665. + } + + /** + * Creates a project. It generates a project number randomly (we do not have project numbers + * available). + */ + private ProjectContainer createProject(String projectId) { + Quota quota = new Quota(); + quota.setManagedZones(10000); + quota.setRrsetsPerManagedZone(10000); + quota.setRrsetAdditionsPerChange(100); + quota.setRrsetDeletionsPerChange(100); + quota.setTotalRrdataSizePerChange(10000); + quota.setResourceRecordsPerRrset(100); + Project project = new Project(); + project.setId(projectId); + project.setNumber(new BigInteger(String.valueOf( + Math.abs(ID_GENERATOR.nextLong() % Long.MAX_VALUE)))); + project.setQuota(quota); + return new ProjectContainer(project); + } + + /** + * Deletes a zone. + */ + Response deleteZone(String projectId, String zoneName) { + ProjectContainer projectContainer = projects.get(projectId); + ZoneContainer previous = projectContainer.zones.remove(zoneName); + return previous == null + // map was not in the collection + ? Error.NOT_FOUND.response(String.format( + "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)) + : new Response(HTTP_NO_CONTENT, "{}"); + } + + /** + * Creates new managed zone and stores it in the collection. Assumes that project exists. + */ + Response createZone(String projectId, ManagedZone zone, String[] fields) { + checkNotNull(zone, "Zone to create cannot be null"); + // check if the provided data is valid + Response errorResponse = checkZone(zone); + if (errorResponse != null) { + return errorResponse; + } + // create a copy of the managed zone in order to avoid side effects + ManagedZone completeZone = new ManagedZone(); + completeZone.setName(zone.getName()); + completeZone.setDnsName(zone.getDnsName()); + completeZone.setNameServerSet(zone.getNameServerSet()); + completeZone.setCreationTime(ISODateTimeFormat.dateTime().withZoneUTC() + .print(System.currentTimeMillis())); + completeZone.setId( + new BigInteger(String.valueOf(Math.abs(ID_GENERATOR.nextLong() % Long.MAX_VALUE)))); + completeZone.setNameServers(randomNameservers()); + ZoneContainer zoneContainer = new ZoneContainer(completeZone); + // create the default NS and SOA records + zoneContainer.dnsRecords().put(zone.getName(), defaultRecords(completeZone)); + // place the zone in the data collection + ProjectContainer projectContainer = findProject(projectId); + ZoneContainer oldValue = projectContainer.zones().putIfAbsent( + completeZone.getName(), zoneContainer); + if (oldValue != null) { + return Error.ALREADY_EXISTS.response(String.format( + "The resource 'entity.managedZone' named '%s' already exists", completeZone.getName())); + } + // now return the desired attributes + ManagedZone result = OptionParsersAndExtractors.extractFields(completeZone, fields); + try { + return new Response(HTTP_OK, jsonFactory.toString(result)); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response( + String.format("Error when serializing managed zone %s.", result.getName())); + } + // todo(mderka) Test field options within #665. + } + + /** + * Creates a new change, stores it, and invokes processing in a new thread. + */ + Response createChange(String projectId, String zoneName, Change change, String[] fields) { + ZoneContainer zoneContainer = findZone(projectId, zoneName); + if (zoneContainer == null) { + return Error.NOT_FOUND.response(String.format( + "The 'parameters.managedZone' resource named %s does not exist.", zoneName)); + } + // check that the change to be applied is valid + Response response = checkChange(change, zoneContainer); + if (response != null) { + return response; + } + // start applying + Change completeChange = new Change(); // copy to avoid side effects + if (change.getAdditions() != null) { + completeChange.setAdditions(ImmutableList.copyOf(change.getAdditions())); + } + if (change.getDeletions() != null) { + completeChange.setDeletions(ImmutableList.copyOf(change.getDeletions())); + } + /* we need to get the proper ID in concurrent environment + the element fell on an index between 0 and maxId + we will reset all IDs in this range (all of them are valid) */ + ConcurrentLinkedQueue changeSequence = zoneContainer.changes(); + changeSequence.add(completeChange); + int maxId = changeSequence.size(); + int index = 0; + for (Change c : changeSequence) { + if (index == maxId) { + break; + } + c.setId(String.valueOf(++index)); // indexing from 1 + } + completeChange.setStatus("pending"); // not finished yet + completeChange.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC() + .print(System.currentTimeMillis())); // accepted + invokeChange(projectId, zoneName, completeChange.getId()); + Change result = OptionParsersAndExtractors.extractFields(completeChange, fields); + try { + return new Response(HTTP_OK, jsonFactory.toString(result)); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response( + String.format("Error when serializing change %s in managed zone %s in project %s.", + result.getId(), zoneName, projectId)); + } + // todo(mderka) Test field options within #665. + } + + /** + * Applies change. Uses a new thread which applies the change only if DELAY_CHANGE is > 0. + */ + private Thread invokeChange(final String projectId, final String zoneName, + final String changeId) { + if (delayChange > 0) { + Thread thread = new Thread() { + @Override + public void run() { + try { + Thread.sleep(delayChange); // simulate delayed execution + } catch (InterruptedException ex) { + log.log(Level.WARNING, "Thread was interrupted while sleeping.", ex); + } + // start applying the changes + applyExistingChange(projectId, zoneName, changeId); + } + }; + thread.start(); + return thread; + } else { + applyExistingChange(projectId, zoneName, changeId); + return null; + } + } + + /** + * Applies changes to a zone. Repeatedly tries until succeeds. Thread safe and deadlock safe. + */ + private void applyExistingChange(String projectId, String zoneName, String changeId) { + Change change = findChange(projectId, zoneName, changeId); + if (change == null) { + return; // no such change exists, nothing to do + } + ZoneContainer wrapper = findZone(projectId, zoneName); + ConcurrentSkipListMap> dnsRecords = wrapper.dnsRecords(); + while (true) { + // managed zone must have a set of records which is not null + ImmutableList original = dnsRecords.get(zoneName); + assert original != null; + List copy = Lists.newLinkedList(original); + // apply deletions first + List deletions = change.getDeletions(); + if (deletions != null) { + List transformedDeletions = Lists.transform(deletions, + RrsetWrapper.WRAP_FUNCTION); + copy.removeAll(transformedDeletions); + } + // apply additions + List additions = change.getAdditions(); + if (additions != null) { + for (ResourceRecordSet addition : additions) { + String id = getUniqueId(copy); + RrsetWrapper rrsetWrapper = new RrsetWrapper(addition); + rrsetWrapper.setId(id); + copy.add(rrsetWrapper); + } + } + // make it immutable and replace + boolean success = dnsRecords.replace(zoneName, original, ImmutableList.copyOf(copy)); + if (success) { + break; // success if no other thread modified the value in the meantime + } + } + // set status to done + change.setStatus("done"); + } + + /** + * Lists zones. Next page token is the last listed zone name and is returned only of there is more + * to list. + */ + Response listZones(String projectId, Map options) { + Response response = checkListOptions(options); + if (response != null) { + return response; + } + ConcurrentSkipListMap containers = findProject(projectId).zones(); + String[] fields = (String[]) options.get("fields"); + String dnsName = (String) options.get("dnsName"); + String pageToken = (String) options.get("pageToken"); + Integer maxResults = options.get("maxResults") == null + ? null : Integer.valueOf((String) options.get("maxResults")); + // matches will be included in the result if true + boolean listing = (pageToken == null || !containers.containsKey(pageToken)); + boolean sizeReached = false; // maximum result size was reached, we should not return more + boolean hasMorePages = false; // should next page token be included in the response? + LinkedList serializedZones = new LinkedList<>(); + String lastZoneName = null; + for (ZoneContainer zoneContainer : containers.values()) { + ManagedZone zone = zoneContainer.zone(); + if (listing) { + if (dnsName == null || zone.getDnsName().equals(dnsName)) { + lastZoneName = zone.getName(); + if (sizeReached) { + // we do not add this, just note that there would be more and there should be a token + hasMorePages = true; + break; + } else { + try { + serializedZones.addLast(jsonFactory.toString( + OptionParsersAndExtractors.extractFields(zone, fields))); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing managed zone %s in project %s", zone.getName(), + projectId)); + } + } + } + } + // either we are listing already, or we check if we should start in the next iteration + listing = zone.getName().equals(pageToken) || listing; + sizeReached = (maxResults != null) && maxResults.equals(serializedZones.size()); + } + boolean includePageToken = + hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("pageToken")); + return toListResponse(serializedZones, lastZoneName, includePageToken); + // todo(mderka) Test field and listing options within #665. + } + + /** + * Lists DNS records for a zone. Next page token is ID of the last record listed. + */ + Response listDnsRecords(String projectId, String zoneName, Map options) { + Response response = checkListOptions(options); + if (response != null) { + return response; + } + ZoneContainer zoneContainer = findZone(projectId, zoneName); + if (zoneContainer == null) { + return Error.NOT_FOUND.response(String.format( + "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)); + } + List dnsRecords = zoneContainer.dnsRecords().get(zoneName); + String[] fields = (String[]) options.get("fields"); + String name = (String) options.get("name"); + String type = (String) options.get("type"); + String pageToken = (String) options.get("pageToken"); + Integer maxResults = options.get("maxResults") == null + ? null : Integer.valueOf((String) options.get("maxResults")); + boolean listing = (pageToken == null); // matches will be included in the result if true + boolean sizeReached = false; // maximum result size was reached, we should not return more + boolean hasMorePages = false; // should next page token be included in the response? + LinkedList serializedRrsets = new LinkedList<>(); + String lastRecordId = null; + for (RrsetWrapper recordWrapper : dnsRecords) { + ResourceRecordSet record = recordWrapper.rrset(); + if (listing) { + if (matchesCriteria(record, name, type)) { + lastRecordId = recordWrapper.id(); + if (sizeReached) { + // we do not add this, just note that there would be more and there should be a token + hasMorePages = true; + break; + } else { + try { + serializedRrsets.addLast(jsonFactory.toString( + OptionParsersAndExtractors.extractFields(record, fields))); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing resource record set in managed zone %s in project %s", + zoneName, projectId)); + } + } + } + } + // either we are listing already, or we check if we should start in the next iteration + listing = recordWrapper.id().equals(pageToken) || listing; + sizeReached = (maxResults != null) && maxResults.equals(serializedRrsets.size()); + } + boolean includePageToken = + hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("pageToken")); + return toListResponse(serializedRrsets, lastRecordId, includePageToken); + // todo(mderka) Test field and listing options within #665. + } + + /** + * Lists changes. Next page token is ID of the last change listed. + */ + Response listChanges(String projectId, String zoneName, Map options) { + Response response = checkListOptions(options); + if (response != null) { + return response; + } + ZoneContainer zoneContainer = findZone(projectId, zoneName); + // take a sorted snapshot of the current change list + TreeMap changes = new TreeMap<>(); + for (Change c : zoneContainer.changes()) { + if (c.getId() != null) { + changes.put(Integer.valueOf(c.getId()), c); + } + } + String[] fields = (String[]) options.get("fields"); + String sortOrder = (String) options.get("sortOrder"); + String pageToken = (String) options.get("pageToken"); + Integer maxResults = options.get("maxResults") == null + ? null : Integer.valueOf((String) options.get("maxResults")); + // we are not reading sort by as it the only key is the change sequence + NavigableSet keys; + if ("descending".equals(sortOrder)) { + keys = changes.descendingKeySet(); + } else { + keys = changes.navigableKeySet(); + } + boolean listing = (pageToken == null); // matches will be included in the result if true + boolean sizeReached = false; // maximum result size was reached, we should not return more + boolean hasMorePages = false; // should next page token be included in the response? + LinkedList serializedResults = new LinkedList<>(); + String lastChangeId = null; + for (Integer key : keys) { + Change change = changes.get(key); + if (listing) { + lastChangeId = change.getId(); + if (sizeReached) { + // we do not add this, just note that there would be more and there should be a token + hasMorePages = true; + break; + } else { + try { + serializedResults.addLast(jsonFactory.toString( + OptionParsersAndExtractors.extractFields(change, fields))); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing change %s in managed zone %s in project %s", + change.getId(), zoneName, projectId)); + } + } + } + + // either we are listing already, or we check if we should start in the next iteration + listing = change.getId().equals(pageToken) || listing; + sizeReached = (maxResults != null) && maxResults.equals(serializedResults.size()); + } + boolean includePageToken = + hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("pageToken")); + return toListResponse(serializedResults, lastChangeId, includePageToken); + // todo(mderka) Test field and listing options within #665. + } + + /** + * Validates a zone to be created. + */ + static Response checkZone(ManagedZone zone) { + if (zone.getName() == null) { + return Error.REQUIRED.response( + "The 'entity.managedZone.name' parameter is required but was missing."); + } + if (zone.getDnsName() == null) { + return Error.REQUIRED.response( + "The 'entity.managedZone.dnsName' parameter is required but was missing."); + } + if (zone.getDescription() == null) { + return Error.REQUIRED.response( + "The 'entity.managedZone.description' parameter is required but was missing."); + } + try { + int number = Integer.valueOf(zone.getName()); + return Error.INVALID.response( + String.format("Invalid value for 'entity.managedZone.name': '%s'", number)); + } catch (NumberFormatException ex) { + // expected + } + if (zone.getName().isEmpty()) { + return Error.INVALID.response( + String.format("Invalid value for 'entity.managedZone.name': '%s'", zone.getName())); + } + if (zone.getDnsName().isEmpty() || !zone.getDnsName().endsWith(".")) { + return Error.INVALID.response( + String.format("Invalid value for 'entity.managedZone.dnsName': '%s'", zone.getDnsName())); + } + TreeSet forbidden = Sets.newTreeSet( + ImmutableList.of("google.com.", "com.", "example.com.", "net.", "org.")); + if (forbidden.contains(zone.getDnsName())) { + return Error.NOT_AVAILABLE.response(String.format( + "The '%s' managed zone is not available to be created.", zone.getDnsName())); + } + return null; + } + + /** + * Validates a change to be created. + */ + static Response checkChange(Change change, ZoneContainer zone) { + checkNotNull(zone); + if ((change.getDeletions() != null && change.getDeletions().size() > 0) + || (change.getAdditions() != null && change.getAdditions().size() > 0)) { + // ok, this is what we want + } else { + return Error.REQUIRED.response("The 'entity.change' parameter is required but was missing."); + } + if (change.getAdditions() != null) { + int counter = 0; + for (ResourceRecordSet addition : change.getAdditions()) { + Response response = checkRrset(addition, zone, counter, "additions"); + if (response != null) { + return response; + } + counter++; + } + } + if (change.getDeletions() != null) { + int counter = 0; + for (ResourceRecordSet deletion : change.getDeletions()) { + Response response = checkRrset(deletion, zone, counter, "deletions"); + if (response != null) { + return response; + } + counter++; + } + } + return additionsMeetDeletions(change.getAdditions(), change.getDeletions(), zone); + // null if everything is ok + } + + /** + * Checks a rrset within a change. + * + * @param type [additions|deletions] + * @param index the index or addition or deletion in the list + * @param zone the zone that this change is applied to + */ + static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int index, String type) { + if (rrset.getName() == null || !rrset.getName().endsWith(zone.zone().getDnsName())) { + return Error.INVALID.response(String.format( + "Invalid value for 'entity.change.%s[%s].name': '%s'", type, index, rrset.getName())); + } + if (rrset.getType() == null || !TYPES.contains(rrset.getType())) { + return Error.INVALID.response(String.format( + "Invalid value for 'entity.change.%s[%s].type': '%s'", type, index, rrset.getType())); + } + if (rrset.getTtl() != null && rrset.getTtl() != 0 && rrset.getTtl() < 0) { + return Error.INVALID.response(String.format( + "Invalid value for 'entity.change.%s[%s].ttl': '%s'", type, index, rrset.getTtl())); + } + if (rrset.getRrdatas() == null || rrset.isEmpty()) { + return Error.INVALID.response(String.format( + "Invalid value for 'entity.change.%s[%s].rrdata': '%s'", type, index, "")); + } + int counter = 0; + for (String record : rrset.getRrdatas()) { + if (!checkRrData(record, rrset.getType())) { + return Error.INVALID.response(String.format( + "Invalid value for 'entity.change.%s[%s].rrdata[%s]': '%s'", + type, index, counter, record)); + } + counter++; + } + if ("deletions".equals(type)) { + // check that deletion has a match by name and type + boolean found = false; + for (RrsetWrapper rrsetWrapper : zone.dnsRecords().get(zone.zone().getName())) { + ResourceRecordSet wrappedRrset = rrsetWrapper.rrset(); + if (rrset.getName().equals(wrappedRrset.getName()) + && rrset.getType().equals(wrappedRrset.getType())) { + found = true; + break; + } + } + if (!found) { + return Error.NOT_FOUND.response(String.format( + "The 'entity.change.deletions[%s]' resource named '%s (%s)' does not exist.", + index, rrset.getName(), rrset.getType())); + } + // if found, we still need an exact match + if ("deletions".equals(type) + && !zone.dnsRecords().get(zone.zone().getName()).contains(new RrsetWrapper(rrset))) { + // such a record does not exist + return Error.CONDITION_NOT_MET.response(String.format( + "Precondition not met for 'entity.change.deletions[%s]", index)); + } + } + return null; + } + + /** + * Checks that for each record that already exists, we have a matching deletion. Furthermore, + * check that mandatory SOA and NS records stay. + */ + static Response additionsMeetDeletions(List additions, + List deletions, ZoneContainer zone) { + if (additions != null) { + int index = 0; + for (ResourceRecordSet rrset : additions) { + for (RrsetWrapper wrapper : zone.dnsRecords().get(zone.zone().getName())) { + ResourceRecordSet wrappedRrset = wrapper.rrset(); + if (rrset.getName().equals(wrappedRrset.getName()) + && rrset.getType().equals(wrappedRrset.getType())) { + // such a record exist and we must have a deletion + if (deletions == null || !deletions.contains(wrappedRrset)) { + return Error.ALREADY_EXISTS.response(String.format( + "The 'entity.change.additions[%s]' resource named '%s (%s)' already exists.", + index, rrset.getName(), rrset.getType())); + } + } + } + if (rrset.getType().equals("SOA") && findByNameAndType(deletions, null, "SOA") == null) { + return Error.INVALID_ZONE_APEX.response(String.format("The resource record set 'entity" + + ".change.additions[%s]' is invalid because a zone must contain exactly one resource" + + " record set of type 'SOA' at the apex.", index)); + } + if (rrset.getType().equals("NS") && findByNameAndType(deletions, null, "NS") == null) { + return Error.INVALID_ZONE_APEX.response(String.format("The resource record set 'entity" + + ".change.additions[%s]' is invalid because a zone must contain exactly one resource" + + " record set of type 'NS' at the apex.", index)); + } + index++; + } + } + if (deletions != null) { + int index = 0; + for (ResourceRecordSet rrset : deletions) { + if (rrset.getType().equals("SOA") && findByNameAndType(additions, null, "SOA") == null) { + return Error.INVALID_ZONE_APEX.response(String.format("The resource record set 'entity" + + ".change.deletions[%s]' is invalid because a zone must contain exactly one resource" + + " record set of type 'SOA' at the apex.", index)); + } + if (rrset.getType().equals("NS") && findByNameAndType(additions, null, "NS") == null) { + return Error.INVALID_ZONE_APEX.response(String.format("The resource record set 'entity" + + ".change.deletions[%s]' is invalid because a zone must contain exactly one resource" + + " record set of type 'NS' at the apex.", index)); + } + index++; + } + } + return null; + } + + /** + * Helper for searching rrsets in a collection. + */ + private static ResourceRecordSet findByNameAndType(Iterable records, + String name, String type) { + if (records != null) { + for (ResourceRecordSet rrset : records) { + if ((name == null || name.equals(rrset.getName())) + && (type == null || type.equals(rrset.getType()))) { + return rrset; + } + } + } + return null; + } + + /** + * We only provide the most basic validation for A and AAAA records. + */ + static boolean checkRrData(String data, String type) { + // todo add validation for other records + String[] tokens; + switch (type) { + case "A": + tokens = data.split("\\."); + if (tokens.length != 4) { + return false; + } + for (String token : tokens) { + try { + Integer number = Integer.valueOf(token); + if (number < 0 || number > 255) { + return false; + } + } catch (NumberFormatException ex) { + return false; + } + } + return true; + case "AAAA": + tokens = data.split(":", -1); + if (tokens.length != 8) { + return false; + } + for (String token : tokens) { + try { + if (!token.isEmpty()) { + // empty is ok + Long number = Long.parseLong(token, 16); + if (number < 0 || number > 0xFFFF) { + return false; + } + } + } catch (NumberFormatException ex) { + return false; + } + } + return true; + default: + return true; + } + } + + /** + * Check supplied listing options. + */ + static Response checkListOptions(Map options) { + // for general listing + String maxResultsString = (String) options.get("maxResults"); + if (maxResultsString != null) { + Integer maxResults = null; + try { + maxResults = Integer.valueOf(maxResultsString); + } catch (NumberFormatException ex) { + return Error.INVALID.response(String.format( + "Invalid integer value': '%s'.", maxResultsString)); + } + if (maxResults <= 0) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.maxResults': '%s'", maxResults)); + } + } + String dnsName = (String) options.get("dnsName"); + if (dnsName != null) { + if (!dnsName.endsWith(".")) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.dnsName': '%s'", dnsName)); + } + } + // for listing dns records, name must be fully qualified + String name = (String) options.get("name"); + if (name != null) { + if (!name.endsWith(".")) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.name': '%s'", name)); + } + } + String type = (String) options.get("type"); // must be provided with name + if (type != null) { + if (name == null) { + return Error.INVALID.response("Invalid value for 'parameters.name': ''"); + } + if (!TYPES.contains(type)) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.type': '%s'", type)); + } + } + // for listing changes + String order = (String) options.get("sortOrder"); + if (order != null && !"ascending".equals(order) && !"descending".equals(order)) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.sortOrder': '%s'", order)); + } + String sortBy = (String) options.get("sortBy"); // case insensitive + if (sortBy != null && !"changesequence".equals(sortBy.toLowerCase())) { + return Error.INVALID.response(String.format( + "Invalid string value: '%s'. Allowed values: [changesequence]", sortBy)); + } + return null; + } +} diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java b/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java new file mode 100644 index 000000000000..f94cb15779ca --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java @@ -0,0 +1,279 @@ +/* + * 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.testing; + +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.Project; +import com.google.api.services.dns.model.ResourceRecordSet; + +import java.util.HashMap; +import java.util.Map; + +/** + * Utility helpers for LocalDnsHelper. + */ +class OptionParsersAndExtractors { + + /** + * Makes a map of list options. Expects query to be only query part of the url (i.e., what follows + * the '?'). + */ + static Map parseListZonesOptions(String query) { + Map options = new HashMap<>(); + if (query != null) { + String[] args = query.split("&"); + for (String arg : args) { + String[] argEntry = arg.split("="); + switch (argEntry[0]) { + case "fields": + // List fields are in the form "managedZones(field1, field2, ...)" + options.put( + "fields", + argEntry[1].substring("managedZones(".length(), argEntry[1].length() - 1) + .split(",")); + break; + case "dnsName": + options.put("dnsName", argEntry[1]); + break; + case "pageToken": + options.put("pageToken", argEntry[1]); + break; + case "maxResults": + // parsing to int is done while handling + options.put("maxResults", argEntry[1]); + break; + default: + break; + } + } + } + return options; + } + + /** + * Makes a map of list options. Expects query to be only query part of the url (i.e., what follows + * the '?'). This format is common for all of zone, change and project. + */ + static String[] parseGetOptions(String query) { + if (query != null) { + String[] args = query.split("&"); + for (String arg : args) { + String[] argEntry = arg.split("="); + if (argEntry[0].equals("fields")) { + // List fields are in the form "fields=field1, field2,..." + return argEntry[1].split(","); + } + } + } + return null; + } + + /** + * Extracts only request fields. + */ + static ManagedZone extractFields(ManagedZone fullZone, String[] fields) { + if (fields == null) { + return fullZone; + } + ManagedZone managedZone = new ManagedZone(); + for (String field : fields) { + switch (field) { + case "creationTime": + managedZone.setCreationTime(fullZone.getCreationTime()); + break; + case "description": + managedZone.setDescription(fullZone.getDescription()); + break; + case "dnsName": + managedZone.setDnsName(fullZone.getDnsName()); + break; + case "id": + managedZone.setId(fullZone.getId()); + break; + case "name": + managedZone.setName(fullZone.getName()); + break; + case "nameServerSet": + managedZone.setNameServerSet(fullZone.getNameServerSet()); + break; + case "nameServers": + managedZone.setNameServers(fullZone.getNameServers()); + break; + default: + break; + } + } + return managedZone; + } + + /** + * Extracts only request fields. + */ + static Change extractFields(Change fullChange, String[] fields) { + if (fields == null) { + return fullChange; + } + Change change = new Change(); + for (String field : fields) { + switch (field) { + case "additions": + // todo the fragmentation is ignored here as our api does not support it + change.setAdditions(fullChange.getAdditions()); + break; + case "deletions": + // todo the fragmentation is ignored here as our api does not support it + change.setDeletions(fullChange.getDeletions()); + break; + case "id": + change.setId(fullChange.getId()); + break; + case "startTime": + change.setStartTime(fullChange.getStartTime()); + break; + case "status": + change.setStatus(fullChange.getStatus()); + break; + default: + break; + } + } + return change; + } + + /** + * Extracts only request fields. + */ + static Project extractFields(Project fullProject, String[] fields) { + if (fields == null) { + return fullProject; + } + Project project = new Project(); + for (String field : fields) { + switch (field) { + case "id": + project.setId(fullProject.getId()); + break; + case "number": + project.setNumber(fullProject.getNumber()); + break; + case "quota": + project.setQuota(fullProject.getQuota()); + break; + default: + break; + } + } + return project; + } + + /** + * Extracts only request fields. + */ + static ResourceRecordSet extractFields(ResourceRecordSet fullRecord, String[] fields) { + if (fields == null) { + return fullRecord; + } + ResourceRecordSet record = new ResourceRecordSet(); + for (String field : fields) { + switch (field) { + case "name": + record.setName(fullRecord.getName()); + break; + case "rrdatas": + record.setRrdatas(fullRecord.getRrdatas()); + break; + case "type": + record.setType(fullRecord.getType()); + break; + case "ttl": + record.setTtl(fullRecord.getTtl()); + break; + default: + break; + } + } + return record; + } + + static Map parseListChangesOptions(String query) { + Map options = new HashMap<>(); + if (query != null) { + String[] args = query.split("&"); + for (String arg : args) { + String[] argEntry = arg.split("="); + switch (argEntry[0]) { + case "fields": + // todo we do not support fragmentation in deletions and additions + options.put( + "fields", + argEntry[1].substring("changes(".length(), argEntry[1].length() - 1).split(",")); + break; + case "name": + options.put("name", argEntry[1]); + break; + case "pageToken": + options.put("pageToken", argEntry[1]); + break; + case "sortBy": + options.put("sortBy", argEntry[1]); + break; + case "sortOrder": + options.put("sortOrder", argEntry[1]); + break; + case "maxResults": + // parsing to int is done while handling + options.put("maxResults", argEntry[1]); + break; + default: + break; + } + } + } + return options; + } + + static Map parseListDnsRecordsOptions(String query) { + Map options = new HashMap<>(); + if (query != null) { + String[] args = query.split("&"); + for (String arg : args) { + String[] argEntry = arg.split("="); + switch (argEntry[0]) { + case "fields": + options.put( + "fields", + argEntry[1].substring("rrsets(".length(), argEntry[1].length() - 1).split(",")); + break; + case "name": + options.put("name", argEntry[1]); + break; + case "pageToken": + options.put("pageToken", argEntry[1]); + break; + case "maxResults": + // parsing to int is done while handling + options.put("maxResults", argEntry[1]); + break; + default: + break; + } + } + } + return options; + } +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java new file mode 100644 index 000000000000..1f851045659c --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java @@ -0,0 +1,955 @@ +/* + * 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.testing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.api.services.dns.model.Change; +import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.ResourceRecordSet; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class LocalDnsHelperTest { + + private static final String RRSET_TYPE = "A"; + private static final ResourceRecordSet RRSET1 = new ResourceRecordSet(); + private static final ResourceRecordSet RRSET2 = new ResourceRecordSet(); + private static final ResourceRecordSet RRSET_KEEP = new ResourceRecordSet(); + private static final String PROJECT_ID1 = "2135436541254"; + private static final String PROJECT_ID2 = "882248761325"; + private static final String ZONE_NAME1 = "my little zone"; + private static final String ZONE_NAME2 = "another zone name"; + private static final ManagedZone ZONE1 = new ManagedZone(); + private static final ManagedZone ZONE2 = new ManagedZone(); + private static final String DNS_NAME = "www.example.com."; + private static final Change CHANGE1 = new Change(); + private static final Change CHANGE2 = new Change(); + private static final Change CHANGE_KEEP = new Change(); + private Map optionsMap; + private LocalDnsHelper localDns; + private ManagedZone minimalZone = new ManagedZone(); // to be adjusted as needed + + @BeforeClass + public static void before() { + RRSET1.setName(DNS_NAME); + RRSET1.setType(RRSET_TYPE); + RRSET1.setRrdatas(ImmutableList.of("1.1.1.1")); + ZONE1.setName(ZONE_NAME1); + ZONE1.setDescription(""); + ZONE1.setDnsName(DNS_NAME); + ZONE2.setName(ZONE_NAME2); + ZONE2.setDescription(""); + ZONE2.setDnsName(DNS_NAME); + RRSET2.setName(DNS_NAME); + RRSET2.setType(RRSET_TYPE); + RRSET_KEEP.setName(DNS_NAME); + RRSET_KEEP.setType("MX"); + RRSET_KEEP.setRrdatas(ImmutableList.of("255.255.255.254")); + RRSET2.setRrdatas(ImmutableList.of("123.132.153.156")); + CHANGE1.setAdditions(ImmutableList.of(RRSET1, RRSET2)); + CHANGE2.setDeletions(ImmutableList.of(RRSET2)); + CHANGE_KEEP.setAdditions(ImmutableList.of(RRSET_KEEP)); + } + + @Before + public void setUp() { + localDns = LocalDnsHelper.create(0L); // synchronous + optionsMap = new HashMap<>(); + minimalZone = copyZone(ZONE1); + } + + @After + public void after() { + localDns = null; + } + + @Test + public void testMatchesCriteria() { + assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), RRSET1.getType())); + assertFalse(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), "anothertype")); + assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, null, RRSET1.getType())); + assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), null)); + assertFalse(LocalDnsHelper.matchesCriteria(RRSET1, "anothername", RRSET1.getType())); + } + + @Test + public void testGetUniqueId() { + assertNotNull(LocalDnsHelper.getUniqueId(Lists.newLinkedList())); + } + + @Test + public void testFindProject() { + assertEquals(0, localDns.projects().size()); + LocalDnsHelper.ProjectContainer project = localDns.findProject(PROJECT_ID1); + assertNotNull(project); + assertTrue(localDns.projects().containsKey(PROJECT_ID1)); + assertNotNull(localDns.findProject(PROJECT_ID2)); + assertTrue(localDns.projects().containsKey(PROJECT_ID2)); + assertTrue(localDns.projects().containsKey(PROJECT_ID1)); + assertNotNull(project.zones()); + assertEquals(0, project.zones().size()); + assertNotNull(project.project()); + assertNotNull(project.project().getQuota()); + } + + @Test + public void testCreateAndFindZone() { + LocalDnsHelper.ZoneContainer zone1 = localDns.findZone(PROJECT_ID1, ZONE_NAME1); + assertTrue(localDns.projects().containsKey(PROJECT_ID1)); + assertNull(zone1); + localDns.createZone(PROJECT_ID1, ZONE1, null); // we do not care about options + zone1 = localDns.findZone(PROJECT_ID1, ZONE1.getName()); + assertNotNull(zone1); + // cannot call equals because id and timestamp got assigned + assertEquals(ZONE_NAME1, zone1.zone().getName()); + assertNotNull(zone1.changes()); + assertTrue(zone1.changes().isEmpty()); + assertNotNull(zone1.dnsRecords()); + assertEquals(2, zone1.dnsRecords().get(ZONE_NAME1).size()); // default SOA and NS + localDns.createZone(PROJECT_ID2, ZONE1, null); // project does not exits yet + assertEquals(ZONE1.getName(), localDns.findZone(PROJECT_ID2, ZONE_NAME1).zone().getName()); + } + + @Test + public void testDeleteZone() { + localDns.createZone(PROJECT_ID1, ZONE1, null); + LocalDnsHelper.Response response = localDns.deleteZone(PROJECT_ID1, ZONE1.getName()); + assertEquals(204, response.code()); + // deleting non-existent zone + response = localDns.deleteZone(PROJECT_ID1, ZONE1.getName()); + assertEquals(404, response.code()); + assertNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); + localDns.createZone(PROJECT_ID1, ZONE1, null); + localDns.createZone(PROJECT_ID1, ZONE2, null); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE2.getName())); + // delete in reverse order + response = localDns.deleteZone(PROJECT_ID1, ZONE1.getName()); + assertEquals(204, response.code()); + assertNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE2.getName())); + localDns.deleteZone(PROJECT_ID1, ZONE2.getName()); + assertEquals(204, response.code()); + assertNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); + assertNull(localDns.findZone(PROJECT_ID1, ZONE2.getName())); + } + + @Test + public void testCreateAndApplyChange() { + localDns = LocalDnsHelper.create(5 * 1000L); // we will be using threads here + localDns.createZone(PROJECT_ID1, ZONE1, null); + assertNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + LocalDnsHelper.Response response + = localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add + assertEquals(200, response.code()); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + assertNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add + assertEquals(200, response.code()); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); // delete + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); + assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("3")); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE_KEEP, null); // id is "4" + // check execution + Change change = localDns.findChange(PROJECT_ID1, ZONE_NAME1, "4"); + for (int i = 0; i < 10 && !change.getStatus().equals("done"); i++) { + // change has not been finished yet; wait at most 20 seconds + // it takes 5 seconds for the thread to kick in in the first place + try { + Thread.sleep(2 * 1000); + } catch (InterruptedException e) { + fail("Test was interrupted"); + } + } + assertEquals("done", change.getStatus()); + List list = + localDns.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); + assertTrue(list.contains(new LocalDnsHelper.RrsetWrapper(RRSET_KEEP))); + } + + @Test + public void testFindChange() { + localDns.createZone(PROJECT_ID1, ZONE1, null); + Change change = localDns.findChange(PROJECT_ID1, ZONE1.getName(), "somerandomchange"); + assertNull(change); + localDns.createChange(PROJECT_ID1, ZONE1.getName(), CHANGE1, null); + // changes are sequential so we should find ID 1 + assertNotNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "1")); + // add another + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); + assertNotNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "1")); + assertNotNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "2")); + // try to find non-existent change + assertNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "3")); + // try to find a change in yet non-existent project + assertNull(localDns.findChange(PROJECT_ID2, ZONE1.getName(), "3")); + } + + @Test + public void testRandomNameServers() { + assertEquals(4, LocalDnsHelper.randomNameservers().size()); + assertEquals(4, LocalDnsHelper.randomNameservers().size()); + assertEquals(4, LocalDnsHelper.randomNameservers().size()); + assertEquals(4, LocalDnsHelper.randomNameservers().size()); + } + + @Test + public void testGetProject() { + // only interested in no exceptions and non-null response here + assertNotNull(localDns.getProject(PROJECT_ID1, null)); + assertNotNull(localDns.getProject(PROJECT_ID2, null)); + } + + @Test + public void testGetZone() { + // non-existent + LocalDnsHelper.Response response = localDns.getZone(PROJECT_ID1, ZONE_NAME1, null); + assertEquals(404, response.code()); + assertTrue(response.body().contains("does not exist")); + // existent + localDns.createZone(PROJECT_ID1, ZONE1, null); + response = localDns.getZone(PROJECT_ID1, ZONE1.getName(), null); + assertEquals(200, response.code()); + } + + @Test + public void testCreateZone() { + // only interested in no exceptions and non-null response here + LocalDnsHelper.Response response = localDns.createZone(PROJECT_ID1, ZONE1, null); + assertEquals(200, response.code()); + assertEquals(1, localDns.projects().get(PROJECT_ID1).zones().size()); + try { + localDns.createZone(PROJECT_ID1, null, null); + fail("Zone cannot be null"); + } catch (NullPointerException ex) { + // expected + } + // create zone twice + response = localDns.createZone(PROJECT_ID1, ZONE1, null); + assertEquals(409, response.code()); + assertTrue(response.body().contains("already exists")); + } + + @Test + public void testCreateChange() { + // non-existent zone + LocalDnsHelper.Response response = + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + assertEquals(404, response.code()); + + // existent zone + assertNotNull(localDns.createZone(PROJECT_ID1, ZONE1, null)); + assertNull(localDns.findChange(PROJECT_ID1, ZONE_NAME1, "1")); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + assertEquals(200, response.code()); + assertNotNull(localDns.findChange(PROJECT_ID1, ZONE_NAME1, "1")); + } + + @Test + public void testGetChange() { + // existent + assertEquals(200, localDns.createZone(PROJECT_ID1, ZONE1, null).code()); + assertEquals(200, localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null).code()); + assertEquals(200, localDns.getChange(PROJECT_ID1, ZONE_NAME1, "1", null).code()); + // non-existent + LocalDnsHelper.Response response = localDns.getChange(PROJECT_ID1, ZONE_NAME1, "2", null); + assertEquals(404, response.code()); + assertTrue(response.body().contains("parameters.changeId")); + // non-existent zone + response = localDns.getChange(PROJECT_ID1, ZONE_NAME2, "1", null); + assertEquals(404, response.code()); + assertTrue(response.body().contains("parameters.managedZone")); + } + + @Test + public void testListZones() { + // only interested in no exceptions and non-null response here + optionsMap.put("dnsName", null); + optionsMap.put("fields", null); + optionsMap.put("pageToken", null); + optionsMap.put("maxResults", null); + LocalDnsHelper.Response response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + // some zones exists + localDns.createZone(PROJECT_ID1, ZONE1, null); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + localDns.createZone(PROJECT_ID1, ZONE2, null); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + // error in options + optionsMap.put("maxResults", "aaa"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "0"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "-1"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "15"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("dnsName", "aaa"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("dnsName", "aaa."); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + } + + @Test + public void testListDnsRecords() { + // only interested in no exceptions and non-null response here + optionsMap.put("name", null); + optionsMap.put("fields", null); + optionsMap.put("type", null); + optionsMap.put("pageToken", null); + optionsMap.put("maxResults", null); + // no zone exists + LocalDnsHelper.Response response = localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, + optionsMap); + assertEquals(404, response.code()); + // zone exists but has no records + localDns.createZone(PROJECT_ID1, ZONE1, null); + localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); + // zone has records + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + response = localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + // error in options + optionsMap.put("maxResults", "aaa"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "0"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "-1"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "15"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("name", "aaa"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("name", "aaa."); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("name", null); + optionsMap.put("type", "A"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("name", "aaa."); + optionsMap.put("type", "a"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("name", "aaaa."); + optionsMap.put("type", "A"); + response = localDns.listZones(PROJECT_ID1, optionsMap); + assertEquals(200, response.code()); + } + + @Test + public void testListChanges() { + optionsMap.put("sortBy", null); + optionsMap.put("sortOrder", null); + optionsMap.put("fields", null); + optionsMap.put("pageToken", null); + optionsMap.put("maxResults", null); + // no such zone exists + LocalDnsHelper.Response response = localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(404, response.code()); + assertTrue(response.body().contains("managedZone")); + // zone exists but has no changes + localDns.createZone(PROJECT_ID1, ZONE1, null); + assertNotNull(localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); + // zone has changes + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + assertNotNull(localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); + assertNotNull(localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); + // error in options + optionsMap.put("maxResults", "aaa"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "0"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "-1"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("maxResults", "15"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("dnsName", "aaa"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(400, response.code()); + optionsMap.put("dnsName", "aaa."); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("sortBy", "changeSequence"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("sortBy", "something else"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("Allowed values: [changesequence]")); + optionsMap.put("sortBy", "ChAnGeSeQuEnCe"); // is not case sensitive + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("sortOrder", "ascending"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("sortBy", null); + optionsMap.put("sortOrder", "descending"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(200, response.code()); + optionsMap.put("sortOrder", "somethingelse"); + response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.sortOrder")); + } + + @Test + public void testToListResponse() { + LocalDnsHelper.Response response = LocalDnsHelper.toListResponse( + Lists.newArrayList("some", "multiple", "words"), "IncludeThisPageToken", true); + assertTrue(response.body().contains("IncludeThisPageToken")); + response = LocalDnsHelper.toListResponse( + Lists.newArrayList("some", "multiple", "words"), "IncludeThisPageToken", false); + assertFalse(response.body().contains("IncludeThisPageToken")); + response = LocalDnsHelper.toListResponse( + Lists.newArrayList("some", "multiple", "words"), null, true); + assertFalse(response.body().contains("pageToken")); + } + + @Test + public void testCheckZone() { + // no name + ManagedZone copy = copyZone(minimalZone); + copy.setName(null); + LocalDnsHelper.Response response = LocalDnsHelper.checkZone(copy); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.name")); + // no description + copy = copyZone(minimalZone); + copy.setDescription(null); + response = LocalDnsHelper.checkZone(copy); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.description")); + // no description + copy = copyZone(minimalZone); + copy.setDnsName(null); + response = LocalDnsHelper.checkZone(copy); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.dnsName")); + // zone name is a number + copy = copyZone(minimalZone); + copy.setName("123456"); + response = LocalDnsHelper.checkZone(copy); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.name")); + assertTrue(response.body().contains("Invalid")); + // dns name does not end with period + copy = copyZone(minimalZone); + copy.setDnsName("aaaaaa.com"); + response = LocalDnsHelper.checkZone(copy); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.dnsName")); + assertTrue(response.body().contains("Invalid")); + // dns name is reserved + copy = copyZone(minimalZone); + copy.setDnsName("com."); + response = LocalDnsHelper.checkZone(copy); + assertEquals(400, response.code()); + assertTrue(response.body().contains("not available to be created.")); + // empty description should pass + copy = copyZone(minimalZone); + copy.setDescription(""); + assertNull(LocalDnsHelper.checkZone(copy)); + } + + @Test + public void testCreateZoneValidatesZone() { + // no name + ManagedZone copy = copyZone(minimalZone); + copy.setName(null); + LocalDnsHelper.Response response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.name")); + // no description + copy = copyZone(minimalZone); + copy.setDescription(null); + response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.description")); + // no dns name + copy = copyZone(minimalZone); + copy.setDnsName(null); + response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.dnsName")); + // zone name is a number + copy = copyZone(minimalZone); + copy.setName("123456"); + response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.name")); + assertTrue(response.body().contains("Invalid")); + // dns name does not end with period + copy = copyZone(minimalZone); + copy.setDnsName("aaaaaa.com"); + response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("entity.managedZone.dnsName")); + assertTrue(response.body().contains("Invalid")); + // dns name is reserved + copy = copyZone(minimalZone); + copy.setDnsName("com."); + response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("not available to be created.")); + // empty description should pass + copy = copyZone(minimalZone); + copy.setDescription(""); + response = localDns.createZone(PROJECT_ID1, copy, null); + assertEquals(200, response.code()); + } + + @Test + public void testCheckListOptions() { + // listing zones + optionsMap.put("maxResults", "-1"); + LocalDnsHelper.Response response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.maxResults")); + optionsMap.put("maxResults", "0"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.maxResults")); + optionsMap.put("maxResults", "aaaa"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("integer")); + optionsMap.put("maxResults", "15"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + optionsMap.put("dnsName", "aaa"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.dnsName")); + optionsMap.put("dnsName", "aaa."); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + // listing dns records + optionsMap.put("name", "aaa"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.name")); + optionsMap.put("name", "aaa."); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + optionsMap.put("name", null); + optionsMap.put("type", "A"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.name")); + optionsMap.put("name", "aaa."); + optionsMap.put("type", "a"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.type")); + optionsMap.put("name", "aaaa."); + optionsMap.put("type", "A"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + // listing changes + optionsMap.put("sortBy", "changeSequence"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + optionsMap.put("sortBy", "something else"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("Allowed values: [changesequence]")); + optionsMap.put("sortBy", "ChAnGeSeQuEnCe"); // is not case sensitive + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + optionsMap.put("sortOrder", "ascending"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + optionsMap.put("sortOrder", "descending"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertNull(response); + optionsMap.put("sortOrder", "somethingelse"); + response = LocalDnsHelper.checkListOptions(optionsMap); + assertEquals(400, response.code()); + assertTrue(response.body().contains("parameters.sortOrder")); + } + + @Test + public void testCheckRrset() { + ResourceRecordSet valid = new ResourceRecordSet(); + valid.setName(ZONE1.getDnsName()); + valid.setType("A"); + valid.setRrdatas(ImmutableList.of("0.255.1.5")); + valid.setTtl(500); + Change validChange = new Change(); + validChange.setAdditions(ImmutableList.of(valid)); + localDns.createZone(PROJECT_ID1, ZONE1, null); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + // delete with field mismatch + LocalDnsHelper.ZoneContainer zone = localDns.findZone(PROJECT_ID1, ZONE_NAME1); + valid.setTtl(valid.getTtl() + 20); + LocalDnsHelper.Response response = LocalDnsHelper.checkRrset(valid, zone, 0, "deletions"); + assertEquals(412, response.code()); + assertTrue(response.body().contains("entity.change.deletions[0]")); + } + + @Test + public void testCheckRrdata() { + // A + assertTrue(LocalDnsHelper.checkRrData("255.255.255.255", "A")); + assertTrue(LocalDnsHelper.checkRrData("13.15.145.165", "A")); + assertTrue(LocalDnsHelper.checkRrData("0.0.0.0", "A")); + assertFalse(LocalDnsHelper.checkRrData("255.255.255.256", "A")); + assertFalse(LocalDnsHelper.checkRrData("-1.255.255.255", "A")); + assertFalse(LocalDnsHelper.checkRrData(".255.255.254", "A")); + assertFalse(LocalDnsHelper.checkRrData("111.255.255.", "A")); + assertFalse(LocalDnsHelper.checkRrData("111.255..22", "A")); + assertFalse(LocalDnsHelper.checkRrData("111.255.aa.22", "A")); + assertFalse(LocalDnsHelper.checkRrData("", "A")); + assertFalse(LocalDnsHelper.checkRrData("...", "A")); + assertFalse(LocalDnsHelper.checkRrData("111.255.12", "A")); + assertFalse(LocalDnsHelper.checkRrData("111.255.12.11.11", "A")); + // AAAA + assertTrue(LocalDnsHelper.checkRrData(":::::::", "AAAA")); + assertTrue(LocalDnsHelper.checkRrData("1F:fa:09fd::343:aaaa:AAAA:", "AAAA")); + assertTrue(LocalDnsHelper.checkRrData("0000:FFFF:09fd::343:aaaa:AAAA:", "AAAA")); + assertFalse(LocalDnsHelper.checkRrData("-2:::::::", "AAAA")); + assertTrue(LocalDnsHelper.checkRrData("0:::::::", "AAAA")); + assertFalse(LocalDnsHelper.checkRrData("::1FFFF:::::", "AAAA")); + assertFalse(LocalDnsHelper.checkRrData("::aqaa:::::", "AAAA")); + assertFalse(LocalDnsHelper.checkRrData("::::::::", "AAAA")); // too long + assertFalse(LocalDnsHelper.checkRrData("::::::", "AAAA")); // too short + } + + @Test + public void testCheckChange() { + ResourceRecordSet validA = new ResourceRecordSet(); + validA.setName(ZONE1.getDnsName()); + validA.setType("A"); + validA.setRrdatas(ImmutableList.of("0.255.1.5")); + ResourceRecordSet invalidA = new ResourceRecordSet(); + invalidA.setName(ZONE1.getDnsName()); + invalidA.setType("A"); + invalidA.setRrdatas(ImmutableList.of("0.-255.1.5")); + Change validChange = new Change(); + validChange.setAdditions(ImmutableList.of(validA)); + Change invalidChange = new Change(); + invalidChange.setAdditions(ImmutableList.of(invalidA)); + LocalDnsHelper.ZoneContainer zoneContainer = new LocalDnsHelper.ZoneContainer(ZONE1); + LocalDnsHelper.Response response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertNull(response); + response = LocalDnsHelper.checkChange(invalidChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].rrdata[0]")); + // only empty additions/deletions + Change empty = new Change(); + empty.setAdditions(ImmutableList.of()); + empty.setDeletions(ImmutableList.of()); + response = LocalDnsHelper.checkChange(empty, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "The 'entity.change' parameter is required but was missing.")); + // null additions/deletions + empty = new Change(); + response = LocalDnsHelper.checkChange(empty, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "The 'entity.change' parameter is required but was missing.")); + // non-matching name + validA.setName(ZONE1.getDnsName() + ".aaa."); + response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].name")); + // wrong type + validA.setName(ZONE1.getDnsName()); // revert + validA.setType("ABCD"); + response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].type")); + // wrong ttl + validA.setType("A"); // revert + validA.setTtl(-1); + response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].ttl")); + validA.setTtl(null); + // null name + validA.setName(null); + response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].name")); + validA.setName(ZONE1.getDnsName()); + // null type + validA.setType(null); + response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].type")); + validA.setType("A"); + // null rrdata + List temp = validA.getRrdatas(); // preserve + validA.setRrdatas(null); + response = LocalDnsHelper.checkChange(validChange, zoneContainer); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].rrdata")); + validA.setRrdatas(temp); + // delete non-existent + ResourceRecordSet nonExistent = new ResourceRecordSet(); + nonExistent.setName(ZONE1.getDnsName()); + nonExistent.setType("AAAA"); + nonExistent.setRrdatas(ImmutableList.of(":::::::")); + Change delete = new Change(); + delete.setDeletions(ImmutableList.of(nonExistent)); + response = LocalDnsHelper.checkChange(delete, zoneContainer); + assertEquals(404, response.code()); + assertTrue(response.body().contains("deletions[0]")); + + } + + @Test + public void testAdditionsMeetDeletions() { + ResourceRecordSet validA = new ResourceRecordSet(); + validA.setName(ZONE1.getDnsName()); + validA.setType("A"); + validA.setRrdatas(ImmutableList.of("0.255.1.5")); + Change validChange = new Change(); + validChange.setAdditions(ImmutableList.of(validA)); + localDns.createZone(PROJECT_ID1, ZONE1, null); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LocalDnsHelper.ZoneContainer container = localDns.findZone(PROJECT_ID1, ZONE_NAME1); + LocalDnsHelper.Response response = + LocalDnsHelper.additionsMeetDeletions(ImmutableList.of(validA), null, container); + assertEquals(409, response.code()); + assertTrue(response.body().contains("already exists")); + + } + + @Test + public void testCreateChangeValidatesChangeContent() { + ResourceRecordSet validA = new ResourceRecordSet(); + validA.setName(ZONE1.getDnsName()); + validA.setType("A"); + validA.setRrdatas(ImmutableList.of("0.255.1.5")); + Change validChange = new Change(); + validChange.setAdditions(ImmutableList.of(validA)); + localDns.createZone(PROJECT_ID1, ZONE1, null); + localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LocalDnsHelper.Response response = + localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(409, response.code()); + assertTrue(response.body().contains("already exists")); + // delete with field mismatch + Change delete = new Change(); + validA.setTtl(20); // mismatch + delete.setDeletions(ImmutableList.of(validA)); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + assertEquals(412, response.code()); + assertTrue(response.body().contains("entity.change.deletions[0]")); + // delete and add SOA + Change addition = new Change(); + ImmutableList rrsetWrappers + = localDns.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); + LinkedList deletions = new LinkedList<>(); + LinkedList additions = new LinkedList<>(); + for (LocalDnsHelper.RrsetWrapper wrapper : rrsetWrappers) { + ResourceRecordSet rrset = wrapper.rrset(); + if (rrset.getType().equals("SOA")) { + deletions.add(rrset); + ResourceRecordSet copy = copyRrset(rrset); + copy.setName("x." + copy.getName()); + additions.add(copy); + break; + } + } + delete.setDeletions(deletions); + addition.setAdditions(additions); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "zone must contain exactly one resource record set of type 'SOA' at the apex")); + assertTrue(response.body().contains("deletions[0]")); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "zone must contain exactly one resource record set of type 'SOA' at the apex")); + assertTrue(response.body().contains("additions[0]")); + // delete NS + deletions = new LinkedList<>(); + additions = new LinkedList<>(); + for (LocalDnsHelper.RrsetWrapper wrapper : rrsetWrappers) { + ResourceRecordSet rrset = wrapper.rrset(); + if (rrset.getType().equals("NS")) { + deletions.add(rrset); + ResourceRecordSet copy = copyRrset(rrset); + copy.setName("x." + copy.getName()); + additions.add(copy); + break; + } + } + delete.setDeletions(deletions); + addition.setAdditions(additions); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "zone must contain exactly one resource record set of type 'NS' at the apex")); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "zone must contain exactly one resource record set of type 'NS' at the apex")); + assertTrue(response.body().contains("additions[0]")); + // change (delete + add) + addition.setDeletions(deletions); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + assertEquals(200, response.code()); + } + + @Test + public void testCreateChangeValidatesChange() { + localDns.createZone(PROJECT_ID1, ZONE1, null); + ResourceRecordSet validA = new ResourceRecordSet(); + validA.setName(ZONE1.getDnsName()); + validA.setType("A"); + validA.setRrdatas(ImmutableList.of("0.255.1.5")); + ResourceRecordSet invalidA = new ResourceRecordSet(); + invalidA.setName(ZONE1.getDnsName()); + invalidA.setType("A"); + invalidA.setRrdatas(ImmutableList.of("0.-255.1.5")); + Change validChange = new Change(); + validChange.setAdditions(ImmutableList.of(validA)); + Change invalidChange = new Change(); + invalidChange.setAdditions(ImmutableList.of(invalidA)); + LocalDnsHelper.Response response = + localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(200, response.code()); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, invalidChange, null); + assertEquals(400, response.code()); + // only empty additions/deletions + Change empty = new Change(); + empty.setAdditions(ImmutableList.of()); + empty.setDeletions(ImmutableList.of()); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, empty, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains( + "The 'entity.change' parameter is required but was missing.")); + // non-matching name + validA.setName(ZONE1.getDnsName() + ".aaa."); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].name")); + // wrong type + validA.setName(ZONE1.getDnsName()); // revert + validA.setType("ABCD"); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].type")); + // wrong ttl + validA.setType("A"); // revert + validA.setTtl(-1); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].ttl")); + validA.setTtl(null); // revert + // null name + validA.setName(null); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].name")); + validA.setName(ZONE1.getDnsName()); + // null type + validA.setType(null); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].type")); + validA.setType("A"); + // null rrdata + List temp = validA.getRrdatas(); // preserve + validA.setRrdatas(null); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + assertEquals(400, response.code()); + assertTrue(response.body().contains("additions[0].rrdata")); + validA.setRrdatas(temp); + // delete non-existent + ResourceRecordSet nonExistent = new ResourceRecordSet(); + nonExistent.setName(ZONE1.getDnsName()); + nonExistent.setType("AAAA"); + nonExistent.setRrdatas(ImmutableList.of(":::::::")); + Change delete = new Change(); + delete.setDeletions(ImmutableList.of(nonExistent)); + response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + assertEquals(404, response.code()); + assertTrue(response.body().contains("deletions[0]")); + } + + private static ManagedZone copyZone(ManagedZone original) { + ManagedZone copy = new ManagedZone(); + copy.setDescription(original.getDescription()); + copy.setName(original.getName()); + copy.setCreationTime(original.getCreationTime()); + copy.setId(original.getId()); + copy.setNameServerSet(original.getNameServerSet()); + copy.setDnsName(original.getDnsName()); + if (original.getNameServers() != null) { + copy.setNameServers(ImmutableList.copyOf(original.getNameServers())); + } + return copy; + } + + private static ResourceRecordSet copyRrset(ResourceRecordSet set) { + ResourceRecordSet copy = new ResourceRecordSet(); + if (set.getRrdatas() != null) { + copy.setRrdatas(ImmutableList.copyOf(set.getRrdatas())); + } + copy.setTtl(set.getTtl()); + copy.setName(set.getName()); + copy.setType(set.getType()); + return copy; + } +} From 04f354a16a8759af38d3e883b9bb9dcc467744f3 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 23 Feb 2016 11:38:51 -0800 Subject: [PATCH 51/74] Added RPC layer of tests for local helpers. Closes #665. Debugged parsing for options. Fixed context for the server URLs and regular expression parsing. Fixed paging. Improved error detection for missing zones vs. non-existent changes. --- .../com/google/gcloud/spi/DefaultDnsRpc.java | 4 +- .../google/gcloud/testing/LocalDnsHelper.java | 126 +- .../testing/OptionParsersAndExtractors.java | 31 +- .../gcloud/testing/LocalDnsHelperTest.java | 1176 ++++++++++++++--- 4 files changed, 1097 insertions(+), 240 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index 6ed9c7e0f216..b72a21445a80 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -162,7 +162,9 @@ public Change getChangeRequest(String zoneName, String changeRequestId, MapWhile the mock attempts to simulate the service, there are some differences in the behaviour. * The mock will accept any project ID and never returns a notFound or another error because of - * project ID. It assumes that all project IDs exists and that the user has all the necessary + * project ID. It assumes that all project IDs exist and that the user has all the necessary * privileges to manipulate any project. Similarly, the local simulation does not work with any * verification of domain name ownership. Any request for creating a managed zone will be approved. * The mock does not track quota and will allow the user to exceed it. The mock provides only basic @@ -92,11 +93,10 @@ public class LocalDnsHelper { = new ConcurrentSkipListMap<>(); private static final URI BASE_CONTEXT; private static final Logger log = Logger.getLogger(LocalDnsHelper.class.getName()); - private static final JsonFactory jsonFactory = - new com.google.api.client.json.jackson.JacksonFactory(); + private static final JsonFactory jsonFactory = new JacksonFactory(); private static final Random ID_GENERATOR = new Random(); private static final String VERSION = "v1"; - private static final String CONTEXT = "/" + VERSION + "/projects"; + private static final String CONTEXT = "/dns/" + VERSION + "/projects"; private static final Set SUPPORTED_COMPRESSION_ENCODINGS = ImmutableSet.of("gzip", "x-gzip"); private static final List TYPES = ImmutableList.of("A", "AAAA", "CNAME", "MX", "NAPTR", @@ -119,15 +119,15 @@ public class LocalDnsHelper { * For matching URLs to operations. */ private enum CallRegex { - CHANGE_CREATE("POST", "/[^/]+/managedZones/[^/]+/changes"), - CHANGE_GET("GET", "/[^/]+/managedZones/[^/]+/changes/[^/]+"), - CHANGE_LIST("GET", "/[^/]+/managedZones/[^/]+/changes"), - ZONE_CREATE("POST", "/[^/]+/managedZones"), - ZONE_DELETE("DELETE", "/[^/]+/managedZones/[^/]+"), - ZONE_GET("GET", "/[^/]+/managedZones/[^/]+"), - ZONE_LIST("GET", "/[^/]+/managedZones"), - PROJECT_GET("GET", "/[^/]+"), - RECORD_LIST("GET", "/[^/]+/managedZones/[^/]+/rrsets"); + CHANGE_CREATE("POST", CONTEXT + "/[^/]+/managedZones/[^/]+/changes"), + CHANGE_GET("GET", CONTEXT + "/[^/]+/managedZones/[^/]+/changes/[^/]+"), + CHANGE_LIST("GET", CONTEXT + "/[^/]+/managedZones/[^/]+/changes"), + ZONE_CREATE("POST", CONTEXT + "/[^/]+/managedZones"), + ZONE_DELETE("DELETE", CONTEXT + "/[^/]+/managedZones/[^/]+"), + ZONE_GET("GET", CONTEXT + "/[^/]+/managedZones/[^/]+"), + ZONE_LIST("GET", CONTEXT + "/[^/]+/managedZones"), + PROJECT_GET("GET", CONTEXT + "/[^/]+"), + RECORD_LIST("GET", CONTEXT + "/[^/]+/managedZones/[^/]+/rrsets"); private String method; private String pathRegex; @@ -220,14 +220,14 @@ ConcurrentSkipListMap zones() { } /** - * Associates a zone with a collection of changes and dns record. Thread safe. + * Associates a zone with a collection of changes and dns records. Thread safe. */ static class ZoneContainer { private final ManagedZone zone; /** * DNS records are held in a map to allow for atomic replacement of record sets when applying * changes. The key for the map is always the zone name. The collection of records is immutable - * and must always exist, i.e., dnsRecords.get(zone.getName()) is never null. + * and must always exist, i.e., dnsRecords.get(zone.getName()) is never {@code null}. */ private final ConcurrentSkipListMap> dnsRecords = new ConcurrentSkipListMap<>(); @@ -377,20 +377,19 @@ public void handle(HttpExchange exchange) throws IOException { writeResponse(exchange, Error.NOT_FOUND.response("The url does not match any API call.")); } - // todo(mderka) Test handlers using gcloud-java-dns. Issue #665. private Response handleZoneDelete(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; - String zoneName = tokens[3]; + String projectId = tokens[0]; + String zoneName = tokens[2]; return deleteZone(projectId, zoneName); } private Response handleZoneGet(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; - String zoneName = tokens[3]; + String projectId = tokens[0]; + String zoneName = tokens[2]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); String[] fields = OptionParsersAndExtractors.parseGetOptions(query); return getZone(projectId, zoneName, fields); @@ -399,7 +398,7 @@ private Response handleZoneGet(HttpExchange exchange) { private Response handleZoneList(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; + String projectId = tokens[0]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); Map options = OptionParsersAndExtractors.parseListZonesOptions(query); return listZones(projectId, options); @@ -408,7 +407,7 @@ private Response handleZoneList(HttpExchange exchange) { private Response handleProjectGet(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; + String projectId = tokens[0]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); String[] fields = OptionParsersAndExtractors.parseGetOptions(query); return getProject(projectId, fields); @@ -420,8 +419,8 @@ private Response handleProjectGet(HttpExchange exchange) { private Response handleChangeCreate(HttpExchange exchange) throws IOException { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; - String zoneName = tokens[3]; + String projectId = tokens[0]; + String zoneName = tokens[2]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); String[] fields = OptionParsersAndExtractors.parseGetOptions(query); String requestBody = decodeContent(exchange.getRequestHeaders(), exchange.getRequestBody()); @@ -432,9 +431,9 @@ private Response handleChangeCreate(HttpExchange exchange) throws IOException { private Response handleChangeGet(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; - String zoneName = tokens[3]; - String changeId = tokens[5]; + String projectId = tokens[0]; + String zoneName = tokens[2]; + String changeId = tokens[4]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); String[] fields = OptionParsersAndExtractors.parseGetOptions(query); return getChange(projectId, zoneName, changeId, fields); @@ -443,8 +442,8 @@ private Response handleChangeGet(HttpExchange exchange) { private Response handleChangeList(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; - String zoneName = tokens[3]; + String projectId = tokens[0]; + String zoneName = tokens[2]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); Map options = OptionParsersAndExtractors.parseListChangesOptions(query); return listChanges(projectId, zoneName, options); @@ -453,8 +452,8 @@ private Response handleChangeList(HttpExchange exchange) { private Response handleDnsRecordList(HttpExchange exchange) { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; - String zoneName = tokens[3]; + String projectId = tokens[0]; + String zoneName = tokens[2]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); Map options = OptionParsersAndExtractors.parseListDnsRecordsOptions(query); return listDnsRecords(projectId, zoneName, options); @@ -466,7 +465,7 @@ private Response handleDnsRecordList(HttpExchange exchange) { private Response handleZoneCreate(HttpExchange exchange) throws IOException { String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); String[] tokens = path.split("/"); - String projectId = tokens[1]; + String projectId = tokens[0]; String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); String[] options = OptionParsersAndExtractors.parseGetOptions(query); String requestBody = decodeContent(exchange.getRequestHeaders(), exchange.getRequestBody()); @@ -539,7 +538,9 @@ private static void writeResponse(HttpExchange exchange, Response response) { try { exchange.getResponseHeaders().add("Connection", "close"); exchange.sendResponseHeaders(response.code(), response.body().length()); - outputStream.write(response.body().getBytes(StandardCharsets.UTF_8)); + if (response.code() != 204) { + outputStream.write(response.body().getBytes(StandardCharsets.UTF_8)); + } outputStream.close(); } catch (IOException e) { log.log(Level.WARNING, "IOException encountered when sending response.", e); @@ -569,18 +570,20 @@ private static String decodeContent(Headers headers, InputStream inputStream) th } /** - * Generates a JSON response. Tested. + * Generates a JSON response. + * + * @param context managedZones | projects | rrsets | changes */ - static Response toListResponse(List serializedObjects, String pageToken, + static Response toListResponse(List serializedObjects, String context, String pageToken, boolean includePageToken) { // start building response StringBuilder responseBody = new StringBuilder(); - responseBody.append("{\"projects\": ["); + responseBody.append("{\"").append(context).append("\": ["); Joiner.on(",").appendTo(responseBody, serializedObjects); responseBody.append("]"); // add page token only if exists and is asked for if (pageToken != null && includePageToken) { - responseBody.append(",\"pageToken\": \"").append(pageToken).append("\""); + responseBody.append(",\"nextPageToken\": \"").append(pageToken).append("\""); } responseBody.append("}"); return new Response(HTTP_OK, responseBody.toString()); @@ -627,14 +630,13 @@ static List randomNameservers() { } /** - * Returns a hex string id (used for a dns record) unique withing the set of wrappers. + * Returns a hex string id (used for a dns record) unique within the set of wrappers. */ static String getUniqueId(List wrappers) { TreeSet ids = Sets.newTreeSet(Lists.transform(wrappers, new Function() { - @Nullable @Override - public String apply(@Nullable RrsetWrapper input) { + public String apply(RrsetWrapper input) { return input.id() == null ? "null" : input.id(); } })); @@ -663,7 +665,8 @@ static boolean matchesCriteria(ResourceRecordSet record, String name, String typ } /** - * Returns a project container. Never returns null because we assume that all projects exists. + * Returns a project container. Never returns {@code null} because we assume that all projects + * exists. */ ProjectContainer findProject(String projectId) { ProjectContainer defaultProject = createProject(projectId); @@ -672,7 +675,7 @@ ProjectContainer findProject(String projectId) { } /** - * Returns a zone container. Returns null if zone does not exist within project. + * Returns a zone container. Returns {@code null} if zone does not exist within project. */ ZoneContainer findZone(String projectId, String zoneName) { ProjectContainer projectContainer = findProject(projectId); // never null @@ -680,7 +683,7 @@ ZoneContainer findZone(String projectId, String zoneName) { } /** - * Returns a change found by its id. Returns null if such a change does not exist. + * Returns a change found by its id. Returns {@code null} if such a change does not exist. */ Change findChange(String projectId, String zoneName, String changeId) { ZoneContainer wrapper = findZone(projectId, zoneName); @@ -688,7 +691,7 @@ Change findChange(String projectId, String zoneName, String changeId) { } /** - * Returns a response to get change call. + * Returns a response to getChange service call. */ Response getChange(String projectId, String zoneName, String changeId, String[] fields) { Change change = findChange(projectId, zoneName, changeId); @@ -711,11 +714,10 @@ Response getChange(String projectId, String zoneName, String changeId, String[] "Error when serializing change %s in managed zone %s in project %s.", changeId, zoneName, projectId)); } - // todo(mderka) Test field options within #665. } /** - * Returns a response to get zone call. + * Returns a response to getZone service call. */ Response getZone(String projectId, String zoneName, String[] fields) { ZoneContainer container = findZone(projectId, zoneName); @@ -730,7 +732,6 @@ Response getZone(String projectId, String zoneName, String[] fields) { return Error.INTERNAL_ERROR.response(String.format( "Error when serializing managed zone %s in project %s.", zoneName, projectId)); } - // todo(mderka) Test field options within #665. } /** @@ -748,7 +749,6 @@ Response getProject(String projectId, String[] fields) { return Error.INTERNAL_ERROR.response( String.format("Error when serializing project %s.", projectId)); } - // todo(mderka) Test field options within #665. } /** @@ -798,6 +798,7 @@ Response createZone(String projectId, ManagedZone zone, String[] fields) { ManagedZone completeZone = new ManagedZone(); completeZone.setName(zone.getName()); completeZone.setDnsName(zone.getDnsName()); + completeZone.setDescription(zone.getDescription()); completeZone.setNameServerSet(zone.getNameServerSet()); completeZone.setCreationTime(ISODateTimeFormat.dateTime().withZoneUTC() .print(System.currentTimeMillis())); @@ -823,7 +824,6 @@ Response createZone(String projectId, ManagedZone zone, String[] fields) { return Error.INTERNAL_ERROR.response( String.format("Error when serializing managed zone %s.", result.getName())); } - // todo(mderka) Test field options within #665. } /** @@ -873,7 +873,6 @@ we will reset all IDs in this range (all of them are valid) */ String.format("Error when serializing change %s in managed zone %s in project %s.", result.getId(), zoneName, projectId)); } - // todo(mderka) Test field options within #665. } /** @@ -969,13 +968,13 @@ Response listZones(String projectId, Map options) { ManagedZone zone = zoneContainer.zone(); if (listing) { if (dnsName == null || zone.getDnsName().equals(dnsName)) { - lastZoneName = zone.getName(); if (sizeReached) { // we do not add this, just note that there would be more and there should be a token hasMorePages = true; break; } else { try { + lastZoneName = zone.getName(); serializedZones.addLast(jsonFactory.toString( OptionParsersAndExtractors.extractFields(zone, fields))); } catch (IOException e) { @@ -991,9 +990,8 @@ Response listZones(String projectId, Map options) { sizeReached = (maxResults != null) && maxResults.equals(serializedZones.size()); } boolean includePageToken = - hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("pageToken")); - return toListResponse(serializedZones, lastZoneName, includePageToken); - // todo(mderka) Test field and listing options within #665. + hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("nextPageToken")); + return toListResponse(serializedZones, "managedZones", lastZoneName, includePageToken); } /** @@ -1025,12 +1023,12 @@ Response listDnsRecords(String projectId, String zoneName, Map o ResourceRecordSet record = recordWrapper.rrset(); if (listing) { if (matchesCriteria(record, name, type)) { - lastRecordId = recordWrapper.id(); if (sizeReached) { // we do not add this, just note that there would be more and there should be a token hasMorePages = true; break; } else { + lastRecordId = recordWrapper.id(); try { serializedRrsets.addLast(jsonFactory.toString( OptionParsersAndExtractors.extractFields(record, fields))); @@ -1047,9 +1045,8 @@ Response listDnsRecords(String projectId, String zoneName, Map o sizeReached = (maxResults != null) && maxResults.equals(serializedRrsets.size()); } boolean includePageToken = - hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("pageToken")); - return toListResponse(serializedRrsets, lastRecordId, includePageToken); - // todo(mderka) Test field and listing options within #665. + hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("nextPageToken")); + return toListResponse(serializedRrsets, "rrsets", lastRecordId, includePageToken); } /** @@ -1061,6 +1058,10 @@ Response listChanges(String projectId, String zoneName, Map opti return response; } ZoneContainer zoneContainer = findZone(projectId, zoneName); + if (zoneContainer == null) { + return Error.NOT_FOUND.response(String.format( + "The 'parameters.managedZone' resource named '%s' does not exist", zoneName)); + } // take a sorted snapshot of the current change list TreeMap changes = new TreeMap<>(); for (Change c : zoneContainer.changes()) { @@ -1088,12 +1089,12 @@ Response listChanges(String projectId, String zoneName, Map opti for (Integer key : keys) { Change change = changes.get(key); if (listing) { - lastChangeId = change.getId(); if (sizeReached) { // we do not add this, just note that there would be more and there should be a token hasMorePages = true; break; } else { + lastChangeId = change.getId(); try { serializedResults.addLast(jsonFactory.toString( OptionParsersAndExtractors.extractFields(change, fields))); @@ -1110,9 +1111,8 @@ Response listChanges(String projectId, String zoneName, Map opti sizeReached = (maxResults != null) && maxResults.equals(serializedResults.size()); } boolean includePageToken = - hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("pageToken")); - return toListResponse(serializedResults, lastChangeId, includePageToken); - // todo(mderka) Test field and listing options within #665. + hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("nextPageToken")); + return toListResponse(serializedResults, "changes", lastChangeId, includePageToken); } /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java b/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java index f94cb15779ca..26759f7e3ccc 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java @@ -42,14 +42,19 @@ static Map parseListZonesOptions(String query) { switch (argEntry[0]) { case "fields": // List fields are in the form "managedZones(field1, field2, ...)" + String replaced = argEntry[1].replace("managedZones(", ","); + replaced = replaced.replace(")", ","); + // we will get empty strings, but it does not matter, they will be ignored options.put( "fields", - argEntry[1].substring("managedZones(".length(), argEntry[1].length() - 1) - .split(",")); + replaced.split(",")); break; case "dnsName": options.put("dnsName", argEntry[1]); break; + case "nextPageToken": + options.put("nextPageToken", argEntry[1]); + break; case "pageToken": options.put("pageToken", argEntry[1]); break; @@ -218,14 +223,16 @@ static Map parseListChangesOptions(String query) { String[] argEntry = arg.split("="); switch (argEntry[0]) { case "fields": - // todo we do not support fragmentation in deletions and additions - options.put( - "fields", - argEntry[1].substring("changes(".length(), argEntry[1].length() - 1).split(",")); + // todo we do not support fragmentation in deletions and additions in the library + String replaced = argEntry[1].replace("changes(", ",").replace(")", ","); + options.put("fields", replaced.split(",")); // empty strings will be ignored break; case "name": options.put("name", argEntry[1]); break; + case "nextPageToken": + options.put("nextPageToken", argEntry[1]); + break; case "pageToken": options.put("pageToken", argEntry[1]); break; @@ -255,16 +262,22 @@ static Map parseListDnsRecordsOptions(String query) { String[] argEntry = arg.split("="); switch (argEntry[0]) { case "fields": - options.put( - "fields", - argEntry[1].substring("rrsets(".length(), argEntry[1].length() - 1).split(",")); + String replace = argEntry[1].replace("rrsets(", ","); + replace = replace.replace(")", ","); + options.put("fields", replace.split(",")); // empty strings do not matter break; case "name": options.put("name", argEntry[1]); break; + case "type": + options.put("type", argEntry[1]); + break; case "pageToken": options.put("pageToken", argEntry[1]); break; + case "nextPageToken": + options.put("nextPageToken", argEntry[1]); + break; case "maxResults": // parsing to int is done while handling options.put("maxResults", argEntry[1]); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java index 1f851045659c..7a97b69846ef 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/testing/LocalDnsHelperTest.java @@ -18,6 +18,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -25,11 +26,16 @@ import com.google.api.services.dns.model.Change; import com.google.api.services.dns.model.ManagedZone; +import com.google.api.services.dns.model.Project; import com.google.api.services.dns.model.ResourceRecordSet; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; +import com.google.gcloud.dns.DnsException; +import com.google.gcloud.spi.DefaultDnsRpc; +import com.google.gcloud.spi.DnsRpc; -import org.junit.After; +import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -55,8 +61,14 @@ public class LocalDnsHelperTest { private static final Change CHANGE1 = new Change(); private static final Change CHANGE2 = new Change(); private static final Change CHANGE_KEEP = new Change(); + private static final Change CHANGE_COMPLEX = new Change(); + private static final LocalDnsHelper LOCAL_DNS_HELPER = LocalDnsHelper.create(0L); // synchronous + private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); + private static final DnsRpc RPC = + new DefaultDnsRpc(LOCAL_DNS_HELPER.options()); + private static final String REAL_PROJECT_ID = LOCAL_DNS_HELPER.options().projectId(); private Map optionsMap; - private LocalDnsHelper localDns; + private ManagedZone minimalZone = new ManagedZone(); // to be adjusted as needed @BeforeClass @@ -67,9 +79,11 @@ public static void before() { ZONE1.setName(ZONE_NAME1); ZONE1.setDescription(""); ZONE1.setDnsName(DNS_NAME); + ZONE1.setNameServerSet("somenameserveset"); ZONE2.setName(ZONE_NAME2); ZONE2.setDescription(""); ZONE2.setDnsName(DNS_NAME); + ZONE2.setNameServerSet("somenameserveset"); RRSET2.setName(DNS_NAME); RRSET2.setType(RRSET_TYPE); RRSET_KEEP.setName(DNS_NAME); @@ -79,18 +93,27 @@ public static void before() { CHANGE1.setAdditions(ImmutableList.of(RRSET1, RRSET2)); CHANGE2.setDeletions(ImmutableList.of(RRSET2)); CHANGE_KEEP.setAdditions(ImmutableList.of(RRSET_KEEP)); + CHANGE_COMPLEX.setAdditions(ImmutableList.of(RRSET_KEEP)); + CHANGE_COMPLEX.setDeletions(ImmutableList.of(RRSET_KEEP)); + LOCAL_DNS_HELPER.start(); } @Before public void setUp() { - localDns = LocalDnsHelper.create(0L); // synchronous + resetProjects(); optionsMap = new HashMap<>(); minimalZone = copyZone(ZONE1); } - @After - public void after() { - localDns = null; + private static void resetProjects() { + for (String project : LOCAL_DNS_HELPER.projects().keySet()) { + LOCAL_DNS_HELPER.projects().remove(project); + } + } + + @AfterClass + public static void after() { + LOCAL_DNS_HELPER.stop(); } @Test @@ -109,13 +132,13 @@ public void testGetUniqueId() { @Test public void testFindProject() { - assertEquals(0, localDns.projects().size()); - LocalDnsHelper.ProjectContainer project = localDns.findProject(PROJECT_ID1); + assertEquals(0, LOCAL_DNS_HELPER.projects().size()); + LocalDnsHelper.ProjectContainer project = LOCAL_DNS_HELPER.findProject(PROJECT_ID1); assertNotNull(project); - assertTrue(localDns.projects().containsKey(PROJECT_ID1)); - assertNotNull(localDns.findProject(PROJECT_ID2)); - assertTrue(localDns.projects().containsKey(PROJECT_ID2)); - assertTrue(localDns.projects().containsKey(PROJECT_ID1)); + assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID1)); + assertNotNull(LOCAL_DNS_HELPER.findProject(PROJECT_ID2)); + assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID2)); + assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID1)); assertNotNull(project.zones()); assertEquals(0, project.zones().size()); assertNotNull(project.project()); @@ -124,11 +147,11 @@ public void testFindProject() { @Test public void testCreateAndFindZone() { - LocalDnsHelper.ZoneContainer zone1 = localDns.findZone(PROJECT_ID1, ZONE_NAME1); - assertTrue(localDns.projects().containsKey(PROJECT_ID1)); + LocalDnsHelper.ZoneContainer zone1 = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1); + assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID1)); assertNull(zone1); - localDns.createZone(PROJECT_ID1, ZONE1, null); // we do not care about options - zone1 = localDns.findZone(PROJECT_ID1, ZONE1.getName()); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); // we do not care about options + zone1 = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName()); assertNotNull(zone1); // cannot call equals because id and timestamp got assigned assertEquals(ZONE_NAME1, zone1.zone().getName()); @@ -136,56 +159,99 @@ public void testCreateAndFindZone() { assertTrue(zone1.changes().isEmpty()); assertNotNull(zone1.dnsRecords()); assertEquals(2, zone1.dnsRecords().get(ZONE_NAME1).size()); // default SOA and NS - localDns.createZone(PROJECT_ID2, ZONE1, null); // project does not exits yet - assertEquals(ZONE1.getName(), localDns.findZone(PROJECT_ID2, ZONE_NAME1).zone().getName()); + LOCAL_DNS_HELPER.createZone(PROJECT_ID2, ZONE1, null); // project does not exits yet + assertEquals(ZONE1.getName(), + LOCAL_DNS_HELPER.findZone(PROJECT_ID2, ZONE_NAME1).zone().getName()); + } + + @Test + public void testCreateAndFindZoneUsingRpc() { + // zone does not exist yet + ManagedZone zone1 = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); + assertTrue(LOCAL_DNS_HELPER.projects().containsKey(REAL_PROJECT_ID)); // check internal state + assertNull(zone1); + // create zone + ManagedZone createdZone = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + assertEquals(ZONE1.getName(), createdZone.getName()); + assertEquals(ZONE1.getDescription(), createdZone.getDescription()); + assertEquals(ZONE1.getDnsName(), createdZone.getDnsName()); + assertEquals(4, createdZone.getNameServers().size()); + // get the same zone zone + ManagedZone zone = RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS); + assertEquals(createdZone, zone); + // check that default records were created + DnsRpc.ListResult resourceRecordSetListResult + = RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS); + assertEquals(2, Lists.newLinkedList(resourceRecordSetListResult.results()).size()); } @Test public void testDeleteZone() { - localDns.createZone(PROJECT_ID1, ZONE1, null); - LocalDnsHelper.Response response = localDns.deleteZone(PROJECT_ID1, ZONE1.getName()); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE1.getName()); assertEquals(204, response.code()); // deleting non-existent zone - response = localDns.deleteZone(PROJECT_ID1, ZONE1.getName()); + response = LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE1.getName()); assertEquals(404, response.code()); - assertNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); - localDns.createZone(PROJECT_ID1, ZONE1, null); - localDns.createZone(PROJECT_ID1, ZONE2, null); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE2.getName())); + assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE2, null); + assertNotNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); + assertNotNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE2.getName())); // delete in reverse order - response = localDns.deleteZone(PROJECT_ID1, ZONE1.getName()); + response = LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE1.getName()); assertEquals(204, response.code()); - assertNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE2.getName())); - localDns.deleteZone(PROJECT_ID1, ZONE2.getName()); + assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); + assertNotNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE2.getName())); + LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE2.getName()); assertEquals(204, response.code()); - assertNull(localDns.findZone(PROJECT_ID1, ZONE1.getName())); - assertNull(localDns.findZone(PROJECT_ID1, ZONE2.getName())); + assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); + assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE2.getName())); + } + + @Test + public void testDeleteZoneUsingRpc() { + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + assertTrue(RPC.deleteZone(ZONE1.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + // deleting non-existent zone + assertFalse(RPC.deleteZone(ZONE1.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + RPC.create(ZONE2, EMPTY_RPC_OPTIONS); + assertNotNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + assertNotNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); + // delete in reverse order + assertTrue(RPC.deleteZone(ZONE1.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + assertNotNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); + assertTrue(RPC.deleteZone(ZONE2.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + assertNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); } @Test public void testCreateAndApplyChange() { - localDns = LocalDnsHelper.create(5 * 1000L); // we will be using threads here - localDns.createZone(PROJECT_ID1, ZONE1, null); - assertNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + LocalDnsHelper localDnsThreaded = LocalDnsHelper.create(5 * 1000L); // using threads here + localDnsThreaded.createZone(PROJECT_ID1, ZONE1, null); + assertNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); LocalDnsHelper.Response response - = localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add + = localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add assertEquals(200, response.code()); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - assertNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add + assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + assertNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); + localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add + response = localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add assertEquals(200, response.code()); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); // delete - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); - assertNotNull(localDns.findZone(PROJECT_ID1, ZONE_NAME1).findChange("3")); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE_KEEP, null); // id is "4" + assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); + localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); // delete + assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); + assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); + assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("3")); + localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE_KEEP, null); // id is "4" // check execution - Change change = localDns.findChange(PROJECT_ID1, ZONE_NAME1, "4"); + Change change = localDnsThreaded.findChange(PROJECT_ID1, ZONE_NAME1, "4"); for (int i = 0; i < 10 && !change.getStatus().equals("done"); i++) { // change has not been finished yet; wait at most 20 seconds // it takes 5 seconds for the thread to kick in in the first place @@ -197,26 +263,70 @@ public void testCreateAndApplyChange() { } assertEquals("done", change.getStatus()); List list = - localDns.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); + localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); assertTrue(list.contains(new LocalDnsHelper.RrsetWrapper(RRSET_KEEP))); + localDnsThreaded.stop(); + } + + @Test + public void testCreateAndApplyChangeUsingRpc() { + // not using threads + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + assertNull(RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); + //add + Change createdChange = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + assertEquals(createdChange.getAdditions(), CHANGE1.getAdditions()); + assertEquals(createdChange.getDeletions(), CHANGE1.getDeletions()); + assertNotNull(createdChange.getStartTime()); + assertEquals("1", createdChange.getId()); + Change retrievedChange = RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS); + assertEquals(createdChange, retrievedChange); + assertNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + try { + Change anotherChange = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + } catch (DnsException ex) { + assertEquals(409, ex.code()); + } + assertNotNull(RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); + assertNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + // delete + RPC.applyChangeRequest(ZONE1.getName(), CHANGE2, EMPTY_RPC_OPTIONS); + assertNotNull(RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); + assertNotNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + Change last = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + assertEquals("done", last.getStatus()); + // todo(mderka) replace with real call + List list = + LOCAL_DNS_HELPER.findZone(REAL_PROJECT_ID, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); + assertTrue(list.contains(new LocalDnsHelper.RrsetWrapper(RRSET_KEEP))); + Iterable results = + RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + boolean ok = false; + for (ResourceRecordSet dnsRecord : results) { + if (dnsRecord.getName().equals(RRSET_KEEP.getName()) + && dnsRecord.getType().equals(RRSET_KEEP.getType())) { + ok = true; + } + } + assertTrue(ok); } @Test public void testFindChange() { - localDns.createZone(PROJECT_ID1, ZONE1, null); - Change change = localDns.findChange(PROJECT_ID1, ZONE1.getName(), "somerandomchange"); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + Change change = LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "somerandomchange"); assertNull(change); - localDns.createChange(PROJECT_ID1, ZONE1.getName(), CHANGE1, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE1.getName(), CHANGE1, null); // changes are sequential so we should find ID 1 - assertNotNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "1")); + assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "1")); // add another - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); - assertNotNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "1")); - assertNotNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "2")); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); + assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "1")); + assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "2")); // try to find non-existent change - assertNull(localDns.findChange(PROJECT_ID1, ZONE1.getName(), "3")); + assertNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "3")); // try to find a change in yet non-existent project - assertNull(localDns.findChange(PROJECT_ID2, ZONE1.getName(), "3")); + assertNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID2, ZONE1.getName(), "3")); } @Test @@ -230,71 +340,375 @@ public void testRandomNameServers() { @Test public void testGetProject() { // only interested in no exceptions and non-null response here - assertNotNull(localDns.getProject(PROJECT_ID1, null)); - assertNotNull(localDns.getProject(PROJECT_ID2, null)); + assertNotNull(LOCAL_DNS_HELPER.getProject(PROJECT_ID1, null)); + assertNotNull(LOCAL_DNS_HELPER.getProject(PROJECT_ID2, null)); + Project project = RPC.getProject(EMPTY_RPC_OPTIONS); + assertNotNull(project.getQuota()); + assertEquals(REAL_PROJECT_ID, project.getId()); + // fields options + Map options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "number"); + project = RPC.getProject(options); + assertNull(project.getId()); + assertNotNull(project.getNumber()); + assertNull(project.getQuota()); + options.put(DnsRpc.Option.FIELDS, "id"); + project = RPC.getProject(options); + assertNotNull(project.getId()); + assertNull(project.getNumber()); + assertNull(project.getQuota()); + options.put(DnsRpc.Option.FIELDS, "quota"); + project = RPC.getProject(options); + assertNull(project.getId()); + assertNull(project.getNumber()); + assertNotNull(project.getQuota()); } @Test public void testGetZone() { // non-existent - LocalDnsHelper.Response response = localDns.getZone(PROJECT_ID1, ZONE_NAME1, null); + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.getZone(PROJECT_ID1, ZONE_NAME1, null); assertEquals(404, response.code()); assertTrue(response.body().contains("does not exist")); // existent - localDns.createZone(PROJECT_ID1, ZONE1, null); - response = localDns.getZone(PROJECT_ID1, ZONE1.getName(), null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + response = LOCAL_DNS_HELPER.getZone(PROJECT_ID1, ZONE1.getName(), null); assertEquals(200, response.code()); } + @Test + public void testGetZoneUsingRpc() { + // non-existent + assertNull(RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS)); + // existent + ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + ManagedZone zone = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); + assertEquals(created, zone); + assertEquals(ZONE1.getName(), zone.getName()); + // field options + Map options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "id"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNotNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "creationTime"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNotNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "dnsName"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNotNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "description"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "nameServers"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNotNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "nameServerSet"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNotNull(zone.getNameServerSet()); + assertNull(zone.getId()); + // several combined + options.put(DnsRpc.Option.FIELDS, "nameServerSet,description,id,name"); + zone = RPC.getZone(ZONE1.getName(), options); + assertNull(zone.getCreationTime()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNotNull(zone.getNameServerSet()); + assertNotNull(zone.getId()); + } + @Test public void testCreateZone() { // only interested in no exceptions and non-null response here - LocalDnsHelper.Response response = localDns.createZone(PROJECT_ID1, ZONE1, null); + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); assertEquals(200, response.code()); - assertEquals(1, localDns.projects().get(PROJECT_ID1).zones().size()); + assertEquals(1, LOCAL_DNS_HELPER.projects().get(PROJECT_ID1).zones().size()); try { - localDns.createZone(PROJECT_ID1, null, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, null, null); fail("Zone cannot be null"); } catch (NullPointerException ex) { // expected } // create zone twice - response = localDns.createZone(PROJECT_ID1, ZONE1, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); assertEquals(409, response.code()); assertTrue(response.body().contains("already exists")); } + @Test + public void testCreateZoneUsingRpc() { + ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + assertEquals(created, LOCAL_DNS_HELPER.findZone(REAL_PROJECT_ID, ZONE1.getName()).zone()); + ManagedZone zone = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); + assertEquals(created, zone); + try { + RPC.create(null, EMPTY_RPC_OPTIONS); + fail("Zone cannot be null"); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("entity.managedZone")); + } + // create zone twice + try { + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + } catch (DnsException ex) { + // expected + assertEquals(409, ex.code()); + assertTrue(ex.getMessage().contains("already exists")); + } + // field options + resetProjects(); + Map options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "id"); + zone = RPC.create(ZONE1, options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNotNull(zone.getId()); + resetProjects(); + options.put(DnsRpc.Option.FIELDS, "creationTime"); + zone = RPC.create(ZONE1, options); + assertNotNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "dnsName"); + resetProjects(); + zone = RPC.create(ZONE1, options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNotNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "description"); + resetProjects(); + zone = RPC.create(ZONE1, options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "nameServers"); + resetProjects(); + zone = RPC.create(ZONE1, options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNotNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "nameServerSet"); + resetProjects(); + zone = RPC.create(ZONE1, options); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNotNull(zone.getNameServerSet()); + assertNull(zone.getId()); + // several combined + options.put(DnsRpc.Option.FIELDS, "nameServerSet,description,id,name"); + resetProjects(); + zone = RPC.create(ZONE1, options); + assertNull(zone.getCreationTime()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNotNull(zone.getNameServerSet()); + assertNotNull(zone.getId()); + } + @Test public void testCreateChange() { // non-existent zone LocalDnsHelper.Response response = - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); assertEquals(404, response.code()); - // existent zone - assertNotNull(localDns.createZone(PROJECT_ID1, ZONE1, null)); - assertNull(localDns.findChange(PROJECT_ID1, ZONE_NAME1, "1")); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + assertNotNull(LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null)); + assertNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE_NAME1, "1")); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); assertEquals(200, response.code()); - assertNotNull(localDns.findChange(PROJECT_ID1, ZONE_NAME1, "1")); + assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE_NAME1, "1")); + } + + @Test + public void testCreateChangeUsingRpc() { + // non-existent zone + try { + RPC.applyChangeRequest(ZONE_NAME1, CHANGE1, EMPTY_RPC_OPTIONS); + } catch (DnsException ex) { + assertEquals(404, ex.code()); + } + // existent zone + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + assertNull(RPC.getChangeRequest(ZONE_NAME1, "1", EMPTY_RPC_OPTIONS)); + Change created = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + assertEquals(created, RPC.getChangeRequest(ZONE_NAME1, "1", EMPTY_RPC_OPTIONS)); + // field options + RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + Map options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "additions"); + Change complex = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, options); + assertNotNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "deletions"); + complex = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, options); + assertNull(complex.getAdditions()); + assertNotNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "id"); + complex = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, options); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNotNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "startTime"); + complex = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, options); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNotNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "status"); + complex = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, options); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNotNull(complex.getStatus()); } @Test public void testGetChange() { // existent - assertEquals(200, localDns.createZone(PROJECT_ID1, ZONE1, null).code()); - assertEquals(200, localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null).code()); - assertEquals(200, localDns.getChange(PROJECT_ID1, ZONE_NAME1, "1", null).code()); + assertEquals(200, LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null).code()); + assertEquals(200, LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null).code()); + assertEquals(200, LOCAL_DNS_HELPER.getChange(PROJECT_ID1, ZONE_NAME1, "1", null).code()); // non-existent - LocalDnsHelper.Response response = localDns.getChange(PROJECT_ID1, ZONE_NAME1, "2", null); + LocalDnsHelper.Response response = + LOCAL_DNS_HELPER.getChange(PROJECT_ID1, ZONE_NAME1, "2", null); assertEquals(404, response.code()); assertTrue(response.body().contains("parameters.changeId")); // non-existent zone - response = localDns.getChange(PROJECT_ID1, ZONE_NAME2, "1", null); + response = LOCAL_DNS_HELPER.getChange(PROJECT_ID1, ZONE_NAME2, "1", null); assertEquals(404, response.code()); assertTrue(response.body().contains("parameters.managedZone")); } + @Test + public void testGetChangeUsingRpc() { + // existent + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + Change created = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + Change retrieved = RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS); + assertEquals(created, retrieved); + // non-existent + assertNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + // non-existent zone + try { + RPC.getChangeRequest(ZONE_NAME2, "1", EMPTY_RPC_OPTIONS); + } catch (DnsException ex) { + // expected + assertEquals(404, ex.code()); + } + // field options + RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + Change change = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, EMPTY_RPC_OPTIONS); + Map options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "additions"); + Change complex = RPC.getChangeRequest(ZONE1.getName(), change.getId(), options); + assertNotNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "deletions"); + complex = RPC.getChangeRequest(ZONE1.getName(), change.getId(), options); + assertNull(complex.getAdditions()); + assertNotNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "id"); + complex = RPC.getChangeRequest(ZONE1.getName(), change.getId(), options); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNotNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "startTime"); + complex = RPC.getChangeRequest(ZONE1.getName(), change.getId(), options); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNotNull(complex.getStartTime()); + assertNull(complex.getStatus()); + options.put(DnsRpc.Option.FIELDS, "status"); + complex = RPC.getChangeRequest(ZONE1.getName(), change.getId(), options); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNotNull(complex.getStatus()); + } + @Test public void testListZones() { // only interested in no exceptions and non-null response here @@ -302,36 +716,175 @@ public void testListZones() { optionsMap.put("fields", null); optionsMap.put("pageToken", null); optionsMap.put("maxResults", null); - LocalDnsHelper.Response response = localDns.listZones(PROJECT_ID1, optionsMap); + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); // some zones exists - localDns.createZone(PROJECT_ID1, ZONE1, null); - response = localDns.listZones(PROJECT_ID1, optionsMap); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); - localDns.createZone(PROJECT_ID1, ZONE2, null); - response = localDns.listZones(PROJECT_ID1, optionsMap); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE2, null); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); // error in options optionsMap.put("maxResults", "aaa"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "0"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "-1"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "15"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); optionsMap.put("dnsName", "aaa"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("dnsName", "aaa."); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); } + @Test + public void testListZonesUsingRpc() { + Iterable results = RPC.listZones(EMPTY_RPC_OPTIONS).results(); + ImmutableList zones = ImmutableList.copyOf(results); + assertEquals(0, zones.size()); + // some zones exists + ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + results = RPC.listZones(EMPTY_RPC_OPTIONS).results(); + zones = ImmutableList.copyOf(results); + assertEquals(created, zones.get(0)); + assertEquals(1, zones.size()); + created = RPC.create(ZONE2, EMPTY_RPC_OPTIONS); + results = RPC.listZones(EMPTY_RPC_OPTIONS).results(); + zones = ImmutableList.copyOf(results); + assertEquals(2, zones.size()); + assertTrue(zones.contains(created)); + // error in options + Map options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 0); + try { + RPC.listZones(options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, -1); + try { + RPC.listZones(options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + // ok size + options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + results = RPC.listZones(options).results(); + zones = ImmutableList.copyOf(results); + assertEquals(1, zones.size()); + // dns name problems + options = new HashMap<>(); + options.put(DnsRpc.Option.DNS_NAME, "aaa"); + try { + RPC.listZones(options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + // ok name + options = new HashMap<>(); + options.put(DnsRpc.Option.DNS_NAME, "aaaa."); + results = RPC.listZones(options).results(); + zones = ImmutableList.copyOf(results); + assertEquals(0, zones.size()); + // field options + options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "managedZones(id)"); + ManagedZone zone = RPC.listZones(options).results().iterator().next(); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNotNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "managedZones(creationTime)"); + zone = RPC.listZones(options).results().iterator().next(); + assertNotNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "managedZones(dnsName)"); + zone = RPC.listZones(options).results().iterator().next(); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNotNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "managedZones(description)"); + zone = RPC.listZones(options).results().iterator().next(); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "managedZones(nameServers)"); + zone = RPC.listZones(options).results().iterator().next(); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNotNull(zone.getNameServers()); + assertNull(zone.getNameServerSet()); + assertNull(zone.getId()); + options.put(DnsRpc.Option.FIELDS, "managedZones(nameServerSet)"); + DnsRpc.ListResult managedZoneListResult = RPC.listZones(options); + zone = managedZoneListResult.results().iterator().next(); + assertNull(managedZoneListResult.pageToken()); + assertNull(zone.getCreationTime()); + assertNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNotNull(zone.getNameServerSet()); + assertNull(zone.getId()); + // several combined + options.put(DnsRpc.Option.FIELDS, + "managedZones(nameServerSet,description,id,name),nextPageToken"); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + managedZoneListResult = RPC.listZones(options); + zone = managedZoneListResult.results().iterator().next(); + assertNull(zone.getCreationTime()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServers()); + assertNotNull(zone.getNameServerSet()); + assertNotNull(zone.getId()); + assertEquals(zone.getName(), managedZoneListResult.pageToken()); + // paging + options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + managedZoneListResult = RPC.listZones(options); + ImmutableList page1 = ImmutableList.copyOf(managedZoneListResult.results()); + assertEquals(1, page1.size()); + options.put(DnsRpc.Option.PAGE_TOKEN, managedZoneListResult.pageToken()); + managedZoneListResult = RPC.listZones(options); + ImmutableList page2 = ImmutableList.copyOf(managedZoneListResult.results()); + assertEquals(1, page2.size()); + assertNotEquals(page1.get(0), page2.get(0)); + } + @Test public void testListDnsRecords() { // only interested in no exceptions and non-null response here @@ -341,49 +894,196 @@ public void testListDnsRecords() { optionsMap.put("pageToken", null); optionsMap.put("maxResults", null); // no zone exists - LocalDnsHelper.Response response = localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(404, response.code()); // zone exists but has no records - localDns.createZone(PROJECT_ID1, ZONE1, null); - localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + LOCAL_DNS_HELPER.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); // zone has records - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - response = localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + response = LOCAL_DNS_HELPER.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(200, response.code()); // error in options optionsMap.put("maxResults", "aaa"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "0"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "-1"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "15"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); optionsMap.put("name", "aaa"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("name", "aaa."); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); optionsMap.put("name", null); optionsMap.put("type", "A"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("name", "aaa."); optionsMap.put("type", "a"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(400, response.code()); optionsMap.put("name", "aaaa."); optionsMap.put("type", "A"); - response = localDns.listZones(PROJECT_ID1, optionsMap); + response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); assertEquals(200, response.code()); } + @Test + public void testListDnsRecordsUsingRpc() { + // no zone exists + try { + RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS); + } catch (DnsException ex) { + // expected + assertEquals(404, ex.code()); + } + // zone exists but has no records + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + Iterable results = + RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); + ImmutableList records = ImmutableList.copyOf(results); + assertEquals(2, records.size()); // contains default NS and SOA + // zone has records + RPC.applyChangeRequest(ZONE_NAME1, CHANGE_KEEP, EMPTY_RPC_OPTIONS); + results = RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); + records = ImmutableList.copyOf(results); + assertEquals(3, records.size()); + // error in options + Map options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 0); + try { + RPC.listDnsRecords(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.PAGE_SIZE, -1); + try { + RPC.listDnsRecords(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.PAGE_SIZE, 1); + results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + records = ImmutableList.copyOf(results); + assertEquals(1, records.size()); + options.put(DnsRpc.Option.PAGE_SIZE, 15); + results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + records = ImmutableList.copyOf(results); + assertEquals(3, records.size()); + + // dnsName filter + options = new HashMap<>(); + options.put(DnsRpc.Option.NAME, "aaa"); + try { + RPC.listDnsRecords(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.NAME, "aaa."); + results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + records = ImmutableList.copyOf(results); + assertEquals(0, records.size()); + options.put(DnsRpc.Option.NAME, null); + options.put(DnsRpc.Option.DNS_TYPE, "A"); + try { + RPC.listDnsRecords(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.NAME, "aaa."); + options.put(DnsRpc.Option.DNS_TYPE, "a"); + try { + RPC.listDnsRecords(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.NAME, DNS_NAME); + options.put(DnsRpc.Option.DNS_TYPE, "SOA"); + results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + records = ImmutableList.copyOf(results); + assertEquals(1, records.size()); + // field options + options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "rrsets(name)"); + DnsRpc.ListResult resourceRecordSetListResult = + RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + ResourceRecordSet record = records.get(0); + assertNotNull(record.getName()); + assertNull(record.getRrdatas()); + assertNull(record.getType()); + assertNull(record.getTtl()); + assertNull(resourceRecordSetListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "rrsets(rrdatas)"); + resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + record = records.get(0); + assertNull(record.getName()); + assertNotNull(record.getRrdatas()); + assertNull(record.getType()); + assertNull(record.getTtl()); + assertNull(resourceRecordSetListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "rrsets(ttl)"); + resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + record = records.get(0); + assertNull(record.getName()); + assertNull(record.getRrdatas()); + assertNull(record.getType()); + assertNotNull(record.getTtl()); + assertNull(resourceRecordSetListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "rrsets(type)"); + resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + record = records.get(0); + assertNull(record.getName()); + assertNull(record.getRrdatas()); + assertNotNull(record.getType()); + assertNull(record.getTtl()); + assertNull(resourceRecordSetListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "nextPageToken"); + resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + record = records.get(0); + assertNull(record.getName()); + assertNull(record.getRrdatas()); + assertNull(record.getType()); + assertNull(record.getTtl()); + assertNull(resourceRecordSetListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "nextPageToken,rrsets(name,rrdatas)"); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + assertEquals(1, records.size()); + record = records.get(0); + assertNotNull(record.getName()); + assertNotNull(record.getRrdatas()); + assertNull(record.getType()); + assertNull(record.getTtl()); + assertNotNull(resourceRecordSetListResult.pageToken()); + // paging + options.put(DnsRpc.Option.PAGE_TOKEN, resourceRecordSetListResult.pageToken()); + resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + assertEquals(1, records.size()); + ResourceRecordSet nextRecord = records.get(0); + assertNotEquals(record, nextRecord); + } + @Test public void testListChanges() { optionsMap.put("sortBy", null); @@ -392,72 +1092,214 @@ public void testListChanges() { optionsMap.put("pageToken", null); optionsMap.put("maxResults", null); // no such zone exists - LocalDnsHelper.Response response = localDns.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); + LocalDnsHelper.Response response = + LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(404, response.code()); assertTrue(response.body().contains("managedZone")); // zone exists but has no changes - localDns.createZone(PROJECT_ID1, ZONE1, null); - assertNotNull(localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + assertNotNull(LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); // zone has changes - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - assertNotNull(localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); - assertNotNull(localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + assertNotNull(LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); + assertNotNull(LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); // error in options optionsMap.put("maxResults", "aaa"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "0"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "-1"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(400, response.code()); optionsMap.put("maxResults", "15"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("dnsName", "aaa"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("dnsName", "aaa."); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(200, response.code()); optionsMap.put("sortBy", "changeSequence"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(200, response.code()); optionsMap.put("sortBy", "something else"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(400, response.code()); assertTrue(response.body().contains("Allowed values: [changesequence]")); optionsMap.put("sortBy", "ChAnGeSeQuEnCe"); // is not case sensitive - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(200, response.code()); optionsMap.put("sortOrder", "ascending"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(200, response.code()); optionsMap.put("sortBy", null); optionsMap.put("sortOrder", "descending"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(200, response.code()); optionsMap.put("sortOrder", "somethingelse"); - response = localDns.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); + response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); assertEquals(400, response.code()); assertTrue(response.body().contains("parameters.sortOrder")); } + @Test + public void testListChangesUsingRpc() { + // no such zone exists + try { + RPC.listChangeRequests(ZONE_NAME1, EMPTY_RPC_OPTIONS); + } catch (DnsException ex) { + // expected + assertEquals(404, ex.code()); + } + // zone exists but has no changes + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + Iterable results = RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + ImmutableList changes = ImmutableList.copyOf(results); + assertEquals(0, changes.size()); + // zone has changes + RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + RPC.applyChangeRequest(ZONE1.getName(), CHANGE2, EMPTY_RPC_OPTIONS); + RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + results = RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + changes = ImmutableList.copyOf(results); + assertEquals(3, changes.size()); + // error in options + Map options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 0); + try { + RPC.listChangeRequests(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.PAGE_SIZE, -1); + try { + RPC.listChangeRequests(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options.put(DnsRpc.Option.PAGE_SIZE, 15); + try { + RPC.listChangeRequests(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + options = new HashMap<>(); + options.put(DnsRpc.Option.SORTING_ORDER, "descending"); + results = RPC.listChangeRequests(ZONE1.getName(), options).results(); + ImmutableList descending = ImmutableList.copyOf(results); + results = RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + ImmutableList ascending = ImmutableList.copyOf(results); + int size = 3; + assertEquals(size, descending.size()); + for (int i = 0; i < size; i++) { + assertEquals(descending.get(i), ascending.get(size - i - 1)); + } + options.put(DnsRpc.Option.SORTING_ORDER, "something else"); + try { + RPC.listChangeRequests(ZONE1.getName(), options); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + } + // field options + RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, EMPTY_RPC_OPTIONS); + options = new HashMap<>(); + options.put(DnsRpc.Option.SORTING_ORDER, "descending"); + options.put(DnsRpc.Option.FIELDS, "changes(additions)"); + DnsRpc.ListResult changeListResult = + RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + Change complex = changes.get(0); + assertNotNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + assertNull(changeListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "changes(deletions)"); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + complex = changes.get(0); + assertNull(complex.getAdditions()); + assertNotNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + assertNull(changeListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "changes(id)"); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + complex = changes.get(0); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNotNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + assertNull(changeListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "changes(startTime)"); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + complex = changes.get(0); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNotNull(complex.getStartTime()); + assertNull(complex.getStatus()); + assertNull(changeListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "changes(status)"); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + complex = changes.get(0); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNotNull(complex.getStatus()); + assertNull(changeListResult.pageToken()); + options.put(DnsRpc.Option.FIELDS, "nextPageToken"); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + complex = changes.get(0); + assertNull(complex.getAdditions()); + assertNull(complex.getDeletions()); + assertNull(complex.getId()); + assertNull(complex.getStartTime()); + assertNull(complex.getStatus()); + assertNotNull(changeListResult.pageToken()); + // paging + options.put(DnsRpc.Option.FIELDS, "nextPageToken,changes(id)"); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + assertEquals(1, changes.size()); + final Change first = changes.get(0); + assertNotNull(changeListResult.pageToken()); + options.put(DnsRpc.Option.PAGE_TOKEN, changeListResult.pageToken()); + changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + changes = ImmutableList.copyOf(changeListResult.results()); + assertEquals(1, changes.size()); + Change second = changes.get(0); + assertNotEquals(first, second); + } + @Test public void testToListResponse() { LocalDnsHelper.Response response = LocalDnsHelper.toListResponse( - Lists.newArrayList("some", "multiple", "words"), "IncludeThisPageToken", true); + Lists.newArrayList("some", "multiple", "words"), "contextA", "IncludeThisPageToken", true); assertTrue(response.body().contains("IncludeThisPageToken")); + assertTrue(response.body().contains("contextA")); response = LocalDnsHelper.toListResponse( - Lists.newArrayList("some", "multiple", "words"), "IncludeThisPageToken", false); + Lists.newArrayList("some", "multiple", "words"), "contextB", "IncludeThisPageToken", false); assertFalse(response.body().contains("IncludeThisPageToken")); + assertTrue(response.body().contains("contextB")); response = LocalDnsHelper.toListResponse( - Lists.newArrayList("some", "multiple", "words"), null, true); + Lists.newArrayList("some", "multiple", "words"), "contextC", null, true); assertFalse(response.body().contains("pageToken")); + assertTrue(response.body().contains("contextC")); } @Test @@ -511,45 +1353,45 @@ public void testCreateZoneValidatesZone() { // no name ManagedZone copy = copyZone(minimalZone); copy.setName(null); - LocalDnsHelper.Response response = localDns.createZone(PROJECT_ID1, copy, null); + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.name")); // no description copy = copyZone(minimalZone); copy.setDescription(null); - response = localDns.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.description")); // no dns name copy = copyZone(minimalZone); copy.setDnsName(null); - response = localDns.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.dnsName")); // zone name is a number copy = copyZone(minimalZone); copy.setName("123456"); - response = localDns.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.name")); assertTrue(response.body().contains("Invalid")); // dns name does not end with period copy = copyZone(minimalZone); copy.setDnsName("aaaaaa.com"); - response = localDns.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.dnsName")); assertTrue(response.body().contains("Invalid")); // dns name is reserved copy = copyZone(minimalZone); copy.setDnsName("com."); - response = localDns.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(400, response.code()); assertTrue(response.body().contains("not available to be created.")); // empty description should pass copy = copyZone(minimalZone); copy.setDescription(""); - response = localDns.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); assertEquals(200, response.code()); } @@ -632,10 +1474,10 @@ public void testCheckRrset() { valid.setTtl(500); Change validChange = new Change(); validChange.setAdditions(ImmutableList.of(valid)); - localDns.createZone(PROJECT_ID1, ZONE1, null); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); // delete with field mismatch - LocalDnsHelper.ZoneContainer zone = localDns.findZone(PROJECT_ID1, ZONE_NAME1); + LocalDnsHelper.ZoneContainer zone = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1); valid.setTtl(valid.getTtl() + 20); LocalDnsHelper.Response response = LocalDnsHelper.checkRrset(valid, zone, 0, "deletions"); assertEquals(412, response.code()); @@ -735,7 +1577,7 @@ public void testCheckChange() { assertTrue(response.body().contains("additions[0].type")); validA.setType("A"); // null rrdata - List temp = validA.getRrdatas(); // preserve + final List temp = validA.getRrdatas(); // preserve validA.setRrdatas(null); response = LocalDnsHelper.checkChange(validChange, zoneContainer); assertEquals(400, response.code()); @@ -762,9 +1604,9 @@ public void testAdditionsMeetDeletions() { validA.setRrdatas(ImmutableList.of("0.255.1.5")); Change validChange = new Change(); validChange.setAdditions(ImmutableList.of(validA)); - localDns.createZone(PROJECT_ID1, ZONE1, null); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - LocalDnsHelper.ZoneContainer container = localDns.findZone(PROJECT_ID1, ZONE_NAME1); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LocalDnsHelper.ZoneContainer container = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1); LocalDnsHelper.Response response = LocalDnsHelper.additionsMeetDeletions(ImmutableList.of(validA), null, container); assertEquals(409, response.code()); @@ -780,23 +1622,23 @@ public void testCreateChangeValidatesChangeContent() { validA.setRrdatas(ImmutableList.of("0.255.1.5")); Change validChange = new Change(); validChange.setAdditions(ImmutableList.of(validA)); - localDns.createZone(PROJECT_ID1, ZONE1, null); - localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); LocalDnsHelper.Response response = - localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(409, response.code()); assertTrue(response.body().contains("already exists")); // delete with field mismatch Change delete = new Change(); validA.setTtl(20); // mismatch delete.setDeletions(ImmutableList.of(validA)); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); assertEquals(412, response.code()); assertTrue(response.body().contains("entity.change.deletions[0]")); // delete and add SOA Change addition = new Change(); ImmutableList rrsetWrappers - = localDns.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); + = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); LinkedList deletions = new LinkedList<>(); LinkedList additions = new LinkedList<>(); for (LocalDnsHelper.RrsetWrapper wrapper : rrsetWrappers) { @@ -811,12 +1653,12 @@ public void testCreateChangeValidatesChangeContent() { } delete.setDeletions(deletions); addition.setAdditions(additions); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'SOA' at the apex")); assertTrue(response.body().contains("deletions[0]")); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'SOA' at the apex")); @@ -836,24 +1678,24 @@ public void testCreateChangeValidatesChangeContent() { } delete.setDeletions(deletions); addition.setAdditions(additions); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'NS' at the apex")); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'NS' at the apex")); assertTrue(response.body().contains("additions[0]")); // change (delete + add) addition.setDeletions(deletions); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); assertEquals(200, response.code()); } @Test public void testCreateChangeValidatesChange() { - localDns.createZone(PROJECT_ID1, ZONE1, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); ResourceRecordSet validA = new ResourceRecordSet(); validA.setName(ZONE1.getDnsName()); validA.setType("A"); @@ -867,52 +1709,52 @@ public void testCreateChangeValidatesChange() { Change invalidChange = new Change(); invalidChange.setAdditions(ImmutableList.of(invalidA)); LocalDnsHelper.Response response = - localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(200, response.code()); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, invalidChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, invalidChange, null); assertEquals(400, response.code()); // only empty additions/deletions Change empty = new Change(); empty.setAdditions(ImmutableList.of()); empty.setDeletions(ImmutableList.of()); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, empty, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, empty, null); assertEquals(400, response.code()); assertTrue(response.body().contains( "The 'entity.change' parameter is required but was missing.")); // non-matching name validA.setName(ZONE1.getDnsName() + ".aaa."); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(400, response.code()); assertTrue(response.body().contains("additions[0].name")); // wrong type validA.setName(ZONE1.getDnsName()); // revert validA.setType("ABCD"); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(400, response.code()); assertTrue(response.body().contains("additions[0].type")); // wrong ttl validA.setType("A"); // revert validA.setTtl(-1); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(400, response.code()); assertTrue(response.body().contains("additions[0].ttl")); validA.setTtl(null); // revert // null name validA.setName(null); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(400, response.code()); assertTrue(response.body().contains("additions[0].name")); validA.setName(ZONE1.getDnsName()); // null type validA.setType(null); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(400, response.code()); assertTrue(response.body().contains("additions[0].type")); validA.setType("A"); // null rrdata - List temp = validA.getRrdatas(); // preserve + final List temp = validA.getRrdatas(); // preserve validA.setRrdatas(null); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); assertEquals(400, response.code()); assertTrue(response.body().contains("additions[0].rrdata")); validA.setRrdatas(temp); @@ -923,7 +1765,7 @@ public void testCreateChangeValidatesChange() { nonExistent.setRrdatas(ImmutableList.of(":::::::")); Change delete = new Change(); delete.setDeletions(ImmutableList.of(nonExistent)); - response = localDns.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); assertEquals(404, response.code()); assertTrue(response.body().contains("deletions[0]")); } From cbf737da9a05d69355199bf979e8e2b950aa56e1 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 24 Feb 2016 08:45:58 -0800 Subject: [PATCH 52/74] Added integration tests. --- .../main/java/com/google/gcloud/dns/Dns.java | 17 +- .../com/google/gcloud/spi/DefaultDnsRpc.java | 4 +- .../com/google/gcloud/dns/DnsImplTest.java | 2 +- .../java/com/google/gcloud/dns/DnsTest.java | 2 +- .../java/com/google/gcloud/dns/ITDnsTest.java | 1268 +++++++++++++++++ 5 files changed, 1283 insertions(+), 10 deletions(-) create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 3ad2094ec2e3..b2cb9fbad371 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -68,7 +68,8 @@ static String selector(ProjectField... fields) { * The fields of a zone. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#getZone(String, ZoneOption...)}. The name is always returned, even if not specified. + * {@link Dns#getZone(String, ZoneOption...)}. The name is always returned, even if not + * specified. */ enum ZoneField { CREATION_TIME("creationTime"), @@ -103,8 +104,8 @@ static String selector(ZoneField... fields) { * The fields of a DNS record. * *

These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#listDnsRecords(String, DnsRecordListOption...)}. The name is always returned even if - * not selected. + * {@link Dns#listDnsRecords(String, DnsRecordListOption...)}. The name and type are always + * returned even if not selected. */ enum DnsRecordField { DNS_RECORDS("rrdatas"), @@ -125,6 +126,7 @@ String selector() { static String selector(DnsRecordField... fields) { Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); fieldStrings.add(NAME.selector()); + fieldStrings.add(TYPE.selector()); for (DnsRecordField field : fields) { fieldStrings.add(field.selector()); } @@ -198,7 +200,7 @@ class DnsRecordListOption extends AbstractOption implements Serializable { */ public static DnsRecordListOption fields(DnsRecordField... fields) { StringBuilder builder = new StringBuilder(); - builder.append("rrsets(").append(DnsRecordField.selector(fields)).append(')'); + builder.append("nextPageToken,rrsets(").append(DnsRecordField.selector(fields)).append(')'); return new DnsRecordListOption(DnsRpc.Option.FIELDS, builder.toString()); } @@ -234,7 +236,7 @@ public static DnsRecordListOption dnsName(String dnsName) { * Dns.DnsRecordListOption#dnsName(String)} must also be present. */ public static DnsRecordListOption type(DnsRecord.Type type) { - return new DnsRecordListOption(DnsRpc.Option.DNS_TYPE, type); + return new DnsRecordListOption(DnsRpc.Option.DNS_TYPE, type.name()); } } @@ -281,7 +283,7 @@ class ZoneListOption extends AbstractOption implements Serializable { */ public static ZoneListOption fields(ZoneField... fields) { StringBuilder builder = new StringBuilder(); - builder.append("managedZones(").append(ZoneField.selector(fields)).append(')'); + builder.append("nextPageToken,managedZones(").append(ZoneField.selector(fields)).append(')'); return new ZoneListOption(DnsRpc.Option.FIELDS, builder.toString()); } @@ -388,7 +390,8 @@ class ChangeRequestListOption extends AbstractOption implements Serializable { */ public static ChangeRequestListOption fields(ChangeRequestField... fields) { StringBuilder builder = new StringBuilder(); - builder.append("changes(").append(ChangeRequestField.selector(fields)).append(')'); + builder.append("nextPageToken,changes(").append(ChangeRequestField.selector(fields)) + .append(')'); return new ChangeRequestListOption(DnsRpc.Option.FIELDS, builder.toString()); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index 6ed9c7e0f216..1df0a8a2f831 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -162,7 +162,9 @@ public Change getChangeRequest(String zoneName, String changeRequestId, Map zones = DNS.listZones(); + Iterator zoneIterator = zones.iterateAll(); + while (zoneIterator.hasNext()) { + Zone zone = zoneIterator.next(); + List toDelete = new LinkedList<>(); + if (zone.name().startsWith(PREFIX)) { + Iterator dnsRecordIterator = zone.listDnsRecords().iterateAll(); + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + if (!ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA).contains(record.type())) { + toDelete.add(record); + } + } + if (!toDelete.isEmpty()) { + zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); + } + zone.delete(); + } + } + } + + private static List filter(Iterator iterator) { + List result = new LinkedList<>(); + while (iterator.hasNext()) { + Zone zone = iterator.next(); + if (zone.name().startsWith(PREFIX)) { + result.add(zone); + } + } + return result; + } + + @BeforeClass + public static void before() { + purge(); + } + + @AfterClass + public static void after() { + purge(); + } + + @Test + public void testCreateValidZone() { + Zone created = DNS.create(ZONE1); + assertEquals(ZONE1.description(), created.description()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertEquals(ZONE1.name(), created.name()); + assertNotNull(created.creationTimeMillis()); + assertNotNull(created.nameServers()); + assertNull(created.nameServerSet()); + assertNotNull(created.id()); + Zone retrieved = DNS.getZone(ZONE1.name()); + assertEquals(created, retrieved); + created = DNS.create(ZONE_EMPTY_DESCRIPTION); + assertEquals(ZONE_EMPTY_DESCRIPTION.description(), created.description()); + assertEquals(ZONE_EMPTY_DESCRIPTION.dnsName(), created.dnsName()); + assertEquals(ZONE_EMPTY_DESCRIPTION.name(), created.name()); + assertNotNull(created.creationTimeMillis()); + assertNotNull(created.nameServers()); + assertNull(created.nameServerSet()); + assertNotNull(created.id()); + retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.name()); + assertEquals(created, retrieved); + } + + @After + public void tearDown() { + purge(); + } + + @Test + public void testCreateZoneWithErrors() { + try { + DNS.create(ZONE_MISSING_DNS_NAME); + fail("Zone is missing DNS name. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + try { + DNS.create(ZONE_MISSING_DESCRIPTION); + fail("Zone is missing description name. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + try { + DNS.create(ZONE_NAME_ERROR); + fail("Zone name is missing a period. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + try { + DNS.create(ZONE_DNS_NO_PERIOD); + fail("Zone name is missing a period. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + } + + @Test + public void testCreateZoneWithOptions() { + Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNotNull(created.creationTimeMillis()); + assertNull(created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.description(), created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); // we did not set it + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertNotNull(created.nameServers()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNotNull(created.id()); + created.delete(); + // combination of multiple things + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertEquals(ZONE1.description(), created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); // we did not set it + assertNotNull(created.id()); + } + + @Test + public void testZoneReload() { + Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNotNull(created.creationTimeMillis()); + assertNull(created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.description(), created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); // we did not set it + assertNull(created.id()); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertNotNull(created.nameServers()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNotNull(created.id()); + // combination of multiple things + created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertEquals(ZONE1.description(), created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); // we did not set it + assertNotNull(created.id()); + } + + @Test + public void testGetZone() { + DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + Zone created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNotNull(created.creationTimeMillis()); + assertNull(created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.description(), created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); // we did not set it + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertNotNull(created.nameServers()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNotNull(created.id()); + // combination of multiple things + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertEquals(ZONE1.description(), created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); // we did not set it + assertNotNull(created.id()); + } + + @Test + public void testListZones() { + List zones = filter(DNS.listZones().iterateAll()); + assertEquals(0, zones.size()); + // some zones exists + Zone created = DNS.create(ZONE1); + zones = filter(DNS.listZones().iterateAll()); + assertEquals(created, zones.get(0)); + assertEquals(1, zones.size()); + created = DNS.create(ZONE_EMPTY_DESCRIPTION); + zones = filter(DNS.listZones().iterateAll()); + assertEquals(2, zones.size()); + assertTrue(zones.contains(created)); + // error in options + try { + DNS.listZones(Dns.ZoneListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test not-retryable + } + try { + DNS.listZones(Dns.ZoneListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test not-retryable + } + // ok size + zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll()); + assertEquals(2, zones.size()); // we still have only 2 zones + // dns name problems + try { + DNS.listZones(Dns.ZoneListOption.dnsName("aaaaa")); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test not-retryable + } + // ok name + zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName())).iterateAll()); + assertEquals(1, zones.size()); + // field options + zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID)).iterateAll()); + assertEquals(1, zones.size()); + Zone zone = zones.get(0); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNotNull(zone.id()); + zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.CREATION_TIME)).iterateAll()); + assertEquals(1, zones.size()); + zone = zones.get(0); + assertNotNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.DNS_NAME)).iterateAll()); + assertEquals(1, zones.size()); + zone = zones.get(0); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNotNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)).iterateAll()); + assertEquals(1, zones.size()); + zone = zones.get(0); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNotNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVERS)).iterateAll()); + assertEquals(1, zones.size()); + zone = zones.get(0); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(!zone.nameServers().isEmpty()); + assertNull(zone.id()); + zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVER_SET)).iterateAll()); + assertEquals(1, zones.size()); + zone = zones.get(0); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); // we cannot set it using gcloud java + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + // several combined + zones = filter(DNS.listZones(Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.DESCRIPTION), + Dns.ZoneListOption.pageSize(1)).iterateAll()); + assertEquals(2, zones.size()); + for (Zone current : zones) { + assertNull(current.creationTimeMillis()); + assertNotNull(current.name()); + assertNull(current.dnsName()); + assertNotNull(current.description()); + assertNull(current.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNotNull(current.id()); + } + } + + @Test + public void testDeleteZoneUsingServiceObject() { + Zone created = DNS.create(ZONE1); + assertEquals(created, DNS.getZone(ZONE1.name())); + DNS.delete(ZONE1.name()); + assertNull(DNS.getZone(ZONE1.name())); + } + + @Test + public void testDeleteZoneUsingZoneObject() { + Zone created = DNS.create(ZONE1); + assertEquals(created, DNS.getZone(ZONE1.name())); + created.delete(); + assertNull(DNS.getZone(ZONE1.name())); + } + + private void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { + ChangeRequest unifiedEx = ChangeRequest.fromPb(expected.toPb().setStatus("pending")); + ChangeRequest unifiedAct = ChangeRequest.fromPb(actual.toPb().setStatus("pending")); + assertEquals(unifiedEx, unifiedAct); + } + + private static void checkChangeComplete(String zoneName, String changeId) { + for (int i = 0; i < TIME_LIMIT; i++) { + ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + if (ChangeRequest.Status.DONE.equals(changeRequest.status())) { + break; + } else { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + throw new RuntimeException("Thread was interrupted while waiting for change."); + } + } + } + } + + @Test + public void testCreateChangeUsingServiceObject() { + DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + ChangeRequest created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); + assertNotNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("1", created.id()); + assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) + .contains(created.status())); + assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); + checkChangeComplete(ZONE1.name(), "1"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "2"); + // with options + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + assertTrue(created.additions().isEmpty()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("3", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "3"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "4"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + assertTrue(created.additions().isEmpty()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("5", created.id()); + assertNotNull(created.status()); + checkChangeComplete(ZONE1.name(), "5"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "6"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertTrue(created.additions().isEmpty()); + assertNotNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("7", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "7"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "8"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("9", created.id()); + assertNull(created.status()); + // finishes with delete otherwise we cannot delete the zone + checkChangeComplete(ZONE1.name(), "9"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + checkChangeComplete(ZONE1.name(), "10"); + assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); + assertNull(created.startTimeMillis()); + assertTrue(created.additions().isEmpty()); + assertEquals("10", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "10"); + } + + @Test + public void testCreateChangeUsingZoneObject() { + Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); + assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); + assertNotNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("1", created.id()); + assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) + .contains(created.status())); + assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); + checkChangeComplete(ZONE1.name(), "1"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "2"); + // with options + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + assertTrue(created.additions().isEmpty()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("3", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "3"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "4"); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + assertTrue(created.additions().isEmpty()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("5", created.id()); + assertNotNull(created.status()); + checkChangeComplete(ZONE1.name(), "5"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "6"); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertTrue(created.additions().isEmpty()); + assertNotNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("7", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "7"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "8"); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("9", created.id()); + assertNull(created.status()); + // finishes with delete otherwise we cannot delete the zone + checkChangeComplete(ZONE1.name(), "9"); + created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + checkChangeComplete(ZONE1.name(), "10"); + assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); + assertNull(created.startTimeMillis()); + assertTrue(created.additions().isEmpty()); + assertEquals("10", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "10"); + } + + @Test + public void testListChangesUsingService() { + // no such zone exists + try { + DNS.listChangeRequests(ZONE1.name()); + fail(); + } catch (DnsException ex) { + // expected + assertEquals(404, ex.code()); + // todo(mderka) test retry functionality + } + // zone exists but has no changes + DNS.create(ZONE1); + ImmutableList changes = ImmutableList.copyOf( + DNS.listChangeRequests(ZONE1.name()).iterateAll()); + assertEquals(1, changes.size()); // default change creating SOA and NS + // zone has changes + ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); + assertEquals(5, changes.size()); + // error in options + try { + DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality + } + try { + DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality + } + // sorting order + ImmutableList ascending = ImmutableList.copyOf(DNS.listChangeRequests( + ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)).iterateAll()); + ImmutableList descending = ImmutableList.copyOf(DNS.listChangeRequests( + ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)).iterateAll()); + int size = 5; + assertEquals(size, descending.size()); + assertEquals(size, ascending.size()); + for (int i = 0; i < size; i++) { + assertEquals(descending.get(i), ascending.get(size - i - 1)); + } + // field options + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ADDITIONS)).iterateAll()); + change = changes.get(1); + assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.DELETIONS)).iterateAll()); + change = changes.get(2); + assertTrue(change.additions().isEmpty()); + assertNotNull(change.deletions()); + assertEquals("2", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ID)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNotNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertEquals(ChangeRequest.Status.DONE, change.status()); + } + + @Test + public void testListChangesUsingZoneObject() { + // zone exists but has no changes + Zone created = DNS.create(ZONE1); + ImmutableList changes = ImmutableList.copyOf( + created.listChangeRequests().iterateAll()); + assertEquals(1, changes.size()); // default change creating SOA and NS + // zone has changes + ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + changes = ImmutableList.copyOf(created.listChangeRequests().iterateAll()); + assertEquals(5, changes.size()); + // error in options + try { + created.listChangeRequests(Dns.ChangeRequestListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality + } + try { + created.listChangeRequests(Dns.ChangeRequestListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality + } + // sorting order + ImmutableList ascending = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)).iterateAll()); + ImmutableList descending = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)).iterateAll()); + int size = 5; + assertEquals(size, descending.size()); + assertEquals(size, ascending.size()); + for (int i = 0; i < size; i++) { + assertEquals(descending.get(i), ascending.get(size - i - 1)); + } + // field options + changes = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ADDITIONS)).iterateAll()); + change = changes.get(1); + assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.DELETIONS)).iterateAll()); + change = changes.get(2); + assertTrue(change.additions().isEmpty()); + assertNotNull(change.deletions()); + assertEquals("2", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ID)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNotNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(created.listChangeRequests( + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertEquals(ChangeRequest.Status.DONE, change.status()); + } + + @Test + public void testGetChangeUsingZoneObject() { + Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); + ChangeRequest retrieved = zone.getChangeRequest(created.id()); + assertEqChangesIgnoreStatus(created, retrieved); + checkChangeComplete(ZONE1.name(), "1"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "2"); + // with options + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + retrieved = zone.getChangeRequest(created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + assertEqChangesIgnoreStatus(created, retrieved); + checkChangeComplete(ZONE1.name(), "3"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "4"); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + retrieved = zone.getChangeRequest(created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + assertEqChangesIgnoreStatus(created, retrieved); + checkChangeComplete(ZONE1.name(), "5"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "6"); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + retrieved = zone.getChangeRequest(created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertEqChangesIgnoreStatus(created, retrieved); + checkChangeComplete(ZONE1.name(), "7"); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "8"); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + retrieved = zone.getChangeRequest(created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + assertEqChangesIgnoreStatus(created, retrieved); + // finishes with delete otherwise we cannot delete the zone + checkChangeComplete(ZONE1.name(), "9"); + created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + retrieved = zone.getChangeRequest(created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + assertEqChangesIgnoreStatus(created, retrieved); + checkChangeComplete(ZONE1.name(), "10"); + } + + @Test + public void testGetChangeUsingServiceObject() { + Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); + ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.id()); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + // with options + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + assertEqChangesIgnoreStatus(created, retrieved); + // finishes with delete otherwise we cannot delete the zone + created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + assertEqChangesIgnoreStatus(created, retrieved); + } + + @Test + public void testGetProject() { + // fetches all fields + ProjectInfo project = DNS.getProject(); + assertNotNull(project.quota()); + assertNotNull(project.number()); + assertNotNull(project.id()); + assertEquals(PROJECT_ID, project.id()); + // options + project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.QUOTA)); + assertNotNull(project.quota()); + assertNull(project.number()); + assertNotNull(project.id()); // id is always returned + project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.PROJECT_ID)); + assertNull(project.quota()); + assertNull(project.number()); + assertNotNull(project.id()); + project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.PROJECT_NUMBER)); + assertNull(project.quota()); + assertNotNull(project.number()); + assertNotNull(project.id()); + project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.PROJECT_NUMBER, + Dns.ProjectField.QUOTA, Dns.ProjectField.PROJECT_ID)); + assertNotNull(project.quota()); + assertNotNull(project.number()); + assertNotNull(project.id()); + } + + @Test + public void testListDnsRecordsUsingService() { + Zone zone = DNS.create(ZONE1); + ImmutableList dnsRecords = ImmutableList.copyOf( + DNS.listDnsRecords(zone.name()).iterateAll()); + assertEquals(2, dnsRecords.size()); + ImmutableList defaultRecords = + ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); + for (DnsRecord record : dnsRecords) { + assertTrue(defaultRecords.contains(record.type())); + } + // field options + Iterator dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); + int counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertTrue(record.records().isEmpty()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertTrue(record.records().isEmpty()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).records(), record.records()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), + Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertTrue(record.records().isEmpty()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + // test page size + Page dnsRecordPage = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), + Dns.DnsRecordListOption.pageSize(1)); + assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); + // test name filter + ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) + .contains(record.type())); + counter++; + } + assertEquals(2, counter); + // test type filter + checkChangeComplete(ZONE1.name(), change.id()); + dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), + Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) + .iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(A_RECORD_ZONE1, record); + counter++; + } + assertEquals(1, counter); + change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + // check wrong arguments + try { + // name is not set + DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + try { + DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + try { + DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + checkChangeComplete(ZONE1.name(), change.id()); + } + + @Test + public void testListDnsRecordsUsingZoneObject() { + Zone zone = DNS.create(ZONE1); + ImmutableList dnsRecords = ImmutableList.copyOf( + zone.listDnsRecords().iterateAll()); + assertEquals(2, dnsRecords.size()); + ImmutableList defaultRecords = + ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); + for (DnsRecord record : dnsRecords) { + assertTrue(defaultRecords.contains(record.type())); + } + // field options + Iterator dnsRecordIterator = zone.listDnsRecords( + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); + int counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertTrue(record.records().isEmpty()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = zone.listDnsRecords( + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertTrue(record.records().isEmpty()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = zone.listDnsRecords( + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).records(), record.records()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = zone.listDnsRecords( + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), + Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertTrue(record.records().isEmpty()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + // test page size + Page dnsRecordPage = zone.listDnsRecords( + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), + Dns.DnsRecordListOption.pageSize(1)); + assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); + // test name filter + ChangeRequest change = zone.applyChangeRequest(CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + dnsRecordIterator = zone.listDnsRecords(Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())) + .iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) + .contains(record.type())); + counter++; + } + assertEquals(2, counter); + // test type filter + checkChangeComplete(ZONE1.name(), change.id()); + dnsRecordIterator = zone.listDnsRecords(Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), + Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) + .iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(A_RECORD_ZONE1, record); + counter++; + } + assertEquals(1, counter); + change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + // check wrong arguments + try { + // name is not set + zone.listDnsRecords(Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + try { + zone.listDnsRecords(Dns.DnsRecordListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + try { + zone.listDnsRecords(Dns.DnsRecordListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + checkChangeComplete(ZONE1.name(), change.id()); + } +} From 75269ff6a0b2b8518ad4dc562905089c20236412 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 26 Feb 2016 18:21:53 -0500 Subject: [PATCH 53/74] Removed unnecessary integration tests. Adjusted deleting objects. --- .../java/com/google/gcloud/dns/ITDnsTest.java | 1763 +++++++---------- 1 file changed, 700 insertions(+), 1063 deletions(-) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java index 07475c52cfda..e473d1c4912c 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java @@ -26,10 +26,11 @@ import com.google.common.collect.ImmutableList; import com.google.gcloud.Page; -import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.Timeout; import java.util.Iterator; import java.util.LinkedList; @@ -41,7 +42,6 @@ public class ITDnsTest { // todo(mderka) Implement test for creating invalid change when DnsException is finished. #673 - public static final int TIME_LIMIT = 10; public static final String PREFIX = "gcldjvit-"; public static final Dns DNS = DnsOptions.builder().build().service(); public static final String PROJECT_ID = DNS.options().projectId(); @@ -80,16 +80,16 @@ public class ITDnsTest { .description(ZONE_DESCRIPTION1) .dnsName(ZONE_DNS_NAME_NO_PERIOD) .build(); - public static final DnsRecord A_RECORD_ZONE1 = DnsRecord - .builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) - .records(ImmutableList.of("123.123.55.1")) - .ttl(25, TimeUnit.SECONDS) - .build(); - public static final DnsRecord AAAA_RECORD_ZONE1 = DnsRecord - .builder("www." + ZONE1.dnsName(), DnsRecord.Type.AAAA) - .records(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) - .ttl(25, TimeUnit.SECONDS) - .build(); + public static final DnsRecord A_RECORD_ZONE1 = + DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) + .records(ImmutableList.of("123.123.55.1")) + .ttl(25, TimeUnit.SECONDS) + .build(); + public static final DnsRecord AAAA_RECORD_ZONE1 = + DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.AAAA) + .records(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) + .ttl(25, TimeUnit.SECONDS) + .build(); public static final ChangeRequest CHANGE_ADD_ZONE1 = ChangeRequest.builder() .add(A_RECORD_ZONE1) .add(AAAA_RECORD_ZONE1) @@ -99,7 +99,7 @@ public class ITDnsTest { .delete(AAAA_RECORD_ZONE1) .build(); - public static void purge() { + public static void clear() { Page zones = DNS.listZones(); Iterator zoneIterator = zones.iterateAll(); while (zoneIterator.hasNext()) { @@ -114,7 +114,9 @@ public static void purge() { } } if (!toDelete.isEmpty()) { - zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); + ChangeRequest deletion = + zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); + checkChangeComplete(zone.name(), deletion.id()); } zone.delete(); } @@ -134,868 +136,617 @@ private static List filter(Iterator iterator) { @BeforeClass public static void before() { - purge(); + clear(); } @AfterClass public static void after() { - purge(); + clear(); } - @Test - public void testCreateValidZone() { - Zone created = DNS.create(ZONE1); - assertEquals(ZONE1.description(), created.description()); - assertEquals(ZONE1.dnsName(), created.dnsName()); - assertEquals(ZONE1.name(), created.name()); - assertNotNull(created.creationTimeMillis()); - assertNotNull(created.nameServers()); - assertNull(created.nameServerSet()); - assertNotNull(created.id()); - Zone retrieved = DNS.getZone(ZONE1.name()); - assertEquals(created, retrieved); - created = DNS.create(ZONE_EMPTY_DESCRIPTION); - assertEquals(ZONE_EMPTY_DESCRIPTION.description(), created.description()); - assertEquals(ZONE_EMPTY_DESCRIPTION.dnsName(), created.dnsName()); - assertEquals(ZONE_EMPTY_DESCRIPTION.name(), created.name()); - assertNotNull(created.creationTimeMillis()); - assertNotNull(created.nameServers()); - assertNull(created.nameServerSet()); - assertNotNull(created.id()); - retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.name()); - assertEquals(created, retrieved); + private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { + ChangeRequest unifiedEx = ChangeRequest.fromPb(expected.toPb().setStatus("pending")); + ChangeRequest unifiedAct = ChangeRequest.fromPb(actual.toPb().setStatus("pending")); + assertEquals(unifiedEx, unifiedAct); } - @After - public void tearDown() { - purge(); + private static void checkChangeComplete(String zoneName, String changeId) { + while (true) { + ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + if (ChangeRequest.Status.DONE.equals(changeRequest.status())) { + break; + } + } } + @Rule + public Timeout globalTimeout = Timeout.seconds(300); + @Test - public void testCreateZoneWithErrors() { - try { - DNS.create(ZONE_MISSING_DNS_NAME); - fail("Zone is missing DNS name. The service returns an error."); - } catch (DnsException ex) { - // expected - // todo(mderka) test non-retryable when implemented within #593 - } - try { - DNS.create(ZONE_MISSING_DESCRIPTION); - fail("Zone is missing description name. The service returns an error."); - } catch (DnsException ex) { - // expected - // todo(mderka) test non-retryable when implemented within #593 - } - try { - DNS.create(ZONE_NAME_ERROR); - fail("Zone name is missing a period. The service returns an error."); - } catch (DnsException ex) { - // expected - // todo(mderka) test non-retryable when implemented within #593 - } + public void testCreateValidZone() { try { - DNS.create(ZONE_DNS_NO_PERIOD); - fail("Zone name is missing a period. The service returns an error."); - } catch (DnsException ex) { - // expected - // todo(mderka) test non-retryable when implemented within #593 + Zone created = DNS.create(ZONE1); + assertEquals(ZONE1.description(), created.description()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertEquals(ZONE1.name(), created.name()); + assertNotNull(created.creationTimeMillis()); + assertNotNull(created.nameServers()); + assertNull(created.nameServerSet()); + assertNotNull(created.id()); + Zone retrieved = DNS.getZone(ZONE1.name()); + assertEquals(created, retrieved); + created = DNS.create(ZONE_EMPTY_DESCRIPTION); + assertEquals(ZONE_EMPTY_DESCRIPTION.description(), created.description()); + assertEquals(ZONE_EMPTY_DESCRIPTION.dnsName(), created.dnsName()); + assertEquals(ZONE_EMPTY_DESCRIPTION.name(), created.name()); + assertNotNull(created.creationTimeMillis()); + assertNotNull(created.nameServers()); + assertNull(created.nameServerSet()); + assertNotNull(created.id()); + retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.name()); + assertEquals(created, retrieved); + } finally { + DNS.delete(ZONE1.name()); + DNS.delete(ZONE_EMPTY_DESCRIPTION.name()); } } @Test - public void testCreateZoneWithOptions() { - Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNotNull(created.creationTimeMillis()); - assertNull(created.description()); - assertNull(created.dnsName()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created.delete(); - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertEquals(ZONE1.description(), created.description()); - assertNull(created.dnsName()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created.delete(); - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertEquals(ZONE1.dnsName(), created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created.delete(); - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created.delete(); - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); // we did not set it - assertNull(created.id()); - created.delete(); - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertFalse(created.nameServers().isEmpty()); - assertNull(created.nameServerSet()); - assertNull(created.id()); - created.delete(); - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertNotNull(created.nameServers()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNotNull(created.id()); - created.delete(); - // combination of multiple things - created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, - Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertEquals(ZONE1.description(), created.description()); - assertFalse(created.nameServers().isEmpty()); - assertNull(created.nameServerSet()); // we did not set it - assertNotNull(created.id()); + public void testCreateZoneWithErrors() { + try { + try { + DNS.create(ZONE_MISSING_DNS_NAME); + fail("Zone is missing DNS name. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + try { + DNS.create(ZONE_MISSING_DESCRIPTION); + fail("Zone is missing description name. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + try { + DNS.create(ZONE_NAME_ERROR); + fail("Zone name is missing a period. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + try { + DNS.create(ZONE_DNS_NO_PERIOD); + fail("Zone name is missing a period. The service returns an error."); + } catch (DnsException ex) { + // expected + // todo(mderka) test non-retryable when implemented within #593 + } + } finally { + DNS.delete(ZONE_MISSING_DNS_NAME.name()); + DNS.delete(ZONE_MISSING_DESCRIPTION.name()); + DNS.delete(ZONE_NAME_ERROR.name()); + DNS.delete(ZONE_DNS_NO_PERIOD.name()); + } } @Test - public void testZoneReload() { - Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNotNull(created.creationTimeMillis()); - assertNull(created.description()); - assertNull(created.dnsName()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertEquals(ZONE1.description(), created.description()); - assertNull(created.dnsName()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertEquals(ZONE1.dnsName(), created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); // we did not set it - assertNull(created.id()); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertFalse(created.nameServers().isEmpty()); - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertNotNull(created.nameServers()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNotNull(created.id()); - // combination of multiple things - created = created.reload(Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, - Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertEquals(ZONE1.description(), created.description()); - assertFalse(created.nameServers().isEmpty()); - assertNull(created.nameServerSet()); // we did not set it - assertNotNull(created.id()); + public void testCreateZoneWithOptions() { + try { + Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNotNull(created.creationTimeMillis()); + assertNull(created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.description(), created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); // we did not set it + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); + assertNull(created.id()); + created.delete(); + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertNotNull(created.nameServers()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNotNull(created.id()); + created.delete(); + // combination of multiple things + created = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertEquals(ZONE1.description(), created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); // we did not set it + assertNotNull(created.id()); + } finally { + DNS.delete(ZONE1.name()); + } } @Test public void testGetZone() { - DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - Zone created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNotNull(created.creationTimeMillis()); - assertNull(created.description()); - assertNull(created.dnsName()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertEquals(ZONE1.description(), created.description()); - assertNull(created.dnsName()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertEquals(ZONE1.dnsName(), created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNull(created.nameServerSet()); // we did not set it - assertNull(created.id()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertFalse(created.nameServers().isEmpty()); - assertNull(created.nameServerSet()); - assertNull(created.id()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertNull(created.description()); - assertNotNull(created.nameServers()); - assertTrue(created.nameServers().isEmpty()); // never returns null - assertNotNull(created.id()); - // combination of multiple things - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, - Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); - assertEquals(ZONE1.name(), created.name()); // always returned - assertNull(created.creationTimeMillis()); - assertNull(created.dnsName()); - assertEquals(ZONE1.description(), created.description()); - assertFalse(created.nameServers().isEmpty()); - assertNull(created.nameServerSet()); // we did not set it - assertNotNull(created.id()); + try { + DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + Zone created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNotNull(created.creationTimeMillis()); + assertNull(created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.description(), created.description()); + assertNull(created.dnsName()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.DNS_NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertEquals(ZONE1.dnsName(), created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVER_SET)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNull(created.nameServerSet()); // we did not set it + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.NAME_SERVERS)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); + assertNull(created.id()); + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertNull(created.description()); + assertNotNull(created.nameServers()); + assertTrue(created.nameServers().isEmpty()); // never returns null + assertNotNull(created.id()); + // combination of multiple things + created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.NAME_SERVERS, Dns.ZoneField.NAME_SERVER_SET, Dns.ZoneField.DESCRIPTION)); + assertEquals(ZONE1.name(), created.name()); // always returned + assertNull(created.creationTimeMillis()); + assertNull(created.dnsName()); + assertEquals(ZONE1.description(), created.description()); + assertFalse(created.nameServers().isEmpty()); + assertNull(created.nameServerSet()); // we did not set it + assertNotNull(created.id()); + } finally { + DNS.delete(ZONE1.name()); + } } @Test public void testListZones() { - List zones = filter(DNS.listZones().iterateAll()); - assertEquals(0, zones.size()); - // some zones exists - Zone created = DNS.create(ZONE1); - zones = filter(DNS.listZones().iterateAll()); - assertEquals(created, zones.get(0)); - assertEquals(1, zones.size()); - created = DNS.create(ZONE_EMPTY_DESCRIPTION); - zones = filter(DNS.listZones().iterateAll()); - assertEquals(2, zones.size()); - assertTrue(zones.contains(created)); - // error in options - try { - DNS.listZones(Dns.ZoneListOption.pageSize(0)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test not-retryable - } - try { - DNS.listZones(Dns.ZoneListOption.pageSize(-1)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test not-retryable - } - // ok size - zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll()); - assertEquals(2, zones.size()); // we still have only 2 zones - // dns name problems try { - DNS.listZones(Dns.ZoneListOption.dnsName("aaaaa")); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test not-retryable - } - // ok name - zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName())).iterateAll()); - assertEquals(1, zones.size()); - // field options - zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), - Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID)).iterateAll()); - assertEquals(1, zones.size()); - Zone zone = zones.get(0); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); - assertTrue(zone.nameServers().isEmpty()); - assertNotNull(zone.id()); - zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), - Dns.ZoneListOption.fields(Dns.ZoneField.CREATION_TIME)).iterateAll()); - assertEquals(1, zones.size()); - zone = zones.get(0); - assertNotNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); - assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); - zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), - Dns.ZoneListOption.fields(Dns.ZoneField.DNS_NAME)).iterateAll()); - assertEquals(1, zones.size()); - zone = zones.get(0); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNotNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); - assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); - zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), - Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)).iterateAll()); - assertEquals(1, zones.size()); - zone = zones.get(0); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNotNull(zone.description()); - assertNull(zone.nameServerSet()); - assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); - zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), - Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVERS)).iterateAll()); - assertEquals(1, zones.size()); - zone = zones.get(0); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); - assertTrue(!zone.nameServers().isEmpty()); - assertNull(zone.id()); - zones = ImmutableList.copyOf(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), - Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVER_SET)).iterateAll()); - assertEquals(1, zones.size()); - zone = zones.get(0); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); // we cannot set it using gcloud java - assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.id()); - // several combined - zones = filter(DNS.listZones(Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID, - Dns.ZoneField.DESCRIPTION), - Dns.ZoneListOption.pageSize(1)).iterateAll()); - assertEquals(2, zones.size()); - for (Zone current : zones) { - assertNull(current.creationTimeMillis()); - assertNotNull(current.name()); - assertNull(current.dnsName()); - assertNotNull(current.description()); - assertNull(current.nameServerSet()); + List zones = filter(DNS.listZones().iterateAll()); + assertEquals(0, zones.size()); + // some zones exists + Zone created = DNS.create(ZONE1); + zones = filter(DNS.listZones().iterateAll()); + assertEquals(created, zones.get(0)); + assertEquals(1, zones.size()); + created = DNS.create(ZONE_EMPTY_DESCRIPTION); + zones = filter(DNS.listZones().iterateAll()); + assertEquals(2, zones.size()); + assertTrue(zones.contains(created)); + // error in options + try { + DNS.listZones(Dns.ZoneListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test not-retryable + } + try { + DNS.listZones(Dns.ZoneListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test not-retryable + } + // ok size + zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll()); + assertEquals(2, zones.size()); // we still have only 2 zones + // dns name problems + try { + DNS.listZones(Dns.ZoneListOption.dnsName("aaaaa")); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test not-retryable + } + // ok name + zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName())).iterateAll()); + assertEquals(1, zones.size()); + // field options + Iterator zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID)).iterateAll(); + Zone zone = zoneIterator.next(); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); assertTrue(zone.nameServers().isEmpty()); - assertNotNull(current.id()); - } - } - - @Test - public void testDeleteZoneUsingServiceObject() { - Zone created = DNS.create(ZONE1); - assertEquals(created, DNS.getZone(ZONE1.name())); - DNS.delete(ZONE1.name()); - assertNull(DNS.getZone(ZONE1.name())); - } - - @Test - public void testDeleteZoneUsingZoneObject() { - Zone created = DNS.create(ZONE1); - assertEquals(created, DNS.getZone(ZONE1.name())); - created.delete(); - assertNull(DNS.getZone(ZONE1.name())); - } - - private void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { - ChangeRequest unifiedEx = ChangeRequest.fromPb(expected.toPb().setStatus("pending")); - ChangeRequest unifiedAct = ChangeRequest.fromPb(actual.toPb().setStatus("pending")); - assertEquals(unifiedEx, unifiedAct); - } - - private static void checkChangeComplete(String zoneName, String changeId) { - for (int i = 0; i < TIME_LIMIT; i++) { - ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - if (ChangeRequest.Status.DONE.equals(changeRequest.status())) { - break; - } else { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException("Thread was interrupted while waiting for change."); - } + assertNotNull(zone.id()); + assertFalse(zoneIterator.hasNext()); + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.CREATION_TIME)).iterateAll(); + zone = zoneIterator.next(); + assertNotNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + assertFalse(zoneIterator.hasNext()); + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.DNS_NAME)).iterateAll(); + zone = zoneIterator.next(); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNotNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + assertFalse(zoneIterator.hasNext()); + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION)).iterateAll(); + zone = zoneIterator.next(); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNotNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + assertFalse(zoneIterator.hasNext()); + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVERS)).iterateAll(); + zone = zoneIterator.next(); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); + assertTrue(!zone.nameServers().isEmpty()); + assertNull(zone.id()); + assertFalse(zoneIterator.hasNext()); + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Dns.ZoneListOption.fields(Dns.ZoneField.NAME_SERVER_SET)).iterateAll(); + zone = zoneIterator.next(); + assertNull(zone.creationTimeMillis()); + assertNotNull(zone.name()); + assertNull(zone.dnsName()); + assertNull(zone.description()); + assertNull(zone.nameServerSet()); // we cannot set it using gcloud java + assertTrue(zone.nameServers().isEmpty()); + assertNull(zone.id()); + assertFalse(zoneIterator.hasNext()); + // several combined + zones = filter(DNS.listZones(Dns.ZoneListOption.fields(Dns.ZoneField.ZONE_ID, + Dns.ZoneField.DESCRIPTION), + Dns.ZoneListOption.pageSize(1)).iterateAll()); + assertEquals(2, zones.size()); + for (Zone current : zones) { + assertNull(current.creationTimeMillis()); + assertNotNull(current.name()); + assertNull(current.dnsName()); + assertNotNull(current.description()); + assertNull(current.nameServerSet()); + assertTrue(zone.nameServers().isEmpty()); + assertNotNull(current.id()); } + } finally { + DNS.delete(ZONE1.name()); + DNS.delete(ZONE_EMPTY_DESCRIPTION.name()); } } @Test - public void testCreateChangeUsingServiceObject() { - DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - ChangeRequest created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("1", created.id()); - assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) - .contains(created.status())); - assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); - checkChangeComplete(ZONE1.name(), "1"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "2"); - // with options - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("3", created.id()); - assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "3"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "4"); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("5", created.id()); - assertNotNull(created.status()); - checkChangeComplete(ZONE1.name(), "5"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "6"); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - assertTrue(created.additions().isEmpty()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("7", created.id()); - assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "7"); - DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "8"); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("9", created.id()); - assertNull(created.status()); - // finishes with delete otherwise we cannot delete the zone - checkChangeComplete(ZONE1.name(), "9"); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - checkChangeComplete(ZONE1.name(), "10"); - assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); - assertNull(created.startTimeMillis()); - assertTrue(created.additions().isEmpty()); - assertEquals("10", created.id()); - assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "10"); + public void testDeleteZone() { + try { + Zone created = DNS.create(ZONE1); + assertEquals(created, DNS.getZone(ZONE1.name())); + DNS.delete(ZONE1.name()); + assertNull(DNS.getZone(ZONE1.name())); + } finally { + DNS.delete(ZONE1.name()); + } } - @Test - public void testCreateChangeUsingZoneObject() { - Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("1", created.id()); - assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) - .contains(created.status())); - assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); - checkChangeComplete(ZONE1.name(), "1"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "2"); - // with options - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("3", created.id()); - assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "3"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "4"); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("5", created.id()); - assertNotNull(created.status()); - checkChangeComplete(ZONE1.name(), "5"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "6"); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - assertTrue(created.additions().isEmpty()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("7", created.id()); - assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "7"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "8"); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertEquals("9", created.id()); - assertNull(created.status()); - // finishes with delete otherwise we cannot delete the zone - checkChangeComplete(ZONE1.name(), "9"); - created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - checkChangeComplete(ZONE1.name(), "10"); - assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); - assertNull(created.startTimeMillis()); - assertTrue(created.additions().isEmpty()); - assertEquals("10", created.id()); - assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "10"); - } @Test - public void testListChangesUsingService() { - // no such zone exists + public void testCreateChange() { try { - DNS.listChangeRequests(ZONE1.name()); - fail(); - } catch (DnsException ex) { - // expected - assertEquals(404, ex.code()); - // todo(mderka) test retry functionality - } - // zone exists but has no changes - DNS.create(ZONE1); - ImmutableList changes = ImmutableList.copyOf( - DNS.listChangeRequests(ZONE1.name()).iterateAll()); - assertEquals(1, changes.size()); // default change creating SOA and NS - // zone has changes - ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); - assertEquals(5, changes.size()); - // error in options - try { - DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(0)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality - } - try { - DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(-1)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality - } - // sorting order - ImmutableList ascending = ImmutableList.copyOf(DNS.listChangeRequests( - ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)).iterateAll()); - ImmutableList descending = ImmutableList.copyOf(DNS.listChangeRequests( - ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)).iterateAll()); - int size = 5; - assertEquals(size, descending.size()); - assertEquals(size, ascending.size()); - for (int i = 0; i < size; i++) { - assertEquals(descending.get(i), ascending.get(size - i - 1)); + DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + ChangeRequest created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); + assertNotNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("1", created.id()); + assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) + .contains(created.status())); + assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); + checkChangeComplete(ZONE1.name(), "1"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "2"); + // with options + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + assertTrue(created.additions().isEmpty()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("3", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "3"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "4"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + assertTrue(created.additions().isEmpty()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("5", created.id()); + assertNotNull(created.status()); + checkChangeComplete(ZONE1.name(), "5"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "6"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertTrue(created.additions().isEmpty()); + assertNotNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("7", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "7"); + DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), "8"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); + assertNull(created.startTimeMillis()); + assertTrue(created.deletions().isEmpty()); + assertEquals("9", created.id()); + assertNull(created.status()); + // finishes with delete otherwise we cannot delete the zone + checkChangeComplete(ZONE1.name(), "9"); + created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + checkChangeComplete(ZONE1.name(), "10"); + assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); + assertNull(created.startTimeMillis()); + assertTrue(created.additions().isEmpty()); + assertEquals("10", created.id()); + assertNull(created.status()); + checkChangeComplete(ZONE1.name(), "10"); + } finally { + clear(); } - // field options - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ADDITIONS)).iterateAll()); - change = changes.get(1); - assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.DELETIONS)).iterateAll()); - change = changes.get(2); - assertTrue(change.additions().isEmpty()); - assertNotNull(change.deletions()); - assertEquals("2", change.id()); - assertNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ID)).iterateAll()); - change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME)).iterateAll()); - change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNotNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS)).iterateAll()); - change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNull(change.startTimeMillis()); - assertEquals(ChangeRequest.Status.DONE, change.status()); } @Test - public void testListChangesUsingZoneObject() { - // zone exists but has no changes - Zone created = DNS.create(ZONE1); - ImmutableList changes = ImmutableList.copyOf( - created.listChangeRequests().iterateAll()); - assertEquals(1, changes.size()); // default change creating SOA and NS - // zone has changes - ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - changes = ImmutableList.copyOf(created.listChangeRequests().iterateAll()); - assertEquals(5, changes.size()); - // error in options - try { - created.listChangeRequests(Dns.ChangeRequestListOption.pageSize(0)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality - } + public void testListChanges() { try { - created.listChangeRequests(Dns.ChangeRequestListOption.pageSize(-1)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality - } - // sorting order - ImmutableList ascending = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)).iterateAll()); - ImmutableList descending = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)).iterateAll()); - int size = 5; - assertEquals(size, descending.size()); - assertEquals(size, ascending.size()); - for (int i = 0; i < size; i++) { - assertEquals(descending.get(i), ascending.get(size - i - 1)); + // no such zone exists + try { + DNS.listChangeRequests(ZONE1.name()); + fail(); + } catch (DnsException ex) { + // expected + assertEquals(404, ex.code()); + // todo(mderka) test retry functionality + } + // zone exists but has no changes + DNS.create(ZONE1); + ImmutableList changes = ImmutableList.copyOf( + DNS.listChangeRequests(ZONE1.name()).iterateAll()); + assertEquals(1, changes.size()); // default change creating SOA and NS + // zone has changes + ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); + assertEquals(5, changes.size()); + // error in options + try { + DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality + } + try { + DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality + } + // sorting order + ImmutableList ascending = ImmutableList.copyOf(DNS.listChangeRequests( + ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)).iterateAll()); + ImmutableList descending = ImmutableList.copyOf(DNS.listChangeRequests( + ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)).iterateAll()); + int size = 5; + assertEquals(size, descending.size()); + assertEquals(size, ascending.size()); + for (int i = 0; i < size; i++) { + assertEquals(descending.get(i), ascending.get(size - i - 1)); + } + // field options + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ADDITIONS)).iterateAll()); + change = changes.get(1); + assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.DELETIONS)).iterateAll()); + change = changes.get(2); + assertTrue(change.additions().isEmpty()); + assertNotNull(change.deletions()); + assertEquals("2", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ID)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNotNull(change.startTimeMillis()); + assertNull(change.status()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS)).iterateAll()); + change = changes.get(1); + assertTrue(change.additions().isEmpty()); + assertTrue(change.deletions().isEmpty()); + assertEquals("1", change.id()); + assertNull(change.startTimeMillis()); + assertEquals(ChangeRequest.Status.DONE, change.status()); + } finally { + clear(); } - // field options - changes = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ADDITIONS)).iterateAll()); - change = changes.get(1); - assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.DELETIONS)).iterateAll()); - change = changes.get(2); - assertTrue(change.additions().isEmpty()); - assertNotNull(change.deletions()); - assertEquals("2", change.id()); - assertNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.ID)).iterateAll()); - change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME)).iterateAll()); - change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNotNull(change.startTimeMillis()); - assertNull(change.status()); - changes = ImmutableList.copyOf(created.listChangeRequests( - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS)).iterateAll()); - change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertEquals("1", change.id()); - assertNull(change.startTimeMillis()); - assertEquals(ChangeRequest.Status.DONE, change.status()); - } - - @Test - public void testGetChangeUsingZoneObject() { - Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - ChangeRequest retrieved = zone.getChangeRequest(created.id()); - assertEqChangesIgnoreStatus(created, retrieved); - checkChangeComplete(ZONE1.name(), "1"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "2"); - // with options - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - retrieved = zone.getChangeRequest(created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - assertEqChangesIgnoreStatus(created, retrieved); - checkChangeComplete(ZONE1.name(), "3"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "4"); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - retrieved = zone.getChangeRequest(created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - assertEqChangesIgnoreStatus(created, retrieved); - checkChangeComplete(ZONE1.name(), "5"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "6"); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - retrieved = zone.getChangeRequest(created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - assertEqChangesIgnoreStatus(created, retrieved); - checkChangeComplete(ZONE1.name(), "7"); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "8"); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - retrieved = zone.getChangeRequest(created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - assertEqChangesIgnoreStatus(created, retrieved); - // finishes with delete otherwise we cannot delete the zone - checkChangeComplete(ZONE1.name(), "9"); - created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - retrieved = zone.getChangeRequest(created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - assertEqChangesIgnoreStatus(created, retrieved); - checkChangeComplete(ZONE1.name(), "10"); } @Test - public void testGetChangeUsingServiceObject() { - Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); - ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.id()); - assertEqChangesIgnoreStatus(created, retrieved); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - // with options - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); - assertEqChangesIgnoreStatus(created, retrieved); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); - assertEqChangesIgnoreStatus(created, retrieved); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); - assertEqChangesIgnoreStatus(created, retrieved); - zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); - assertEqChangesIgnoreStatus(created, retrieved); - // finishes with delete otherwise we cannot delete the zone - created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - retrieved = DNS.getChangeRequest(zone.name(), created.id(), - Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - assertEqChangesIgnoreStatus(created, retrieved); + public void testGetChange() { + try { + Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(Dns.ZoneField.NAME)); + ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); + ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.id()); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + // with options + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertEqChangesIgnoreStatus(created, retrieved); + zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); + assertEqChangesIgnoreStatus(created, retrieved); + // finishes with delete otherwise we cannot delete the zone + created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + retrieved = DNS.getChangeRequest(zone.name(), created.id(), + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); + assertEqChangesIgnoreStatus(created, retrieved); + } finally { + clear(); + } } @Test @@ -1027,242 +778,128 @@ public void testGetProject() { } @Test - public void testListDnsRecordsUsingService() { - Zone zone = DNS.create(ZONE1); - ImmutableList dnsRecords = ImmutableList.copyOf( - DNS.listDnsRecords(zone.name()).iterateAll()); - assertEquals(2, dnsRecords.size()); - ImmutableList defaultRecords = - ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); - for (DnsRecord record : dnsRecords) { - assertTrue(defaultRecords.contains(record.type())); - } - // field options - Iterator dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); - int counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); - counter++; - } - assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); - counter++; - } - assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).records(), record.records()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertNull(record.ttl()); - counter++; - } - assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); - counter++; - } - assertEquals(2, counter); - // test page size - Page dnsRecordPage = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)); - assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); - // test name filter - ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) - .contains(record.type())); - counter++; - } - assertEquals(2, counter); - // test type filter - checkChangeComplete(ZONE1.name(), change.id()); - dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), - Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) - .iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(A_RECORD_ZONE1, record); - counter++; - } - assertEquals(1, counter); - change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - // check wrong arguments - try { - // name is not set - DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available - } - try { - DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.pageSize(0)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available - } - try { - DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.pageSize(-1)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available - } - checkChangeComplete(ZONE1.name(), change.id()); - } - - @Test - public void testListDnsRecordsUsingZoneObject() { - Zone zone = DNS.create(ZONE1); - ImmutableList dnsRecords = ImmutableList.copyOf( - zone.listDnsRecords().iterateAll()); - assertEquals(2, dnsRecords.size()); - ImmutableList defaultRecords = - ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); - for (DnsRecord record : dnsRecords) { - assertTrue(defaultRecords.contains(record.type())); - } - // field options - Iterator dnsRecordIterator = zone.listDnsRecords( - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); - int counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); - counter++; - } - assertEquals(2, counter); - dnsRecordIterator = zone.listDnsRecords( - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); - counter++; - } - assertEquals(2, counter); - dnsRecordIterator = zone.listDnsRecords( - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).records(), record.records()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertNull(record.ttl()); - counter++; - } - assertEquals(2, counter); - dnsRecordIterator = zone.listDnsRecords( - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); - counter++; - } - assertEquals(2, counter); - // test page size - Page dnsRecordPage = zone.listDnsRecords( - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)); - assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); - // test name filter - ChangeRequest change = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); - dnsRecordIterator = zone.listDnsRecords(Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())) - .iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) - .contains(record.type())); - counter++; - } - assertEquals(2, counter); - // test type filter - checkChangeComplete(ZONE1.name(), change.id()); - dnsRecordIterator = zone.listDnsRecords(Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), - Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) - .iterateAll(); - counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(A_RECORD_ZONE1, record); - counter++; - } - assertEquals(1, counter); - change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1); - // check wrong arguments - try { - // name is not set - zone.listDnsRecords(Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available - } + public void testListDnsRecords() { try { - zone.listDnsRecords(Dns.DnsRecordListOption.pageSize(0)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available - } - try { - zone.listDnsRecords(Dns.DnsRecordListOption.pageSize(-1)); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available + Zone zone = DNS.create(ZONE1); + ImmutableList dnsRecords = ImmutableList.copyOf( + DNS.listDnsRecords(zone.name()).iterateAll()); + assertEquals(2, dnsRecords.size()); + ImmutableList defaultRecords = + ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); + for (DnsRecord record : dnsRecords) { + assertTrue(defaultRecords.contains(record.type())); + } + // field options + Iterator dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); + int counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertTrue(record.records().isEmpty()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertTrue(record.records().isEmpty()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).records(), record.records()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + dnsRecordIterator = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), + Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(dnsRecords.get(counter).type(), record.type()); + assertEquals(dnsRecords.get(counter).name(), record.name()); + assertTrue(record.records().isEmpty()); + assertNull(record.ttl()); + counter++; + } + assertEquals(2, counter); + // test page size + Page dnsRecordPage = DNS.listDnsRecords(zone.name(), + Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), + Dns.DnsRecordListOption.pageSize(1)); + assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); + // test name filter + ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + checkChangeComplete(ZONE1.name(), change.id()); + dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) + .contains(record.type())); + counter++; + } + assertEquals(2, counter); + // test type filter + checkChangeComplete(ZONE1.name(), change.id()); + dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), + Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) + .iterateAll(); + counter = 0; + while (dnsRecordIterator.hasNext()) { + DnsRecord record = dnsRecordIterator.next(); + assertEquals(A_RECORD_ZONE1, record); + counter++; + } + assertEquals(1, counter); + change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1); + // check wrong arguments + try { + // name is not set + DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + try { + DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.pageSize(0)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + try { + DNS.listDnsRecords(ZONE1.name(), + Dns.DnsRecordListOption.pageSize(-1)); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + // todo(mderka) test retry functionality when available + } + checkChangeComplete(ZONE1.name(), change.id()); + } finally { + clear(); } - checkChangeComplete(ZONE1.name(), change.id()); } } From 9b6929bbfdc9dc376fd52464f1df0cda4b5da7e3 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 1 Mar 2016 11:57:36 -0800 Subject: [PATCH 54/74] Added retryable errors. --- .../java/com/google/gcloud/dns/DnsException.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java index 2092d5909d37..70d7254e9502 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java @@ -16,27 +16,39 @@ package com.google.gcloud.dns; +import com.google.common.collect.ImmutableSet; import com.google.gcloud.BaseServiceException; import com.google.gcloud.RetryHelper.RetryHelperException; import com.google.gcloud.RetryHelper.RetryInterruptedException; import java.io.IOException; +import java.util.Set; /** * DNS service exception. */ public class DnsException extends BaseServiceException { + // see: https://cloud.google.com/dns/troubleshooting + private static final Set RETRYABLE_ERRORS = ImmutableSet.of( + new Error(500, null), + new Error(502, null), + new Error(503, null)); private static final long serialVersionUID = 490302380416260252L; public DnsException(IOException exception) { super(exception, true); } - public DnsException(int code, String message) { + private DnsException(int code, String message) { super(code, message, null, true); } + @Override + protected Set retryableErrors() { + return RETRYABLE_ERRORS; + } + /** * Translate RetryHelperException to the DnsException that caused the error. This method will * always throw an exception. @@ -48,6 +60,4 @@ static DnsException translateAndThrow(RetryHelperException ex) { BaseServiceException.translateAndPropagateIfPossible(ex); throw new DnsException(UNKNOWN_CODE, ex.getMessage()); } - - //TODO(mderka) Add translation and retry functionality. Created issue #593. } From 22153aa90264ef13758435b541ec6ee8f17cd620 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 1 Mar 2016 10:17:19 -0800 Subject: [PATCH 55/74] Added sleep and renamed change completion check. Moved integration test to a separate package and adjusted accordingly. Added missing fails. --- .../google/gcloud/dns/{ => it}/ITDnsTest.java | 125 +++++++++--------- 1 file changed, 64 insertions(+), 61 deletions(-) rename gcloud-java-dns/src/test/java/com/google/gcloud/dns/{ => it}/ITDnsTest.java (92%) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java similarity index 92% rename from gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java rename to gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index e473d1c4912c..ae721e742ae8 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.dns; +package com.google.gcloud.dns.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -25,6 +25,14 @@ import com.google.common.collect.ImmutableList; import com.google.gcloud.Page; +import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.Dns; +import com.google.gcloud.dns.DnsException; +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 org.junit.AfterClass; import org.junit.BeforeClass; @@ -62,24 +70,20 @@ public class ITDnsTest { .description(ZONE_DESCRIPTION1) .dnsName(ZONE_DNS_NAME1) .build(); - public static final ZoneInfo ZONE_NAME_ERROR = - ZoneInfo.builder(ZONE_NAME_TOO_LONG) - .description(ZONE_DESCRIPTION1) - .dnsName(ZONE_DNS_NAME1) - .build(); - public static final ZoneInfo ZONE_MISSING_DESCRIPTION = - ZoneInfo.builder(ZONE_NAME1) - .dnsName(ZONE_DNS_NAME1) - .build(); - public static final ZoneInfo ZONE_MISSING_DNS_NAME = - ZoneInfo.builder(ZONE_NAME1) - .description(ZONE_DESCRIPTION1) - .build(); - public static final ZoneInfo ZONE_DNS_NO_PERIOD = - ZoneInfo.builder(ZONE_NAME1) - .description(ZONE_DESCRIPTION1) - .dnsName(ZONE_DNS_NAME_NO_PERIOD) - .build(); + public static final ZoneInfo ZONE_NAME_ERROR = ZoneInfo.builder(ZONE_NAME_TOO_LONG) + .description(ZONE_DESCRIPTION1) + .dnsName(ZONE_DNS_NAME1) + .build(); + public static final ZoneInfo ZONE_MISSING_DESCRIPTION = ZoneInfo.builder(ZONE_NAME1) + .dnsName(ZONE_DNS_NAME1) + .build(); + public static final ZoneInfo ZONE_MISSING_DNS_NAME = ZoneInfo.builder(ZONE_NAME1) + .description(ZONE_DESCRIPTION1) + .build(); + public static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.builder(ZONE_NAME1) + .description(ZONE_DESCRIPTION1) + .dnsName(ZONE_DNS_NAME_NO_PERIOD) + .build(); public static final DnsRecord A_RECORD_ZONE1 = DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) .records(ImmutableList.of("123.123.55.1")) @@ -116,7 +120,7 @@ public static void clear() { if (!toDelete.isEmpty()) { ChangeRequest deletion = zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); - checkChangeComplete(zone.name(), deletion.id()); + waitUntilComplete(zone.name(), deletion.id()); } zone.delete(); } @@ -145,17 +149,23 @@ public static void after() { } private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { - ChangeRequest unifiedEx = ChangeRequest.fromPb(expected.toPb().setStatus("pending")); - ChangeRequest unifiedAct = ChangeRequest.fromPb(actual.toPb().setStatus("pending")); - assertEquals(unifiedEx, unifiedAct); + assertEquals(expected.additions(), actual.additions()); + assertEquals(expected.deletions(), actual.deletions()); + assertEquals(expected.id(), actual.id()); + assertEquals(expected.startTimeMillis(), actual.startTimeMillis()); } - private static void checkChangeComplete(String zoneName, String changeId) { + private static void waitUntilComplete(String zoneName, String changeId) { while (true) { ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); if (ChangeRequest.Status.DONE.equals(changeRequest.status())) { - break; + return; + } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + fail("Thread was interrupted while waiting for change processing."); } } } @@ -404,6 +414,7 @@ public void testListZones() { // error in options try { DNS.listZones(Dns.ZoneListOption.pageSize(0)); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); @@ -411,6 +422,7 @@ public void testListZones() { } try { DNS.listZones(Dns.ZoneListOption.pageSize(-1)); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); @@ -422,6 +434,7 @@ public void testListZones() { // dns name problems try { DNS.listZones(Dns.ZoneListOption.dnsName("aaaaa")); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); @@ -529,7 +542,6 @@ public void testDeleteZone() { } } - @Test public void testCreateChange() { try { @@ -542,9 +554,9 @@ public void testCreateChange() { assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); - checkChangeComplete(ZONE1.name(), "1"); + waitUntilComplete(ZONE1.name(), "1"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "2"); + waitUntilComplete(ZONE1.name(), "2"); // with options created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); @@ -553,9 +565,9 @@ public void testCreateChange() { assertTrue(created.deletions().isEmpty()); assertEquals("3", created.id()); assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "3"); + waitUntilComplete(ZONE1.name(), "3"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "4"); + waitUntilComplete(ZONE1.name(), "4"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); assertTrue(created.additions().isEmpty()); @@ -563,9 +575,9 @@ public void testCreateChange() { assertTrue(created.deletions().isEmpty()); assertEquals("5", created.id()); assertNotNull(created.status()); - checkChangeComplete(ZONE1.name(), "5"); + waitUntilComplete(ZONE1.name(), "5"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "6"); + waitUntilComplete(ZONE1.name(), "6"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); assertTrue(created.additions().isEmpty()); @@ -573,9 +585,9 @@ public void testCreateChange() { assertTrue(created.deletions().isEmpty()); assertEquals("7", created.id()); assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "7"); + waitUntilComplete(ZONE1.name(), "7"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), "8"); + waitUntilComplete(ZONE1.name(), "8"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); @@ -584,16 +596,16 @@ public void testCreateChange() { assertEquals("9", created.id()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone - checkChangeComplete(ZONE1.name(), "9"); + waitUntilComplete(ZONE1.name(), "9"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - checkChangeComplete(ZONE1.name(), "10"); + waitUntilComplete(ZONE1.name(), "10"); assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); assertNull(created.startTimeMillis()); assertTrue(created.additions().isEmpty()); assertEquals("10", created.id()); assertNull(created.status()); - checkChangeComplete(ZONE1.name(), "10"); + waitUntilComplete(ZONE1.name(), "10"); } finally { clear(); } @@ -618,18 +630,19 @@ public void testListChanges() { assertEquals(1, changes.size()); // default change creating SOA and NS // zone has changes ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); assertEquals(5, changes.size()); // error in options try { DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(0)); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); @@ -637,6 +650,7 @@ public void testListChanges() { } try { DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(-1)); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); @@ -754,27 +768,16 @@ public void testGetProject() { // fetches all fields ProjectInfo project = DNS.getProject(); assertNotNull(project.quota()); - assertNotNull(project.number()); - assertNotNull(project.id()); - assertEquals(PROJECT_ID, project.id()); // options project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.QUOTA)); assertNotNull(project.quota()); - assertNull(project.number()); - assertNotNull(project.id()); // id is always returned project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.PROJECT_ID)); assertNull(project.quota()); - assertNull(project.number()); - assertNotNull(project.id()); project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.PROJECT_NUMBER)); assertNull(project.quota()); - assertNotNull(project.number()); - assertNotNull(project.id()); project = DNS.getProject(Dns.ProjectOption.fields(Dns.ProjectField.PROJECT_NUMBER, Dns.ProjectField.QUOTA, Dns.ProjectField.PROJECT_ID)); assertNotNull(project.quota()); - assertNotNull(project.number()); - assertNotNull(project.id()); } @Test @@ -846,7 +849,7 @@ public void testListDnsRecords() { assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); counter = 0; @@ -858,7 +861,7 @@ public void testListDnsRecords() { } assertEquals(2, counter); // test type filter - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) @@ -874,30 +877,30 @@ public void testListDnsRecords() { // check wrong arguments try { // name is not set - DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); // todo(mderka) test retry functionality when available } try { - DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.pageSize(0)); + DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(0)); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); // todo(mderka) test retry functionality when available } try { - DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.pageSize(-1)); + DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(-1)); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); // todo(mderka) test retry functionality when available } - checkChangeComplete(ZONE1.name(), change.id()); + waitUntilComplete(ZONE1.name(), change.id()); } finally { clear(); } From 4f2810143b17838a75c59bc5615ec44b86a58cab Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 1 Mar 2016 16:09:49 -0800 Subject: [PATCH 56/74] Added retries for userRateLimitExceeded and rateLimitExceeded. --- .../src/main/java/com/google/gcloud/dns/DnsException.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java index 70d7254e9502..1ecb98a3fdc6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsException.java @@ -31,9 +31,12 @@ public class DnsException extends BaseServiceException { // see: https://cloud.google.com/dns/troubleshooting private static final Set RETRYABLE_ERRORS = ImmutableSet.of( + new Error(429, null), new Error(500, null), new Error(502, null), - new Error(503, null)); + new Error(503, null), + new Error(null, "userRateLimitExceeded"), + new Error(null, "rateLimitExceeded")); private static final long serialVersionUID = 490302380416260252L; public DnsException(IOException exception) { From 5858809c9eee2c561f9496552328e6ab1b4bdb40 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 2 Mar 2016 17:32:17 -0800 Subject: [PATCH 57/74] pom.xml version edit --- gcloud-java-dns/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gcloud-java-dns/pom.xml b/gcloud-java-dns/pom.xml index 5f04f261d500..1a559473cc82 100644 --- a/gcloud-java-dns/pom.xml +++ b/gcloud-java-dns/pom.xml @@ -13,7 +13,7 @@ com.google.gcloud gcloud-java-pom - 0.1.3-SNAPSHOT + 0.1.5-SNAPSHOT gcloud-java-dns From 86845061f481d0125ba18ce044cd242e396f40af Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 3 Mar 2016 09:48:50 -0800 Subject: [PATCH 58/74] Added missing waits for change completion. --- .../test/java/com/google/gcloud/dns/it/ITDnsTest.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index ae721e742ae8..fd257c681225 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -52,11 +52,10 @@ public class ITDnsTest { public static final String PREFIX = "gcldjvit-"; public static final Dns DNS = DnsOptions.builder().build().service(); - public static final String PROJECT_ID = DNS.options().projectId(); public static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32); public static final String ZONE_NAME_EMPTY_DESCRIPTION = - ("gcldjvit-" + UUID.randomUUID()).substring(0, 32); - public static final String ZONE_NAME_TOO_LONG = (PREFIX + UUID.randomUUID()); + (PREFIX + UUID.randomUUID()).substring(0, 32); + public static final String ZONE_NAME_TOO_LONG = PREFIX + UUID.randomUUID(); public static final String ZONE_DESCRIPTION1 = "first zone"; public static final String ZONE_DNS_NAME1 = ZONE_NAME1 + ".com."; public static final String ZONE_DNS_EMPTY_DESCRIPTION = ZONE_NAME_EMPTY_DESCRIPTION + ".com."; @@ -727,6 +726,7 @@ public void testGetChange() { ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.id()); assertEqChangesIgnoreStatus(created, retrieved); + waitUntilComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); // with options created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, @@ -734,30 +734,35 @@ public void testGetChange() { retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); assertEqChangesIgnoreStatus(created, retrieved); + waitUntilComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); assertEqChangesIgnoreStatus(created, retrieved); + waitUntilComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); assertEqChangesIgnoreStatus(created, retrieved); + waitUntilComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); assertEqChangesIgnoreStatus(created, retrieved); + waitUntilComplete(zone.name(), created.id()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); assertEqChangesIgnoreStatus(created, retrieved); + waitUntilComplete(zone.name(), created.id()); } finally { clear(); } From b8031e1d1c5068f6bf9f1a5bf180de9aa94fc1d8 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 4 Mar 2016 09:29:18 -0800 Subject: [PATCH 59/74] Adjusted clear not to collide when parallel test are running. --- .../com/google/gcloud/dns/it/ITDnsTest.java | 119 +++++++++--------- 1 file changed, 63 insertions(+), 56 deletions(-) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index fd257c681225..fda579a4a94b 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -50,68 +50,75 @@ public class ITDnsTest { // todo(mderka) Implement test for creating invalid change when DnsException is finished. #673 - public static final String PREFIX = "gcldjvit-"; - public static final Dns DNS = DnsOptions.builder().build().service(); - public static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32); - public static final String ZONE_NAME_EMPTY_DESCRIPTION = + private static final String PREFIX = "gcldjvit-"; + private static final Dns DNS = DnsOptions.builder().build().service(); + private static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32); + private static final String ZONE_NAME_EMPTY_DESCRIPTION = (PREFIX + UUID.randomUUID()).substring(0, 32); - public static final String ZONE_NAME_TOO_LONG = PREFIX + UUID.randomUUID(); - public static final String ZONE_DESCRIPTION1 = "first zone"; - public static final String ZONE_DNS_NAME1 = ZONE_NAME1 + ".com."; - public static final String ZONE_DNS_EMPTY_DESCRIPTION = ZONE_NAME_EMPTY_DESCRIPTION + ".com."; - public static final String ZONE_DNS_NAME_NO_PERIOD = ZONE_NAME1 + ".com"; - public static final ZoneInfo ZONE1 = ZoneInfo.builder(ZONE_NAME1) + private static final String ZONE_NAME_TOO_LONG = PREFIX + UUID.randomUUID(); + private static final String ZONE_DESCRIPTION1 = "first zone"; + private static final String ZONE_DNS_NAME1 = ZONE_NAME1 + ".com."; + private static final String ZONE_DNS_EMPTY_DESCRIPTION = ZONE_NAME_EMPTY_DESCRIPTION + ".com."; + private static final String ZONE_DNS_NAME_NO_PERIOD = ZONE_NAME1 + ".com"; + private static final ZoneInfo ZONE1 = ZoneInfo.builder(ZONE_NAME1) .description(ZONE_DESCRIPTION1) .dnsName(ZONE_DNS_EMPTY_DESCRIPTION) .build(); - public static final ZoneInfo ZONE_EMPTY_DESCRIPTION = + private static final ZoneInfo ZONE_EMPTY_DESCRIPTION = ZoneInfo.builder(ZONE_NAME_EMPTY_DESCRIPTION) .description(ZONE_DESCRIPTION1) .dnsName(ZONE_DNS_NAME1) .build(); - public static final ZoneInfo ZONE_NAME_ERROR = ZoneInfo.builder(ZONE_NAME_TOO_LONG) + private static final ZoneInfo ZONE_NAME_ERROR = ZoneInfo.builder(ZONE_NAME_TOO_LONG) .description(ZONE_DESCRIPTION1) .dnsName(ZONE_DNS_NAME1) .build(); - public static final ZoneInfo ZONE_MISSING_DESCRIPTION = ZoneInfo.builder(ZONE_NAME1) + private static final ZoneInfo ZONE_MISSING_DESCRIPTION = ZoneInfo.builder(ZONE_NAME1) .dnsName(ZONE_DNS_NAME1) .build(); - public static final ZoneInfo ZONE_MISSING_DNS_NAME = ZoneInfo.builder(ZONE_NAME1) + private static final ZoneInfo ZONE_MISSING_DNS_NAME = ZoneInfo.builder(ZONE_NAME1) .description(ZONE_DESCRIPTION1) .build(); - public static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.builder(ZONE_NAME1) + private static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.builder(ZONE_NAME1) .description(ZONE_DESCRIPTION1) .dnsName(ZONE_DNS_NAME_NO_PERIOD) .build(); - public static final DnsRecord A_RECORD_ZONE1 = + private static final DnsRecord A_RECORD_ZONE1 = DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) .records(ImmutableList.of("123.123.55.1")) .ttl(25, TimeUnit.SECONDS) .build(); - public static final DnsRecord AAAA_RECORD_ZONE1 = + private static final DnsRecord AAAA_RECORD_ZONE1 = DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.AAAA) .records(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) .ttl(25, TimeUnit.SECONDS) .build(); - public static final ChangeRequest CHANGE_ADD_ZONE1 = ChangeRequest.builder() + private static final ChangeRequest CHANGE_ADD_ZONE1 = ChangeRequest.builder() .add(A_RECORD_ZONE1) .add(AAAA_RECORD_ZONE1) .build(); - public static final ChangeRequest CHANGE_DELETE_ZONE1 = ChangeRequest.builder() + private static final ChangeRequest CHANGE_DELETE_ZONE1 = ChangeRequest.builder() .delete(A_RECORD_ZONE1) .delete(AAAA_RECORD_ZONE1) .build(); + private static final List ZONE_NAMES = ImmutableList.of(ZONE_NAME1, + ZONE_NAME_EMPTY_DESCRIPTION); - public static void clear() { - Page zones = DNS.listZones(); - Iterator zoneIterator = zones.iterateAll(); - while (zoneIterator.hasNext()) { - Zone zone = zoneIterator.next(); - List toDelete = new LinkedList<>(); - if (zone.name().startsWith(PREFIX)) { - Iterator dnsRecordIterator = zone.listDnsRecords().iterateAll(); - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); + private static void clear() { + for (String zoneName : ZONE_NAMES) { + Zone zone = DNS.getZone(zoneName); + if (zone != null) { + /* We wait for all changes to complete before retrieving a list of DNS records to be + deleted. Waiting is necessary as changes potentially might create more records between + when the list has been retrieved and executing the subsequent delete operation. */ + Iterator iterator = zone.listChangeRequests().iterateAll(); + while (iterator.hasNext()) { + waitForChangeToComplete(zoneName, iterator.next().id()); + } + Iterator recordIterator = zone.listDnsRecords().iterateAll(); + List toDelete = new LinkedList<>(); + while (recordIterator.hasNext()) { + DnsRecord record = recordIterator.next(); if (!ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA).contains(record.type())) { toDelete.add(record); } @@ -119,7 +126,7 @@ public static void clear() { if (!toDelete.isEmpty()) { ChangeRequest deletion = zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); - waitUntilComplete(zone.name(), deletion.id()); + waitForChangeToComplete(zone.name(), deletion.id()); } zone.delete(); } @@ -130,7 +137,7 @@ private static List filter(Iterator iterator) { List result = new LinkedList<>(); while (iterator.hasNext()) { Zone zone = iterator.next(); - if (zone.name().startsWith(PREFIX)) { + if (ZONE_NAMES.contains(zone.name())) { result.add(zone); } } @@ -154,7 +161,7 @@ private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRe assertEquals(expected.startTimeMillis(), actual.startTimeMillis()); } - private static void waitUntilComplete(String zoneName, String changeId) { + private static void waitForChangeToComplete(String zoneName, String changeId) { while (true) { ChangeRequest changeRequest = DNS.getChangeRequest(zoneName, changeId, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); @@ -553,9 +560,9 @@ public void testCreateChange() { assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); - waitUntilComplete(ZONE1.name(), "1"); + waitForChangeToComplete(ZONE1.name(), "1"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitUntilComplete(ZONE1.name(), "2"); + waitForChangeToComplete(ZONE1.name(), "2"); // with options created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); @@ -564,9 +571,9 @@ public void testCreateChange() { assertTrue(created.deletions().isEmpty()); assertEquals("3", created.id()); assertNull(created.status()); - waitUntilComplete(ZONE1.name(), "3"); + waitForChangeToComplete(ZONE1.name(), "3"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitUntilComplete(ZONE1.name(), "4"); + waitForChangeToComplete(ZONE1.name(), "4"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); assertTrue(created.additions().isEmpty()); @@ -574,9 +581,9 @@ public void testCreateChange() { assertTrue(created.deletions().isEmpty()); assertEquals("5", created.id()); assertNotNull(created.status()); - waitUntilComplete(ZONE1.name(), "5"); + waitForChangeToComplete(ZONE1.name(), "5"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitUntilComplete(ZONE1.name(), "6"); + waitForChangeToComplete(ZONE1.name(), "6"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); assertTrue(created.additions().isEmpty()); @@ -584,9 +591,9 @@ public void testCreateChange() { assertTrue(created.deletions().isEmpty()); assertEquals("7", created.id()); assertNull(created.status()); - waitUntilComplete(ZONE1.name(), "7"); + waitForChangeToComplete(ZONE1.name(), "7"); DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitUntilComplete(ZONE1.name(), "8"); + waitForChangeToComplete(ZONE1.name(), "8"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); @@ -595,16 +602,16 @@ public void testCreateChange() { assertEquals("9", created.id()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone - waitUntilComplete(ZONE1.name(), "9"); + waitForChangeToComplete(ZONE1.name(), "9"); created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); - waitUntilComplete(ZONE1.name(), "10"); + waitForChangeToComplete(ZONE1.name(), "10"); assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); assertNull(created.startTimeMillis()); assertTrue(created.additions().isEmpty()); assertEquals("10", created.id()); assertNull(created.status()); - waitUntilComplete(ZONE1.name(), "10"); + waitForChangeToComplete(ZONE1.name(), "10"); } finally { clear(); } @@ -629,13 +636,13 @@ public void testListChanges() { assertEquals(1, changes.size()); // default change creating SOA and NS // zone has changes ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); assertEquals(5, changes.size()); // error in options @@ -726,7 +733,7 @@ public void testGetChange() { ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.id()); assertEqChangesIgnoreStatus(created, retrieved); - waitUntilComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); // with options created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, @@ -734,35 +741,35 @@ public void testGetChange() { retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ID)); assertEqChangesIgnoreStatus(created, retrieved); - waitUntilComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS)); assertEqChangesIgnoreStatus(created, retrieved); - waitUntilComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); assertEqChangesIgnoreStatus(created, retrieved); - waitUntilComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.id()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.ADDITIONS)); assertEqChangesIgnoreStatus(created, retrieved); - waitUntilComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.id()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); retrieved = DNS.getChangeRequest(zone.name(), created.id(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.DELETIONS)); assertEqChangesIgnoreStatus(created, retrieved); - waitUntilComplete(zone.name(), created.id()); + waitForChangeToComplete(zone.name(), created.id()); } finally { clear(); } @@ -854,7 +861,7 @@ public void testListDnsRecords() { assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); counter = 0; @@ -866,7 +873,7 @@ public void testListDnsRecords() { } assertEquals(2, counter); // test type filter - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) @@ -905,7 +912,7 @@ public void testListDnsRecords() { assertEquals(400, ex.code()); // todo(mderka) test retry functionality when available } - waitUntilComplete(ZONE1.name(), change.id()); + waitForChangeToComplete(ZONE1.name(), change.id()); } finally { clear(); } From 1f06caf21d73921280ce6e724cbaebb6f22169d4 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 24 Feb 2016 10:11:02 -0800 Subject: [PATCH 60/74] The following has been done within multiple iterations: Refactored URL parsing and removed unnecessary doc in local helper. Refactored to use AtomicReference instead of singleton Map. Adjusted tests of paging to test that pages contain expected objects. Added check and test for deleting non-empy zone. Removed RrsetWapper and used tailMap in listing. Added @VisibleForTesting annotations. Added fails to expected exceptions. Added error message checks. Addressed codacy suggestions. Assigned project ID to the helper and test. Added pool of executors instead of spawning one threads. Reduced number of threads. --- .../{ => dns}/testing/LocalDnsHelper.java | 719 ++++------- .../testing/OptionParsers.java} | 63 +- .../com/google/gcloud/spi/DefaultDnsRpc.java | 6 +- .../{ => dns}/testing/LocalDnsHelperTest.java | 1116 ++++++----------- 4 files changed, 678 insertions(+), 1226 deletions(-) rename gcloud-java-dns/src/main/java/com/google/gcloud/{ => dns}/testing/LocalDnsHelper.java (63%) rename gcloud-java-dns/src/main/java/com/google/gcloud/{testing/OptionParsersAndExtractors.java => dns/testing/OptionParsers.java} (80%) rename gcloud-java-dns/src/test/java/com/google/gcloud/{ => dns}/testing/LocalDnsHelperTest.java (63%) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java similarity index 63% rename from gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java index b8483bc4fcd7..f9cd1a11281e 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/LocalDnsHelper.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package com.google.gcloud.testing; +package com.google.gcloud.dns.testing; -import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.net.InetAddresses.isInetAddress; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.net.HttpURLConnection.HTTP_OK; @@ -27,12 +27,12 @@ import com.google.api.services.dns.model.Project; import com.google.api.services.dns.model.Quota; import com.google.api.services.dns.model.ResourceRecordSet; -import com.google.common.base.Function; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; @@ -54,26 +54,32 @@ import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.NavigableMap; import java.util.NavigableSet; -import java.util.Objects; import java.util.Random; import java.util.Set; +import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; -import javax.annotation.Nullable; - /** - * A utility to create local Google Cloud DNS mock. + * A local Google Cloud DNS mock. * *

The mock runs in a separate thread, listening for HTTP requests on the local machine at an * ephemeral port. @@ -81,7 +87,7 @@ *

While the mock attempts to simulate the service, there are some differences in the behaviour. * The mock will accept any project ID and never returns a notFound or another error because of * project ID. It assumes that all project IDs exist and that the user has all the necessary - * privileges to manipulate any project. Similarly, the local simulation does not work with any + * privileges to manipulate any project. Similarly, the local simulation does not require * verification of domain name ownership. Any request for creating a managed zone will be approved. * The mock does not track quota and will allow the user to exceed it. The mock provides only basic * validation of the DNS data for records of type A and AAAA. It does not validate any other record @@ -97,16 +103,21 @@ public class LocalDnsHelper { private static final Random ID_GENERATOR = new Random(); private static final String VERSION = "v1"; private static final String CONTEXT = "/dns/" + VERSION + "/projects"; - private static final Set SUPPORTED_COMPRESSION_ENCODINGS = - ImmutableSet.of("gzip", "x-gzip"); + private static final Set ENCODINGS = ImmutableSet.of("gzip", "x-gzip"); private static final List TYPES = ImmutableList.of("A", "AAAA", "CNAME", "MX", "NAPTR", "NS", "PTR", "SOA", "SPF", "SRV", "TXT"); + private static final TreeSet FORBIDDEN = Sets.newTreeSet( + ImmutableList.of("google.com.", "com.", "example.com.", "net.", "org.")); + private static final Pattern ZONE_NAME_RE = Pattern.compile("[a-z][a-z0-9-]*"); + private static final ScheduledExecutorService EXECUTORS = + Executors.newScheduledThreadPool(2, Executors.defaultThreadFactory()); + private static final String PROJECT_ID = "dummyprojectid"; static { try { BASE_CONTEXT = new URI(CONTEXT); } catch (URISyntaxException e) { - throw new RuntimeException( + throw new IllegalArgumentException( "Could not initialize LocalDnsHelper due to URISyntaxException.", e); } } @@ -139,67 +150,7 @@ private enum CallRegex { } /** - * Wraps DNS data by adding a timestamp and id which is used for paging and listing. - */ - static class RrsetWrapper { - static final Function WRAP_FUNCTION = - new Function() { - @Nullable - @Override - public RrsetWrapper apply(@Nullable ResourceRecordSet input) { - return new RrsetWrapper(input); - } - }; - private final ResourceRecordSet rrset; - private final Long timestamp = System.currentTimeMillis(); - private String id; - - RrsetWrapper(ResourceRecordSet rrset) { - // The constructor creates a copy in order to prevent side effects. - this.rrset = new ResourceRecordSet(); - this.rrset.setName(rrset.getName()); - this.rrset.setTtl(rrset.getTtl()); - this.rrset.setRrdatas(ImmutableList.copyOf(rrset.getRrdatas())); - this.rrset.setType(rrset.getType()); - } - - void setId(String id) { - this.id = id; - } - - String id() { - return id; - } - - /** - * Equals does not care about the listing id and timestamp metadata, just the rrset. - */ - @Override - public boolean equals(Object other) { - return (other instanceof RrsetWrapper) && Objects.equals(rrset, ((RrsetWrapper) other).rrset); - } - - @Override - public int hashCode() { - return Objects.hash(rrset); - } - - ResourceRecordSet rrset() { - return rrset; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("rrset", rrset) - .add("timestamp", timestamp) - .add("id", id) - .toString(); - } - } - - /** - * Associates a project with a collection of ManagedZones. Thread safe. + * Associates a project with a collection of ManagedZones. */ static class ProjectContainer { private final Project project; @@ -220,29 +171,24 @@ ConcurrentSkipListMap zones() { } /** - * Associates a zone with a collection of changes and dns records. Thread safe. + * Associates a zone with a collection of changes and dns records. */ static class ZoneContainer { private final ManagedZone zone; - /** - * DNS records are held in a map to allow for atomic replacement of record sets when applying - * changes. The key for the map is always the zone name. The collection of records is immutable - * and must always exist, i.e., dnsRecords.get(zone.getName()) is never {@code null}. - */ - private final ConcurrentSkipListMap> - dnsRecords = new ConcurrentSkipListMap<>(); + private final AtomicReference> + dnsRecords = new AtomicReference<>(ImmutableSortedMap.of()); private final ConcurrentLinkedQueue changes = new ConcurrentLinkedQueue<>(); ZoneContainer(ManagedZone zone) { this.zone = zone; - this.dnsRecords.put(zone.getName(), ImmutableList.of()); + this.dnsRecords.set(ImmutableSortedMap.of()); } ManagedZone zone() { return zone; } - ConcurrentSkipListMap> dnsRecords() { + AtomicReference> dnsRecords() { return dnsRecords; } @@ -283,6 +229,7 @@ private enum Error { INTERNAL_ERROR(500, "global", "internalError", "INTERNAL_ERROR"), BAD_REQUEST(400, "global", "badRequest", "BAD_REQUEST"), INVALID(400, "global", "invalid", "INVALID"), + CONTAINER_NOT_EMPTY(400, "global", "containerNotEmpty", "CONTAINER_NOT_EMPTY"), NOT_AVAILABLE(400, "global", "managedZoneDnsNameNotAvailable", "NOT_AVAILABLE"), NOT_FOUND(404, "global", "notFound", "NOT_FOUND"), ALREADY_EXISTS(409, "global", "alreadyExists", "ALREADY_EXISTS"), @@ -325,34 +272,38 @@ private String toJson(String message) throws IOException { private class RequestHandler implements HttpHandler { - /** - * Chooses the proper handler for a request. - */ private Response pickHandler(HttpExchange exchange, CallRegex regex) { + URI relative = BASE_CONTEXT.relativize(exchange.getRequestURI()); + String path = relative.getPath(); + String[] tokens = path.split("/"); + String projectId = tokens.length > 0 ? tokens[0] : null; + String zoneName = tokens.length > 2 ? tokens[2] : null; + String changeId = tokens.length > 4 ? tokens[4] : null; + String query = relative.getQuery(); switch (regex) { case CHANGE_GET: - return handleChangeGet(exchange); + return getChange(projectId, zoneName, changeId, query); case CHANGE_LIST: - return handleChangeList(exchange); + return listChanges(projectId, zoneName, query); case ZONE_GET: - return handleZoneGet(exchange); + return getZone(projectId, zoneName, query); case ZONE_DELETE: - return handleZoneDelete(exchange); + return deleteZone(projectId, zoneName); case ZONE_LIST: - return handleZoneList(exchange); + return listZones(projectId, query); case PROJECT_GET: - return handleProjectGet(exchange); + return getProject(projectId, query); case RECORD_LIST: - return handleDnsRecordList(exchange); + return listDnsRecords(projectId, zoneName, query); case ZONE_CREATE: try { - return handleZoneCreate(exchange); + return handleZoneCreate(exchange, projectId, query); } catch (IOException ex) { return Error.BAD_REQUEST.response(ex.getMessage()); } case CHANGE_CREATE: try { - return handleChangeCreate(exchange); + return handleChangeCreate(exchange, projectId, zoneName, query); } catch (IOException ex) { return Error.BAD_REQUEST.response(ex.getMessage()); } @@ -367,122 +318,53 @@ public void handle(HttpExchange exchange) throws IOException { String rawPath = exchange.getRequestURI().getRawPath(); for (CallRegex regex : CallRegex.values()) { if (requestMethod.equals(regex.method) && rawPath.matches(regex.pathRegex)) { - // there is a match, pass the handling accordingly Response response = pickHandler(exchange, regex); writeResponse(exchange, response); - return; // only one match is possible + return; } } - // could not be matched, the service returns 404 page not found here - writeResponse(exchange, Error.NOT_FOUND.response("The url does not match any API call.")); - } - - private Response handleZoneDelete(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String zoneName = tokens[2]; - return deleteZone(projectId, zoneName); - } - - private Response handleZoneGet(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String zoneName = tokens[2]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - String[] fields = OptionParsersAndExtractors.parseGetOptions(query); - return getZone(projectId, zoneName, fields); - } - - private Response handleZoneList(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - Map options = OptionParsersAndExtractors.parseListZonesOptions(query); - return listZones(projectId, options); - } - - private Response handleProjectGet(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - String[] fields = OptionParsersAndExtractors.parseGetOptions(query); - return getProject(projectId, fields); + writeResponse(exchange, Error.NOT_FOUND.response(String.format( + "The url %s for %s method does not match any API call.", + requestMethod, exchange.getRequestURI()))); } /** * @throws IOException if the request cannot be parsed. */ - private Response handleChangeCreate(HttpExchange exchange) throws IOException { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String zoneName = tokens[2]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - String[] fields = OptionParsersAndExtractors.parseGetOptions(query); + private Response handleChangeCreate(HttpExchange exchange, String projectId, String zoneName, + String query) throws IOException { String requestBody = decodeContent(exchange.getRequestHeaders(), exchange.getRequestBody()); - Change change = jsonFactory.fromString(requestBody, Change.class); + Change change; + try { + change = jsonFactory.fromString(requestBody, Change.class); + } catch (IllegalArgumentException ex) { + return Error.REQUIRED.response( + "The 'entity.change' parameter is required but was missing."); + } + String[] fields = OptionParsers.parseGetOptions(query); return createChange(projectId, zoneName, change, fields); } - private Response handleChangeGet(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String zoneName = tokens[2]; - String changeId = tokens[4]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - String[] fields = OptionParsersAndExtractors.parseGetOptions(query); - return getChange(projectId, zoneName, changeId, fields); - } - - private Response handleChangeList(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String zoneName = tokens[2]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - Map options = OptionParsersAndExtractors.parseListChangesOptions(query); - return listChanges(projectId, zoneName, options); - } - - private Response handleDnsRecordList(HttpExchange exchange) { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String zoneName = tokens[2]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - Map options = OptionParsersAndExtractors.parseListDnsRecordsOptions(query); - return listDnsRecords(projectId, zoneName, options); - } - /** * @throws IOException if the request cannot be parsed. */ - private Response handleZoneCreate(HttpExchange exchange) throws IOException { - String path = BASE_CONTEXT.relativize(exchange.getRequestURI()).getPath(); - String[] tokens = path.split("/"); - String projectId = tokens[0]; - String query = BASE_CONTEXT.relativize(exchange.getRequestURI()).getQuery(); - String[] options = OptionParsersAndExtractors.parseGetOptions(query); + private Response handleZoneCreate(HttpExchange exchange, String projectId, String query) + throws IOException { String requestBody = decodeContent(exchange.getRequestHeaders(), exchange.getRequestBody()); ManagedZone zone; try { - // IllegalArgumentException if the request body is an empty string zone = jsonFactory.fromString(requestBody, ManagedZone.class); } catch (IllegalArgumentException ex) { return Error.REQUIRED.response( "The 'entity.managedZone' parameter is required but was missing."); } + String[] options = OptionParsers.parseGetOptions(query); return createZone(projectId, zone, options); } } private LocalDnsHelper(long delay) { - this.delayChange = delay; // 0 makes this synchronous + this.delayChange = delay; try { server = HttpServer.create(new InetSocketAddress(0), 0); port = server.getAddress().getPort(); @@ -501,9 +383,9 @@ ConcurrentSkipListMap projects() { /** * Creates new {@link LocalDnsHelper} instance that listens to requests on the local machine. This - * instance processes changes separate threads. The parameter determines how long a thread should - * wait before processing a change. If it is set to 0, the threading is turned off and the mock - * will behave synchronously. + * instance processes changes in separate thread. The parameter determines how long a thread + * should wait before processing a change. If it is set to 0, the threading is turned off and the + * mock will behave synchronously. * * @param delay delay for processing changes in ms or 0 for synchronous processing */ @@ -512,10 +394,10 @@ public static LocalDnsHelper create(Long delay) { } /** - * Returns a DnsOptions instance that sets the host to use the mock server. + * Returns a {@link DnsOptions} instance that sets the host to use the mock server. */ public DnsOptions options() { - return DnsOptions.builder().host("http://localhost:" + port).build(); + return DnsOptions.builder().projectId(PROJECT_ID).host("http://localhost:" + port).build(); } /** @@ -539,6 +421,7 @@ private static void writeResponse(HttpExchange exchange, Response response) { exchange.getResponseHeaders().add("Connection", "close"); exchange.sendResponseHeaders(response.code(), response.body().length()); if (response.code() != 204) { + // the server automatically sends headers and closes output stream when 204 is returned outputStream.write(response.body().getBytes(StandardCharsets.UTF_8)); } outputStream.close(); @@ -547,18 +430,15 @@ private static void writeResponse(HttpExchange exchange, Response response) { } } - /** - * Decodes content of the HttpRequest. - */ private static String decodeContent(Headers headers, InputStream inputStream) throws IOException { List contentEncoding = headers.get("Content-encoding"); InputStream input = inputStream; try { if (contentEncoding != null && !contentEncoding.isEmpty()) { String encoding = contentEncoding.get(0); - if (SUPPORTED_COMPRESSION_ENCODINGS.contains(encoding)) { + if (ENCODINGS.contains(encoding)) { input = new GZIPInputStream(inputStream); - } else if (!encoding.equals("identity")) { + } else if (!"identity".equals(encoding)) { throw new IOException( "The request has the following unsupported HTTP content encoding: " + encoding); } @@ -574,25 +454,25 @@ private static String decodeContent(Headers headers, InputStream inputStream) th * * @param context managedZones | projects | rrsets | changes */ + @VisibleForTesting static Response toListResponse(List serializedObjects, String context, String pageToken, boolean includePageToken) { - // start building response StringBuilder responseBody = new StringBuilder(); responseBody.append("{\"").append(context).append("\": ["); Joiner.on(",").appendTo(responseBody, serializedObjects); - responseBody.append("]"); - // add page token only if exists and is asked for + responseBody.append(']'); + // add page token only if it exists and is asked for if (pageToken != null && includePageToken) { - responseBody.append(",\"nextPageToken\": \"").append(pageToken).append("\""); + responseBody.append(",\"nextPageToken\": \"").append(pageToken).append('"'); } - responseBody.append("}"); + responseBody.append('}'); return new Response(HTTP_OK, responseBody.toString()); } /** * Prepares DNS records that are created by default for each zone. */ - private static ImmutableList defaultRecords(ManagedZone zone) { + private static ImmutableSortedMap defaultRecords(ManagedZone zone) { ResourceRecordSet soa = new ResourceRecordSet(); soa.setTtl(21600); soa.setName(zone.getDnsName()); @@ -606,17 +486,15 @@ private static ImmutableList defaultRecords(ManagedZone zone) { ns.setName(zone.getDnsName()); ns.setRrdatas(zone.getNameServers()); ns.setType("NS"); - RrsetWrapper nsWrapper = new RrsetWrapper(ns); - RrsetWrapper soaWrapper = new RrsetWrapper(soa); - ImmutableList results = ImmutableList.of(nsWrapper, soaWrapper); - nsWrapper.setId(getUniqueId(results)); - soaWrapper.setId(getUniqueId(results)); - return results; + String nsId = getUniqueId(ImmutableSet.of()); + String soaId = getUniqueId(ImmutableSet.of(nsId)); + return ImmutableSortedMap.of(nsId, ns, soaId, soa); } /** * Returns a list of four nameservers randomly chosen from the predefined set. */ + @VisibleForTesting static List randomNameservers() { ArrayList nameservers = Lists.newArrayList( "dns1.googlecloud.com", "dns2.googlecloud.com", "dns3.googlecloud.com", @@ -630,23 +508,14 @@ static List randomNameservers() { } /** - * Returns a hex string id (used for a dns record) unique within the set of wrappers. + * Returns a hex string id (used for a dns record) unique within the set of ids. */ - static String getUniqueId(List wrappers) { - TreeSet ids = Sets.newTreeSet(Lists.transform(wrappers, - new Function() { - @Override - public String apply(RrsetWrapper input) { - return input.id() == null ? "null" : input.id(); - } - })); + @VisibleForTesting + static String getUniqueId(Set ids) { String id; do { id = Long.toHexString(System.currentTimeMillis()) + Long.toHexString(Math.abs(ID_GENERATOR.nextLong())); - if (!ids.contains(id)) { - return id; - } } while (ids.contains(id)); return id; } @@ -654,21 +523,19 @@ public String apply(RrsetWrapper input) { /** * Tests if a DNS record matches name and type (if provided). Used for filtering. */ + @VisibleForTesting static boolean matchesCriteria(ResourceRecordSet record, String name, String type) { if (type != null && !record.getType().equals(type)) { return false; } - if (name != null && !record.getName().equals(name)) { - return false; - } - return true; + return name == null || record.getName().equals(name); } /** * Returns a project container. Never returns {@code null} because we assume that all projects * exists. */ - ProjectContainer findProject(String projectId) { + private ProjectContainer findProject(String projectId) { ProjectContainer defaultProject = createProject(projectId); projects.putIfAbsent(projectId, defaultProject); return projects.get(projectId); @@ -677,6 +544,7 @@ ProjectContainer findProject(String projectId) { /** * Returns a zone container. Returns {@code null} if zone does not exist within project. */ + @VisibleForTesting ZoneContainer findZone(String projectId, String zoneName) { ProjectContainer projectContainer = findProject(projectId); // never null return projectContainer.zones().get(zoneName); @@ -685,6 +553,7 @@ ZoneContainer findZone(String projectId, String zoneName) { /** * Returns a change found by its id. Returns {@code null} if such a change does not exist. */ + @VisibleForTesting Change findChange(String projectId, String zoneName, String changeId) { ZoneContainer wrapper = findZone(projectId, zoneName); return wrapper == null ? null : wrapper.findChange(changeId); @@ -693,20 +562,20 @@ Change findChange(String projectId, String zoneName, String changeId) { /** * Returns a response to getChange service call. */ - Response getChange(String projectId, String zoneName, String changeId, String[] fields) { + @VisibleForTesting + Response getChange(String projectId, String zoneName, String changeId, String query) { Change change = findChange(projectId, zoneName, changeId); if (change == null) { ZoneContainer zone = findZone(projectId, zoneName); if (zone == null) { - // zone does not exist return Error.NOT_FOUND.response(String.format( "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)); } - // zone exists but change does not return Error.NOT_FOUND.response(String.format( "The 'parameters.changeId' resource named '%s' does not exist.", changeId)); } - Change result = OptionParsersAndExtractors.extractFields(change, fields); + String[] fields = OptionParsers.parseGetOptions(query); + Change result = OptionParsers.extractFields(change, fields); try { return new Response(HTTP_OK, jsonFactory.toString(result)); } catch (IOException e) { @@ -719,13 +588,15 @@ Response getChange(String projectId, String zoneName, String changeId, String[] /** * Returns a response to getZone service call. */ - Response getZone(String projectId, String zoneName, String[] fields) { + @VisibleForTesting + Response getZone(String projectId, String zoneName, String query) { ZoneContainer container = findZone(projectId, zoneName); if (container == null) { return Error.NOT_FOUND.response(String.format( "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)); } - ManagedZone result = OptionParsersAndExtractors.extractFields(container.zone(), fields); + String[] fields = OptionParsers.parseGetOptions(query); + ManagedZone result = OptionParsers.extractFields(container.zone(), fields); try { return new Response(HTTP_OK, jsonFactory.toString(result)); } catch (IOException e) { @@ -738,11 +609,11 @@ Response getZone(String projectId, String zoneName, String[] fields) { * We assume that every project exists. If we do not have it in the collection yet, we just create * a new default project instance with default quota. */ - Response getProject(String projectId, String[] fields) { - ProjectContainer defaultProject = createProject(projectId); - projects.putIfAbsent(projectId, defaultProject); - Project project = projects.get(projectId).project(); // project is now guaranteed to exist - Project result = OptionParsersAndExtractors.extractFields(project, fields); + @VisibleForTesting + Response getProject(String projectId, String query) { + String[] fields = OptionParsers.parseGetOptions(query); + Project project = findProject(projectId).project(); // creates project if needed + Project result = OptionParsers.extractFields(project, fields); try { return new Response(HTTP_OK, jsonFactory.toString(result)); } catch (IOException e) { @@ -752,8 +623,7 @@ Response getProject(String projectId, String[] fields) { } /** - * Creates a project. It generates a project number randomly (we do not have project numbers - * available). + * Creates a project. It generates a project number randomly. */ private ProjectContainer createProject(String projectId) { Quota quota = new Quota(); @@ -771,14 +641,21 @@ private ProjectContainer createProject(String projectId) { return new ProjectContainer(project); } - /** - * Deletes a zone. - */ + @VisibleForTesting Response deleteZone(String projectId, String zoneName) { + ZoneContainer zone = findZone(projectId, zoneName); + ImmutableSortedMap rrsets = zone == null + ? ImmutableSortedMap.of() : zone.dnsRecords().get(); + ImmutableList defaults = ImmutableList.of("NS", "SOA"); + for (ResourceRecordSet current : rrsets.values()) { + if (!defaults.contains(current.getType())) { + return Error.CONTAINER_NOT_EMPTY.response(String.format( + "The resource named '%s' cannot be deleted because it is not empty", zoneName)); + } + } ProjectContainer projectContainer = projects.get(projectId); ZoneContainer previous = projectContainer.zones.remove(zoneName); return previous == null - // map was not in the collection ? Error.NOT_FOUND.response(String.format( "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)) : new Response(HTTP_NO_CONTENT, "{}"); @@ -787,14 +664,12 @@ Response deleteZone(String projectId, String zoneName) { /** * Creates new managed zone and stores it in the collection. Assumes that project exists. */ - Response createZone(String projectId, ManagedZone zone, String[] fields) { - checkNotNull(zone, "Zone to create cannot be null"); - // check if the provided data is valid + @VisibleForTesting + Response createZone(String projectId, ManagedZone zone, String... fields) { Response errorResponse = checkZone(zone); if (errorResponse != null) { return errorResponse; } - // create a copy of the managed zone in order to avoid side effects ManagedZone completeZone = new ManagedZone(); completeZone.setName(zone.getName()); completeZone.setDnsName(zone.getDnsName()); @@ -802,13 +677,10 @@ Response createZone(String projectId, ManagedZone zone, String[] fields) { completeZone.setNameServerSet(zone.getNameServerSet()); completeZone.setCreationTime(ISODateTimeFormat.dateTime().withZoneUTC() .print(System.currentTimeMillis())); - completeZone.setId( - new BigInteger(String.valueOf(Math.abs(ID_GENERATOR.nextLong() % Long.MAX_VALUE)))); + completeZone.setId(BigInteger.valueOf(Math.abs(ID_GENERATOR.nextLong() % Long.MAX_VALUE))); completeZone.setNameServers(randomNameservers()); ZoneContainer zoneContainer = new ZoneContainer(completeZone); - // create the default NS and SOA records - zoneContainer.dnsRecords().put(zone.getName(), defaultRecords(completeZone)); - // place the zone in the data collection + zoneContainer.dnsRecords().set(defaultRecords(completeZone)); ProjectContainer projectContainer = findProject(projectId); ZoneContainer oldValue = projectContainer.zones().putIfAbsent( completeZone.getName(), zoneContainer); @@ -816,8 +688,7 @@ Response createZone(String projectId, ManagedZone zone, String[] fields) { return Error.ALREADY_EXISTS.response(String.format( "The resource 'entity.managedZone' named '%s' already exists", completeZone.getName())); } - // now return the desired attributes - ManagedZone result = OptionParsersAndExtractors.extractFields(completeZone, fields); + ManagedZone result = OptionParsers.extractFields(completeZone, fields); try { return new Response(HTTP_OK, jsonFactory.toString(result)); } catch (IOException e) { @@ -827,30 +698,28 @@ Response createZone(String projectId, ManagedZone zone, String[] fields) { } /** - * Creates a new change, stores it, and invokes processing in a new thread. + * Creates a new change, stores it, and if delayChange > 0, invokes processing in a new thread. */ - Response createChange(String projectId, String zoneName, Change change, String[] fields) { + Response createChange(String projectId, String zoneName, Change change, String... fields) { ZoneContainer zoneContainer = findZone(projectId, zoneName); if (zoneContainer == null) { return Error.NOT_FOUND.response(String.format( "The 'parameters.managedZone' resource named %s does not exist.", zoneName)); } - // check that the change to be applied is valid Response response = checkChange(change, zoneContainer); if (response != null) { return response; } - // start applying - Change completeChange = new Change(); // copy to avoid side effects + Change completeChange = new Change(); if (change.getAdditions() != null) { completeChange.setAdditions(ImmutableList.copyOf(change.getAdditions())); } if (change.getDeletions() != null) { completeChange.setDeletions(ImmutableList.copyOf(change.getDeletions())); } - /* we need to get the proper ID in concurrent environment - the element fell on an index between 0 and maxId - we will reset all IDs in this range (all of them are valid) */ + /* We need to set ID for the change. We are working in concurrent environment. We know that the + element fell on an index between 0 and maxId, so we will reset all IDs in this range (all of + them are valid for the respective objects). */ ConcurrentLinkedQueue changeSequence = zoneContainer.changes(); changeSequence.add(completeChange); int maxId = changeSequence.size(); @@ -859,13 +728,13 @@ we will reset all IDs in this range (all of them are valid) */ if (index == maxId) { break; } - c.setId(String.valueOf(++index)); // indexing from 1 + c.setId(String.valueOf(++index)); } - completeChange.setStatus("pending"); // not finished yet + completeChange.setStatus("pending"); completeChange.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC() - .print(System.currentTimeMillis())); // accepted + .print(System.currentTimeMillis())); invokeChange(projectId, zoneName, completeChange.getId()); - Change result = OptionParsersAndExtractors.extractFields(completeChange, fields); + Change result = OptionParsers.extractFields(completeChange, fields); try { return new Response(HTTP_OK, jsonFactory.toString(result)); } catch (IOException e) { @@ -876,28 +745,20 @@ we will reset all IDs in this range (all of them are valid) */ } /** - * Applies change. Uses a new thread which applies the change only if DELAY_CHANGE is > 0. + * Applies change. Uses a different pooled thread which applies the change only if {@code + * delayChange} is > 0. */ - private Thread invokeChange(final String projectId, final String zoneName, + private void invokeChange(final String projectId, final String zoneName, final String changeId) { if (delayChange > 0) { - Thread thread = new Thread() { + EXECUTORS.schedule(new Runnable() { @Override public void run() { - try { - Thread.sleep(delayChange); // simulate delayed execution - } catch (InterruptedException ex) { - log.log(Level.WARNING, "Thread was interrupted while sleeping.", ex); - } - // start applying the changes applyExistingChange(projectId, zoneName, changeId); } - }; - thread.start(); - return thread; + }, delayChange, TimeUnit.MILLISECONDS); } else { applyExistingChange(projectId, zoneName, changeId); - return null; } } @@ -910,44 +771,55 @@ private void applyExistingChange(String projectId, String zoneName, String chang return; // no such change exists, nothing to do } ZoneContainer wrapper = findZone(projectId, zoneName); - ConcurrentSkipListMap> dnsRecords = wrapper.dnsRecords(); + if (wrapper == null) { + return; // no such zone exists; it might have been deleted by another thread + } + AtomicReference> dnsRecords = + wrapper.dnsRecords(); while (true) { // managed zone must have a set of records which is not null - ImmutableList original = dnsRecords.get(zoneName); - assert original != null; - List copy = Lists.newLinkedList(original); + ImmutableSortedMap original = dnsRecords.get(); + // the copy will be populated when handling deletions + SortedMap copy = new TreeMap<>(); // apply deletions first List deletions = change.getDeletions(); if (deletions != null) { - List transformedDeletions = Lists.transform(deletions, - RrsetWrapper.WRAP_FUNCTION); - copy.removeAll(transformedDeletions); + for (Map.Entry entry : original.entrySet()) { + if (!deletions.contains(entry.getValue())) { + copy.put(entry.getKey(), entry.getValue()); + } + } + } else { + copy.putAll(original); } // apply additions List additions = change.getAdditions(); if (additions != null) { for (ResourceRecordSet addition : additions) { - String id = getUniqueId(copy); - RrsetWrapper rrsetWrapper = new RrsetWrapper(addition); - rrsetWrapper.setId(id); - copy.add(rrsetWrapper); + ResourceRecordSet rrset = new ResourceRecordSet(); + rrset.setName(addition.getName()); + rrset.setRrdatas(ImmutableList.copyOf(addition.getRrdatas())); + rrset.setTtl(addition.getTtl()); + rrset.setType(addition.getType()); + String id = getUniqueId(copy.keySet()); + copy.put(id, rrset); } } - // make it immutable and replace - boolean success = dnsRecords.replace(zoneName, original, ImmutableList.copyOf(copy)); + boolean success = dnsRecords.compareAndSet(original, ImmutableSortedMap.copyOf(copy)); if (success) { break; // success if no other thread modified the value in the meantime } } - // set status to done change.setStatus("done"); } /** * Lists zones. Next page token is the last listed zone name and is returned only of there is more - * to list. + * to list and if the user does not exclude nextPageToken from field options. */ - Response listZones(String projectId, Map options) { + @VisibleForTesting + Response listZones(String projectId, String query) { + Map options = OptionParsers.parseListZonesOptions(query); Response response = checkListOptions(options); if (response != null) { return response; @@ -958,46 +830,43 @@ Response listZones(String projectId, Map options) { String pageToken = (String) options.get("pageToken"); Integer maxResults = options.get("maxResults") == null ? null : Integer.valueOf((String) options.get("maxResults")); - // matches will be included in the result if true - boolean listing = (pageToken == null || !containers.containsKey(pageToken)); - boolean sizeReached = false; // maximum result size was reached, we should not return more - boolean hasMorePages = false; // should next page token be included in the response? + boolean sizeReached = false; + boolean hasMorePages = false; LinkedList serializedZones = new LinkedList<>(); String lastZoneName = null; - for (ZoneContainer zoneContainer : containers.values()) { + ConcurrentNavigableMap fragment = + pageToken != null ? containers.tailMap(pageToken, false) : containers; + for (ZoneContainer zoneContainer : fragment.values()) { ManagedZone zone = zoneContainer.zone(); - if (listing) { - if (dnsName == null || zone.getDnsName().equals(dnsName)) { - if (sizeReached) { - // we do not add this, just note that there would be more and there should be a token - hasMorePages = true; - break; - } else { - try { - lastZoneName = zone.getName(); - serializedZones.addLast(jsonFactory.toString( - OptionParsersAndExtractors.extractFields(zone, fields))); - } catch (IOException e) { - return Error.INTERNAL_ERROR.response(String.format( - "Error when serializing managed zone %s in project %s", zone.getName(), - projectId)); - } + if (dnsName == null || zone.getDnsName().equals(dnsName)) { + if (sizeReached) { + // we do not add this, just note that there would be more and there should be a token + hasMorePages = true; + break; + } else { + try { + lastZoneName = zone.getName(); + serializedZones.addLast(jsonFactory.toString( + OptionParsers.extractFields(zone, fields))); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing managed zone %s in project %s", lastZoneName, projectId)); } } } - // either we are listing already, or we check if we should start in the next iteration - listing = zone.getName().equals(pageToken) || listing; - sizeReached = (maxResults != null) && maxResults.equals(serializedZones.size()); + sizeReached = maxResults != null && maxResults.equals(serializedZones.size()); } boolean includePageToken = - hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("nextPageToken")); + hasMorePages && (fields == null || Arrays.asList(fields).contains("nextPageToken")); return toListResponse(serializedZones, "managedZones", lastZoneName, includePageToken); } /** - * Lists DNS records for a zone. Next page token is ID of the last record listed. + * Lists DNS records for a zone. Next page token is the ID of the last record listed. */ - Response listDnsRecords(String projectId, String zoneName, Map options) { + @VisibleForTesting + Response listDnsRecords(String projectId, String zoneName, String query) { + Map options = OptionParsers.parseListDnsRecordsOptions(query); Response response = checkListOptions(options); if (response != null) { return response; @@ -1007,52 +876,51 @@ Response listDnsRecords(String projectId, String zoneName, Map o return Error.NOT_FOUND.response(String.format( "The 'parameters.managedZone' resource named '%s' does not exist.", zoneName)); } - List dnsRecords = zoneContainer.dnsRecords().get(zoneName); + ImmutableSortedMap dnsRecords = zoneContainer.dnsRecords().get(); String[] fields = (String[]) options.get("fields"); String name = (String) options.get("name"); String type = (String) options.get("type"); String pageToken = (String) options.get("pageToken"); + ImmutableSortedMap fragment = + pageToken != null ? dnsRecords.tailMap(pageToken, false) : dnsRecords; Integer maxResults = options.get("maxResults") == null ? null : Integer.valueOf((String) options.get("maxResults")); - boolean listing = (pageToken == null); // matches will be included in the result if true - boolean sizeReached = false; // maximum result size was reached, we should not return more - boolean hasMorePages = false; // should next page token be included in the response? + boolean sizeReached = false; + boolean hasMorePages = false; LinkedList serializedRrsets = new LinkedList<>(); String lastRecordId = null; - for (RrsetWrapper recordWrapper : dnsRecords) { - ResourceRecordSet record = recordWrapper.rrset(); - if (listing) { - if (matchesCriteria(record, name, type)) { - if (sizeReached) { - // we do not add this, just note that there would be more and there should be a token - hasMorePages = true; - break; - } else { - lastRecordId = recordWrapper.id(); - try { - serializedRrsets.addLast(jsonFactory.toString( - OptionParsersAndExtractors.extractFields(record, fields))); - } catch (IOException e) { - return Error.INTERNAL_ERROR.response(String.format( - "Error when serializing resource record set in managed zone %s in project %s", - zoneName, projectId)); - } + for (String recordId : fragment.keySet()) { + ResourceRecordSet record = fragment.get(recordId); + if (matchesCriteria(record, name, type)) { + if (sizeReached) { + // we do not add this, just note that there would be more and there should be a token + hasMorePages = true; + break; + } else { + lastRecordId = recordId; + try { + serializedRrsets.addLast(jsonFactory.toString( + OptionParsers.extractFields(record, fields))); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing resource record set in managed zone %s in project %s", + zoneName, projectId)); } } } - // either we are listing already, or we check if we should start in the next iteration - listing = recordWrapper.id().equals(pageToken) || listing; - sizeReached = (maxResults != null) && maxResults.equals(serializedRrsets.size()); + sizeReached = maxResults != null && maxResults.equals(serializedRrsets.size()); } boolean includePageToken = - hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("nextPageToken")); + hasMorePages && (fields == null || Arrays.asList(fields).contains("nextPageToken")); return toListResponse(serializedRrsets, "rrsets", lastRecordId, includePageToken); } /** - * Lists changes. Next page token is ID of the last change listed. + * Lists changes. Next page token is the ID of the last change listed. */ - Response listChanges(String projectId, String zoneName, Map options) { + @VisibleForTesting + Response listChanges(String projectId, String zoneName, String query) { + Map options = OptionParsers.parseListChangesOptions(query); Response response = checkListOptions(options); if (response != null) { return response; @@ -1063,7 +931,7 @@ Response listChanges(String projectId, String zoneName, Map opti "The 'parameters.managedZone' resource named '%s' does not exist", zoneName)); } // take a sorted snapshot of the current change list - TreeMap changes = new TreeMap<>(); + NavigableMap changes = new TreeMap<>(); for (Change c : zoneContainer.changes()) { if (c.getId() != null) { changes.put(Integer.valueOf(c.getId()), c); @@ -1074,51 +942,54 @@ Response listChanges(String projectId, String zoneName, Map opti String pageToken = (String) options.get("pageToken"); Integer maxResults = options.get("maxResults") == null ? null : Integer.valueOf((String) options.get("maxResults")); - // we are not reading sort by as it the only key is the change sequence + // as the only supported field is change sequence, we are not reading sortBy NavigableSet keys; if ("descending".equals(sortOrder)) { keys = changes.descendingKeySet(); } else { keys = changes.navigableKeySet(); } - boolean listing = (pageToken == null); // matches will be included in the result if true - boolean sizeReached = false; // maximum result size was reached, we should not return more - boolean hasMorePages = false; // should next page token be included in the response? + Integer from = null; + try { + from = Integer.valueOf(pageToken); + } catch (NumberFormatException ex) { + // ignore page token + } + keys = from != null ? keys.tailSet(from, false) : keys; + NavigableMap fragment = + from != null && changes.containsKey(from) ? changes.tailMap(from, false) : changes; + boolean sizeReached = false; + boolean hasMorePages = false; LinkedList serializedResults = new LinkedList<>(); String lastChangeId = null; for (Integer key : keys) { - Change change = changes.get(key); - if (listing) { - if (sizeReached) { - // we do not add this, just note that there would be more and there should be a token - hasMorePages = true; - break; - } else { - lastChangeId = change.getId(); - try { - serializedResults.addLast(jsonFactory.toString( - OptionParsersAndExtractors.extractFields(change, fields))); - } catch (IOException e) { - return Error.INTERNAL_ERROR.response(String.format( - "Error when serializing change %s in managed zone %s in project %s", - change.getId(), zoneName, projectId)); - } + Change change = fragment.get(key); + if (sizeReached) { + // we do not add this, just note that there would be more and there should be a token + hasMorePages = true; + break; + } else { + lastChangeId = change.getId(); + try { + serializedResults.addLast(jsonFactory.toString( + OptionParsers.extractFields(change, fields))); + } catch (IOException e) { + return Error.INTERNAL_ERROR.response(String.format( + "Error when serializing change %s in managed zone %s in project %s", + lastChangeId, zoneName, projectId)); } } - - // either we are listing already, or we check if we should start in the next iteration - listing = change.getId().equals(pageToken) || listing; - sizeReached = (maxResults != null) && maxResults.equals(serializedResults.size()); + sizeReached = maxResults != null && maxResults.equals(serializedResults.size()); } boolean includePageToken = - hasMorePages && (fields == null || ImmutableList.copyOf(fields).contains("nextPageToken")); + hasMorePages && (fields == null || Arrays.asList(fields).contains("nextPageToken")); return toListResponse(serializedResults, "changes", lastChangeId, includePageToken); } /** * Validates a zone to be created. */ - static Response checkZone(ManagedZone zone) { + private static Response checkZone(ManagedZone zone) { if (zone.getName() == null) { return Error.REQUIRED.response( "The 'entity.managedZone.name' parameter is required but was missing."); @@ -1138,7 +1009,8 @@ static Response checkZone(ManagedZone zone) { } catch (NumberFormatException ex) { // expected } - if (zone.getName().isEmpty()) { + if (zone.getName().isEmpty() || zone.getName().length() > 32 + || !ZONE_NAME_RE.matcher(zone.getName()).matches()) { return Error.INVALID.response( String.format("Invalid value for 'entity.managedZone.name': '%s'", zone.getName())); } @@ -1146,9 +1018,7 @@ static Response checkZone(ManagedZone zone) { return Error.INVALID.response( String.format("Invalid value for 'entity.managedZone.dnsName': '%s'", zone.getDnsName())); } - TreeSet forbidden = Sets.newTreeSet( - ImmutableList.of("google.com.", "com.", "example.com.", "net.", "org.")); - if (forbidden.contains(zone.getDnsName())) { + if (FORBIDDEN.contains(zone.getDnsName())) { return Error.NOT_AVAILABLE.response(String.format( "The '%s' managed zone is not available to be created.", zone.getDnsName())); } @@ -1158,12 +1028,10 @@ static Response checkZone(ManagedZone zone) { /** * Validates a change to be created. */ + @VisibleForTesting static Response checkChange(Change change, ZoneContainer zone) { - checkNotNull(zone); - if ((change.getDeletions() != null && change.getDeletions().size() > 0) - || (change.getAdditions() != null && change.getAdditions().size() > 0)) { - // ok, this is what we want - } else { + if ((change.getDeletions() == null || change.getDeletions().size() <= 0) + && (change.getAdditions() == null || change.getAdditions().size() <= 0)) { return Error.REQUIRED.response("The 'entity.change' parameter is required but was missing."); } if (change.getAdditions() != null) { @@ -1186,7 +1054,7 @@ static Response checkChange(Change change, ZoneContainer zone) { counter++; } } - return additionsMeetDeletions(change.getAdditions(), change.getDeletions(), zone); + return checkAdditionsDeletions(change.getAdditions(), change.getDeletions(), zone); // null if everything is ok } @@ -1197,6 +1065,7 @@ static Response checkChange(Change change, ZoneContainer zone) { * @param index the index or addition or deletion in the list * @param zone the zone that this change is applied to */ + @VisibleForTesting static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int index, String type) { if (rrset.getName() == null || !rrset.getName().endsWith(zone.zone().getDnsName())) { return Error.INVALID.response(String.format( @@ -1226,8 +1095,7 @@ static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int inde if ("deletions".equals(type)) { // check that deletion has a match by name and type boolean found = false; - for (RrsetWrapper rrsetWrapper : zone.dnsRecords().get(zone.zone().getName())) { - ResourceRecordSet wrappedRrset = rrsetWrapper.rrset(); + for (ResourceRecordSet wrappedRrset : zone.dnsRecords().get().values()) { if (rrset.getName().equals(wrappedRrset.getName()) && rrset.getType().equals(wrappedRrset.getType())) { found = true; @@ -1241,7 +1109,7 @@ static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int inde } // if found, we still need an exact match if ("deletions".equals(type) - && !zone.dnsRecords().get(zone.zone().getName()).contains(new RrsetWrapper(rrset))) { + && !zone.dnsRecords().get().containsValue(rrset)) { // such a record does not exist return Error.CONDITION_NOT_MET.response(String.format( "Precondition not met for 'entity.change.deletions[%s]", index)); @@ -1251,24 +1119,22 @@ static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int inde } /** - * Checks that for each record that already exists, we have a matching deletion. Furthermore, - * check that mandatory SOA and NS records stay. + * Checks against duplicate additions (for each record to be added that already exists, we must + * have a matching deletion. Furthermore, check that mandatory SOA and NS records stay. */ - static Response additionsMeetDeletions(List additions, + static Response checkAdditionsDeletions(List additions, List deletions, ZoneContainer zone) { if (additions != null) { int index = 0; for (ResourceRecordSet rrset : additions) { - for (RrsetWrapper wrapper : zone.dnsRecords().get(zone.zone().getName())) { - ResourceRecordSet wrappedRrset = wrapper.rrset(); + for (ResourceRecordSet wrappedRrset : zone.dnsRecords().get().values()) { if (rrset.getName().equals(wrappedRrset.getName()) - && rrset.getType().equals(wrappedRrset.getType())) { - // such a record exist and we must have a deletion - if (deletions == null || !deletions.contains(wrappedRrset)) { - return Error.ALREADY_EXISTS.response(String.format( - "The 'entity.change.additions[%s]' resource named '%s (%s)' already exists.", - index, rrset.getName(), rrset.getType())); - } + && rrset.getType().equals(wrappedRrset.getType()) + // such a record exist and we must have a deletion + && (deletions == null || !deletions.contains(wrappedRrset))) { + return Error.ALREADY_EXISTS.response(String.format( + "The 'entity.change.additions[%s]' resource named '%s (%s)' already exists.", + index, rrset.getName(), rrset.getType())); } } if (rrset.getType().equals("SOA") && findByNameAndType(deletions, null, "SOA") == null) { @@ -1323,44 +1189,11 @@ private static ResourceRecordSet findByNameAndType(Iterable r * We only provide the most basic validation for A and AAAA records. */ static boolean checkRrData(String data, String type) { - // todo add validation for other records - String[] tokens; switch (type) { case "A": - tokens = data.split("\\."); - if (tokens.length != 4) { - return false; - } - for (String token : tokens) { - try { - Integer number = Integer.valueOf(token); - if (number < 0 || number > 255) { - return false; - } - } catch (NumberFormatException ex) { - return false; - } - } - return true; + return !data.contains(":") && isInetAddress(data); case "AAAA": - tokens = data.split(":", -1); - if (tokens.length != 8) { - return false; - } - for (String token : tokens) { - try { - if (!token.isEmpty()) { - // empty is ok - Long number = Long.parseLong(token, 16); - if (number < 0 || number > 0xFFFF) { - return false; - } - } - } catch (NumberFormatException ex) { - return false; - } - } - return true; + return data.contains(":") && isInetAddress(data); default: return true; } @@ -1369,11 +1202,12 @@ static boolean checkRrData(String data, String type) { /** * Check supplied listing options. */ + @VisibleForTesting static Response checkListOptions(Map options) { // for general listing String maxResultsString = (String) options.get("maxResults"); if (maxResultsString != null) { - Integer maxResults = null; + Integer maxResults; try { maxResults = Integer.valueOf(maxResultsString); } catch (NumberFormatException ex) { @@ -1386,24 +1220,21 @@ static Response checkListOptions(Map options) { } } String dnsName = (String) options.get("dnsName"); - if (dnsName != null) { - if (!dnsName.endsWith(".")) { - return Error.INVALID.response(String.format( - "Invalid value for 'parameters.dnsName': '%s'", dnsName)); - } + if (dnsName != null && !dnsName.endsWith(".")) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.dnsName': '%s'", dnsName)); } // for listing dns records, name must be fully qualified String name = (String) options.get("name"); - if (name != null) { - if (!name.endsWith(".")) { - return Error.INVALID.response(String.format( - "Invalid value for 'parameters.name': '%s'", name)); - } + if (name != null && !name.endsWith(".")) { + return Error.INVALID.response(String.format( + "Invalid value for 'parameters.name': '%s'", name)); } String type = (String) options.get("type"); // must be provided with name if (type != null) { if (name == null) { - return Error.INVALID.response("Invalid value for 'parameters.name': ''"); + return Error.INVALID.response("Invalid value for 'parameters.name': '' " + + "(name must be specified if type is specified)"); } if (!TYPES.contains(type)) { return Error.INVALID.response(String.format( diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java similarity index 80% rename from gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java index 26759f7e3ccc..ecd7e8179efe 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/testing/OptionParsersAndExtractors.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.testing; +package com.google.gcloud.dns.testing; import com.google.api.services.dns.model.Change; import com.google.api.services.dns.model.ManagedZone; @@ -27,12 +27,8 @@ /** * Utility helpers for LocalDnsHelper. */ -class OptionParsersAndExtractors { +class OptionParsers { - /** - * Makes a map of list options. Expects query to be only query part of the url (i.e., what follows - * the '?'). - */ static Map parseListZonesOptions(String query) { Map options = new HashMap<>(); if (query != null) { @@ -41,20 +37,15 @@ static Map parseListZonesOptions(String query) { String[] argEntry = arg.split("="); switch (argEntry[0]) { case "fields": - // List fields are in the form "managedZones(field1, field2, ...)" + // List fields are in the form "managedZones(field1, field2, ...),nextPageToken" String replaced = argEntry[1].replace("managedZones(", ","); replaced = replaced.replace(")", ","); // we will get empty strings, but it does not matter, they will be ignored - options.put( - "fields", - replaced.split(",")); + options.put("fields", replaced.split(",")); break; case "dnsName": options.put("dnsName", argEntry[1]); break; - case "nextPageToken": - options.put("nextPageToken", argEntry[1]); - break; case "pageToken": options.put("pageToken", argEntry[1]); break; @@ -70,10 +61,6 @@ static Map parseListZonesOptions(String query) { return options; } - /** - * Makes a map of list options. Expects query to be only query part of the url (i.e., what follows - * the '?'). This format is common for all of zone, change and project. - */ static String[] parseGetOptions(String query) { if (query != null) { String[] args = query.split("&"); @@ -85,14 +72,11 @@ static String[] parseGetOptions(String query) { } } } - return null; + return new String[0]; } - /** - * Extracts only request fields. - */ - static ManagedZone extractFields(ManagedZone fullZone, String[] fields) { - if (fields == null) { + static ManagedZone extractFields(ManagedZone fullZone, String... fields) { + if (fields == null || fields.length == 0) { return fullZone; } ManagedZone managedZone = new ManagedZone(); @@ -126,22 +110,17 @@ static ManagedZone extractFields(ManagedZone fullZone, String[] fields) { return managedZone; } - /** - * Extracts only request fields. - */ - static Change extractFields(Change fullChange, String[] fields) { - if (fields == null) { + static Change extractFields(Change fullChange, String... fields) { + if (fields == null || fields.length == 0) { return fullChange; } Change change = new Change(); for (String field : fields) { switch (field) { case "additions": - // todo the fragmentation is ignored here as our api does not support it change.setAdditions(fullChange.getAdditions()); break; case "deletions": - // todo the fragmentation is ignored here as our api does not support it change.setDeletions(fullChange.getDeletions()); break; case "id": @@ -160,11 +139,8 @@ static Change extractFields(Change fullChange, String[] fields) { return change; } - /** - * Extracts only request fields. - */ - static Project extractFields(Project fullProject, String[] fields) { - if (fields == null) { + static Project extractFields(Project fullProject, String... fields) { + if (fields == null || fields.length == 0) { return fullProject; } Project project = new Project(); @@ -186,11 +162,8 @@ static Project extractFields(Project fullProject, String[] fields) { return project; } - /** - * Extracts only request fields. - */ - static ResourceRecordSet extractFields(ResourceRecordSet fullRecord, String[] fields) { - if (fields == null) { + static ResourceRecordSet extractFields(ResourceRecordSet fullRecord, String... fields) { + if (fields == null || fields.length == 0) { return fullRecord; } ResourceRecordSet record = new ResourceRecordSet(); @@ -223,16 +196,9 @@ static Map parseListChangesOptions(String query) { String[] argEntry = arg.split("="); switch (argEntry[0]) { case "fields": - // todo we do not support fragmentation in deletions and additions in the library String replaced = argEntry[1].replace("changes(", ",").replace(")", ","); options.put("fields", replaced.split(",")); // empty strings will be ignored break; - case "name": - options.put("name", argEntry[1]); - break; - case "nextPageToken": - options.put("nextPageToken", argEntry[1]); - break; case "pageToken": options.put("pageToken", argEntry[1]); break; @@ -275,9 +241,6 @@ static Map parseListDnsRecordsOptions(String query) { case "pageToken": options.put("pageToken", argEntry[1]); break; - case "nextPageToken": - options.put("nextPageToken", argEntry[1]); - break; case "maxResults": // parsing to int is done while handling options.put("maxResults", argEntry[1]); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java index b72a21445a80..1df0a8a2f831 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java @@ -162,9 +162,9 @@ public Change getChangeRequest(String zoneName, String changeRequestId, Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); - private static final DnsRpc RPC = - new DefaultDnsRpc(LOCAL_DNS_HELPER.options()); + private static final DnsRpc RPC = new DefaultDnsRpc(LOCAL_DNS_HELPER.options()); private static final String REAL_PROJECT_ID = LOCAL_DNS_HELPER.options().projectId(); private Map optionsMap; - private ManagedZone minimalZone = new ManagedZone(); // to be adjusted as needed - @BeforeClass public static void before() { - RRSET1.setName(DNS_NAME); - RRSET1.setType(RRSET_TYPE); - RRSET1.setRrdatas(ImmutableList.of("1.1.1.1")); ZONE1.setName(ZONE_NAME1); ZONE1.setDescription(""); ZONE1.setDnsName(DNS_NAME); - ZONE1.setNameServerSet("somenameserveset"); + ZONE1.setNameServerSet("somenameserverset"); ZONE2.setName(ZONE_NAME2); ZONE2.setDescription(""); ZONE2.setDnsName(DNS_NAME); - ZONE2.setNameServerSet("somenameserveset"); + ZONE2.setNameServerSet("somenameserverset"); + RRSET1.setName(DNS_NAME); + RRSET1.setType(RRSET_TYPE); + RRSET1.setRrdatas(ImmutableList.of("1.1.1.1")); RRSET2.setName(DNS_NAME); RRSET2.setType(RRSET_TYPE); + RRSET2.setRrdatas(ImmutableList.of("123.132.153.156")); RRSET_KEEP.setName(DNS_NAME); RRSET_KEEP.setType("MX"); RRSET_KEEP.setRrdatas(ImmutableList.of("255.255.255.254")); - RRSET2.setRrdatas(ImmutableList.of("123.132.153.156")); CHANGE1.setAdditions(ImmutableList.of(RRSET1, RRSET2)); CHANGE2.setDeletions(ImmutableList.of(RRSET2)); CHANGE_KEEP.setAdditions(ImmutableList.of(RRSET_KEEP)); @@ -98,17 +99,13 @@ public static void before() { LOCAL_DNS_HELPER.start(); } + @Rule + public Timeout globalTimeout = Timeout.seconds(60); + @Before public void setUp() { resetProjects(); optionsMap = new HashMap<>(); - minimalZone = copyZone(ZONE1); - } - - private static void resetProjects() { - for (String project : LOCAL_DNS_HELPER.projects().keySet()) { - LOCAL_DNS_HELPER.projects().remove(project); - } } @AfterClass @@ -116,279 +113,55 @@ public static void after() { LOCAL_DNS_HELPER.stop(); } - @Test - public void testMatchesCriteria() { - assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), RRSET1.getType())); - assertFalse(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), "anothertype")); - assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, null, RRSET1.getType())); - assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), null)); - assertFalse(LocalDnsHelper.matchesCriteria(RRSET1, "anothername", RRSET1.getType())); - } - - @Test - public void testGetUniqueId() { - assertNotNull(LocalDnsHelper.getUniqueId(Lists.newLinkedList())); - } - - @Test - public void testFindProject() { - assertEquals(0, LOCAL_DNS_HELPER.projects().size()); - LocalDnsHelper.ProjectContainer project = LOCAL_DNS_HELPER.findProject(PROJECT_ID1); - assertNotNull(project); - assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID1)); - assertNotNull(LOCAL_DNS_HELPER.findProject(PROJECT_ID2)); - assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID2)); - assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID1)); - assertNotNull(project.zones()); - assertEquals(0, project.zones().size()); - assertNotNull(project.project()); - assertNotNull(project.project().getQuota()); + private static void resetProjects() { + for (String project : LOCAL_DNS_HELPER.projects().keySet()) { + LOCAL_DNS_HELPER.projects().remove(project); + } } - @Test - public void testCreateAndFindZone() { - LocalDnsHelper.ZoneContainer zone1 = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1); - assertTrue(LOCAL_DNS_HELPER.projects().containsKey(PROJECT_ID1)); - assertNull(zone1); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); // we do not care about options - zone1 = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName()); - assertNotNull(zone1); - // cannot call equals because id and timestamp got assigned - assertEquals(ZONE_NAME1, zone1.zone().getName()); - assertNotNull(zone1.changes()); - assertTrue(zone1.changes().isEmpty()); - assertNotNull(zone1.dnsRecords()); - assertEquals(2, zone1.dnsRecords().get(ZONE_NAME1).size()); // default SOA and NS - LOCAL_DNS_HELPER.createZone(PROJECT_ID2, ZONE1, null); // project does not exits yet - assertEquals(ZONE1.getName(), - LOCAL_DNS_HELPER.findZone(PROJECT_ID2, ZONE_NAME1).zone().getName()); + private static void assertEqChangesIgnoreStatus(Change expected, Change actual) { + assertEquals(expected.getAdditions(), actual.getAdditions()); + assertEquals(expected.getDeletions(), actual.getDeletions()); + assertEquals(expected.getId(), actual.getId()); + assertEquals(expected.getStartTime(), actual.getStartTime()); } @Test - public void testCreateAndFindZoneUsingRpc() { - // zone does not exist yet - ManagedZone zone1 = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); - assertTrue(LOCAL_DNS_HELPER.projects().containsKey(REAL_PROJECT_ID)); // check internal state - assertNull(zone1); - // create zone - ManagedZone createdZone = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - assertEquals(ZONE1.getName(), createdZone.getName()); - assertEquals(ZONE1.getDescription(), createdZone.getDescription()); - assertEquals(ZONE1.getDnsName(), createdZone.getDnsName()); - assertEquals(4, createdZone.getNameServers().size()); - // get the same zone zone - ManagedZone zone = RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS); - assertEquals(createdZone, zone); + public void testCreateZone() { + ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); // check that default records were created - DnsRpc.ListResult resourceRecordSetListResult + DnsRpc.ListResult listResult = RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS); - assertEquals(2, Lists.newLinkedList(resourceRecordSetListResult.results()).size()); - } - - @Test - public void testDeleteZone() { - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - LocalDnsHelper.Response response = LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE1.getName()); - assertEquals(204, response.code()); - // deleting non-existent zone - response = LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE1.getName()); - assertEquals(404, response.code()); - assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE2, null); - assertNotNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); - assertNotNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE2.getName())); - // delete in reverse order - response = LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE1.getName()); - assertEquals(204, response.code()); - assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); - assertNotNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE2.getName())); - LOCAL_DNS_HELPER.deleteZone(PROJECT_ID1, ZONE2.getName()); - assertEquals(204, response.code()); - assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE1.getName())); - assertNull(LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE2.getName())); - } - - @Test - public void testDeleteZoneUsingRpc() { - RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - assertTrue(RPC.deleteZone(ZONE1.getName())); - assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); - // deleting non-existent zone - assertFalse(RPC.deleteZone(ZONE1.getName())); - assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); - RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - RPC.create(ZONE2, EMPTY_RPC_OPTIONS); - assertNotNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); - assertNotNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); - // delete in reverse order - assertTrue(RPC.deleteZone(ZONE1.getName())); - assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); - assertNotNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); - assertTrue(RPC.deleteZone(ZONE2.getName())); - assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); - assertNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); - } - - @Test - public void testCreateAndApplyChange() { - LocalDnsHelper localDnsThreaded = LocalDnsHelper.create(5 * 1000L); // using threads here - localDnsThreaded.createZone(PROJECT_ID1, ZONE1, null); - assertNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - LocalDnsHelper.Response response - = localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add - assertEquals(200, response.code()); - assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - assertNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); - localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add - response = localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); // add - assertEquals(200, response.code()); - assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); - localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); // delete - assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("1")); - assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("2")); - assertNotNull(localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).findChange("3")); - localDnsThreaded.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE_KEEP, null); // id is "4" - // check execution - Change change = localDnsThreaded.findChange(PROJECT_ID1, ZONE_NAME1, "4"); - for (int i = 0; i < 10 && !change.getStatus().equals("done"); i++) { - // change has not been finished yet; wait at most 20 seconds - // it takes 5 seconds for the thread to kick in in the first place - try { - Thread.sleep(2 * 1000); - } catch (InterruptedException e) { - fail("Test was interrupted"); - } + ImmutableList defaultTypes = ImmutableList.of("SOA", "NS"); + Iterator iterator = listResult.results().iterator(); + assertTrue(defaultTypes.contains(iterator.next().getType())); + assertTrue(defaultTypes.contains(iterator.next().getType())); + assertFalse(iterator.hasNext()); + assertEquals(created, LOCAL_DNS_HELPER.findZone(REAL_PROJECT_ID, ZONE1.getName()).zone()); + ManagedZone zone = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); + assertEquals(created, zone); + try { + RPC.create(null, EMPTY_RPC_OPTIONS); + fail("Zone cannot be null"); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("entity.managedZone")); } - assertEquals("done", change.getStatus()); - List list = - localDnsThreaded.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); - assertTrue(list.contains(new LocalDnsHelper.RrsetWrapper(RRSET_KEEP))); - localDnsThreaded.stop(); - } - - @Test - public void testCreateAndApplyChangeUsingRpc() { - // not using threads - RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - assertNull(RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); - //add - Change createdChange = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); - assertEquals(createdChange.getAdditions(), CHANGE1.getAdditions()); - assertEquals(createdChange.getDeletions(), CHANGE1.getDeletions()); - assertNotNull(createdChange.getStartTime()); - assertEquals("1", createdChange.getId()); - Change retrievedChange = RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS); - assertEquals(createdChange, retrievedChange); - assertNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + // create zone twice try { - Change anotherChange = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + fail("Zone already exists."); } catch (DnsException ex) { + // expected assertEquals(409, ex.code()); + assertTrue(ex.getMessage().contains("already exists")); } - assertNotNull(RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); - assertNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); - // delete - RPC.applyChangeRequest(ZONE1.getName(), CHANGE2, EMPTY_RPC_OPTIONS); - assertNotNull(RPC.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); - assertNotNull(RPC.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); - Change last = RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); - assertEquals("done", last.getStatus()); - // todo(mderka) replace with real call - List list = - LOCAL_DNS_HELPER.findZone(REAL_PROJECT_ID, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); - assertTrue(list.contains(new LocalDnsHelper.RrsetWrapper(RRSET_KEEP))); - Iterable results = - RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); - boolean ok = false; - for (ResourceRecordSet dnsRecord : results) { - if (dnsRecord.getName().equals(RRSET_KEEP.getName()) - && dnsRecord.getType().equals(RRSET_KEEP.getType())) { - ok = true; - } - } - assertTrue(ok); - } - - @Test - public void testFindChange() { - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - Change change = LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "somerandomchange"); - assertNull(change); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE1.getName(), CHANGE1, null); - // changes are sequential so we should find ID 1 - assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "1")); - // add another - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); - assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "1")); - assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "2")); - // try to find non-existent change - assertNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE1.getName(), "3")); - // try to find a change in yet non-existent project - assertNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID2, ZONE1.getName(), "3")); - } - - @Test - public void testRandomNameServers() { - assertEquals(4, LocalDnsHelper.randomNameservers().size()); - assertEquals(4, LocalDnsHelper.randomNameservers().size()); - assertEquals(4, LocalDnsHelper.randomNameservers().size()); - assertEquals(4, LocalDnsHelper.randomNameservers().size()); - } - - @Test - public void testGetProject() { - // only interested in no exceptions and non-null response here - assertNotNull(LOCAL_DNS_HELPER.getProject(PROJECT_ID1, null)); - assertNotNull(LOCAL_DNS_HELPER.getProject(PROJECT_ID2, null)); - Project project = RPC.getProject(EMPTY_RPC_OPTIONS); - assertNotNull(project.getQuota()); - assertEquals(REAL_PROJECT_ID, project.getId()); - // fields options - Map options = new HashMap<>(); - options.put(DnsRpc.Option.FIELDS, "number"); - project = RPC.getProject(options); - assertNull(project.getId()); - assertNotNull(project.getNumber()); - assertNull(project.getQuota()); - options.put(DnsRpc.Option.FIELDS, "id"); - project = RPC.getProject(options); - assertNotNull(project.getId()); - assertNull(project.getNumber()); - assertNull(project.getQuota()); - options.put(DnsRpc.Option.FIELDS, "quota"); - project = RPC.getProject(options); - assertNull(project.getId()); - assertNull(project.getNumber()); - assertNotNull(project.getQuota()); - } - - @Test - public void testGetZone() { - // non-existent - LocalDnsHelper.Response response = LOCAL_DNS_HELPER.getZone(PROJECT_ID1, ZONE_NAME1, null); - assertEquals(404, response.code()); - assertTrue(response.body().contains("does not exist")); - // existent - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - response = LOCAL_DNS_HELPER.getZone(PROJECT_ID1, ZONE1.getName(), null); - assertEquals(200, response.code()); - } - - @Test - public void testGetZoneUsingRpc() { - // non-existent - assertNull(RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS)); - // existent - ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - ManagedZone zone = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); - assertEquals(created, zone); - assertEquals(ZONE1.getName(), zone.getName()); // field options + resetProjects(); Map options = new HashMap<>(); options.put(DnsRpc.Option.FIELDS, "id"); - zone = RPC.getZone(ZONE1.getName(), options); + zone = RPC.create(ZONE1, options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -396,8 +169,9 @@ public void testGetZoneUsingRpc() { assertNull(zone.getNameServers()); assertNull(zone.getNameServerSet()); assertNotNull(zone.getId()); + resetProjects(); options.put(DnsRpc.Option.FIELDS, "creationTime"); - zone = RPC.getZone(ZONE1.getName(), options); + zone = RPC.create(ZONE1, options); assertNotNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -406,7 +180,8 @@ public void testGetZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "dnsName"); - zone = RPC.getZone(ZONE1.getName(), options); + resetProjects(); + zone = RPC.create(ZONE1, options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNotNull(zone.getDnsName()); @@ -415,7 +190,8 @@ public void testGetZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "description"); - zone = RPC.getZone(ZONE1.getName(), options); + resetProjects(); + zone = RPC.create(ZONE1, options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -424,7 +200,8 @@ public void testGetZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "nameServers"); - zone = RPC.getZone(ZONE1.getName(), options); + resetProjects(); + zone = RPC.create(ZONE1, options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -433,7 +210,8 @@ public void testGetZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "nameServerSet"); - zone = RPC.getZone(ZONE1.getName(), options); + resetProjects(); + zone = RPC.create(ZONE1, options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -443,7 +221,8 @@ public void testGetZoneUsingRpc() { assertNull(zone.getId()); // several combined options.put(DnsRpc.Option.FIELDS, "nameServerSet,description,id,name"); - zone = RPC.getZone(ZONE1.getName(), options); + resetProjects(); + zone = RPC.create(ZONE1, options); assertNull(zone.getCreationTime()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); @@ -454,50 +233,18 @@ public void testGetZoneUsingRpc() { } @Test - public void testCreateZone() { - // only interested in no exceptions and non-null response here - LocalDnsHelper.Response response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - assertEquals(200, response.code()); - assertEquals(1, LOCAL_DNS_HELPER.projects().get(PROJECT_ID1).zones().size()); - try { - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, null, null); - fail("Zone cannot be null"); - } catch (NullPointerException ex) { - // expected - } - // create zone twice - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - assertEquals(409, response.code()); - assertTrue(response.body().contains("already exists")); - } - - @Test - public void testCreateZoneUsingRpc() { + public void testGetZone() { + // non-existent + assertNull(RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS)); + // existent ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - assertEquals(created, LOCAL_DNS_HELPER.findZone(REAL_PROJECT_ID, ZONE1.getName()).zone()); ManagedZone zone = RPC.getZone(ZONE_NAME1, EMPTY_RPC_OPTIONS); assertEquals(created, zone); - try { - RPC.create(null, EMPTY_RPC_OPTIONS); - fail("Zone cannot be null"); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - assertTrue(ex.getMessage().contains("entity.managedZone")); - } - // create zone twice - try { - RPC.create(ZONE1, EMPTY_RPC_OPTIONS); - } catch (DnsException ex) { - // expected - assertEquals(409, ex.code()); - assertTrue(ex.getMessage().contains("already exists")); - } + assertEquals(ZONE1.getName(), zone.getName()); // field options - resetProjects(); Map options = new HashMap<>(); options.put(DnsRpc.Option.FIELDS, "id"); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -505,9 +252,8 @@ public void testCreateZoneUsingRpc() { assertNull(zone.getNameServers()); assertNull(zone.getNameServerSet()); assertNotNull(zone.getId()); - resetProjects(); options.put(DnsRpc.Option.FIELDS, "creationTime"); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNotNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -516,8 +262,7 @@ public void testCreateZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "dnsName"); - resetProjects(); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNotNull(zone.getDnsName()); @@ -526,8 +271,7 @@ public void testCreateZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "description"); - resetProjects(); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -536,8 +280,7 @@ public void testCreateZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "nameServers"); - resetProjects(); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -546,8 +289,7 @@ public void testCreateZoneUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "nameServerSet"); - resetProjects(); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -557,8 +299,7 @@ public void testCreateZoneUsingRpc() { assertNull(zone.getId()); // several combined options.put(DnsRpc.Option.FIELDS, "nameServerSet,description,id,name"); - resetProjects(); - zone = RPC.create(ZONE1, options); + zone = RPC.getZone(ZONE1.getName(), options); assertNull(zone.getCreationTime()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); @@ -568,25 +309,144 @@ public void testCreateZoneUsingRpc() { assertNotNull(zone.getId()); } + @Test + public void testDeleteZone() { + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + assertTrue(RPC.deleteZone(ZONE1.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + // deleting non-existent zone + assertFalse(RPC.deleteZone(ZONE1.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + RPC.create(ZONE2, EMPTY_RPC_OPTIONS); + assertNotNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + assertNotNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); + // delete in reverse order + assertTrue(RPC.deleteZone(ZONE1.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + assertNotNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); + assertTrue(RPC.deleteZone(ZONE2.getName())); + assertNull(RPC.getZone(ZONE1.getName(), EMPTY_RPC_OPTIONS)); + assertNull(RPC.getZone(ZONE2.getName(), EMPTY_RPC_OPTIONS)); + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + try { + RPC.deleteZone(ZONE1.getName()); + fail(); + } catch (DnsException ex) { + // expected + assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("not empty")); + } + } + + @Test + public void testCreateAndApplyChange() { + executeCreateAndApplyChangeTest(RPC); + } + + @Test + public void testCreateAndApplyChangeWithThreads() { + LocalDnsHelper localDnsThreaded = LocalDnsHelper.create(50L); + localDnsThreaded.start(); + DnsRpc rpc = new DefaultDnsRpc(localDnsThreaded.options()); + executeCreateAndApplyChangeTest(rpc); + localDnsThreaded.stop(); + } + + private static void waitForChangeToComplete(DnsRpc rpc, String zoneName, String changeId) { + while (true) { + Change change = rpc.getChangeRequest(zoneName, changeId, EMPTY_RPC_OPTIONS); + if ("done".equals(change.getStatus())) { + return; + } + try { + Thread.sleep(50L); + } catch (InterruptedException e) { + fail("Thread was interrupted while waiting for change processing."); + } + } + } + + private static void executeCreateAndApplyChangeTest(DnsRpc rpc) { + rpc.create(ZONE1, EMPTY_RPC_OPTIONS); + assertNull(rpc.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); + // add + Change createdChange = rpc.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + assertEquals(CHANGE1.getAdditions(), createdChange.getAdditions()); + assertEquals(CHANGE1.getDeletions(), createdChange.getDeletions()); + assertNotNull(createdChange.getStartTime()); + assertEquals("1", createdChange.getId()); + waitForChangeToComplete(rpc, ZONE1.getName(), "1"); // necessary for the following to return 409 + try { + rpc.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + fail(); + } catch (DnsException ex) { + assertEquals(409, ex.code()); + assertTrue(ex.getMessage().contains("already exists")); + } + assertNotNull(rpc.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); + assertNull(rpc.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + // delete + rpc.applyChangeRequest(ZONE1.getName(), CHANGE2, EMPTY_RPC_OPTIONS); + assertNotNull(rpc.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); + assertNotNull(rpc.getChangeRequest(ZONE1.getName(), "2", EMPTY_RPC_OPTIONS)); + waitForChangeToComplete(rpc, ZONE1.getName(), "2"); + rpc.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + waitForChangeToComplete(rpc, ZONE1.getName(), "3"); + Iterable results = + rpc.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + List defaults = ImmutableList.of("SOA", "NS"); + boolean rrsetKeep = false; + boolean rrset1 = false; + for (ResourceRecordSet dnsRecord : results) { + if (dnsRecord.getName().equals(RRSET_KEEP.getName()) + && dnsRecord.getType().equals(RRSET_KEEP.getType())) { + rrsetKeep = true; + } else if (dnsRecord.getName().equals(RRSET1.getName()) + && dnsRecord.getType().equals(RRSET1.getType())) { + rrset1 = true; + } else if (!defaults.contains(dnsRecord.getType())) { + fail(String.format("Record with type %s should not exist", dnsRecord.getType())); + } + } + assertTrue(rrset1); + assertTrue(rrsetKeep); + } + + @Test + public void testGetProject() { + // the projects are automatically created when getProject is called + assertNotNull(LOCAL_DNS_HELPER.getProject(PROJECT_ID1, null)); + assertNotNull(LOCAL_DNS_HELPER.getProject(PROJECT_ID2, null)); + Project project = RPC.getProject(EMPTY_RPC_OPTIONS); + assertNotNull(project.getQuota()); + assertEquals(REAL_PROJECT_ID, project.getId()); + // fields options + Map options = new HashMap<>(); + options.put(DnsRpc.Option.FIELDS, "number"); + project = RPC.getProject(options); + assertNull(project.getId()); + assertNotNull(project.getNumber()); + assertNull(project.getQuota()); + options.put(DnsRpc.Option.FIELDS, "id"); + project = RPC.getProject(options); + assertNotNull(project.getId()); + assertNull(project.getNumber()); + assertNull(project.getQuota()); + options.put(DnsRpc.Option.FIELDS, "quota"); + project = RPC.getProject(options); + assertNull(project.getId()); + assertNull(project.getNumber()); + assertNotNull(project.getQuota()); + } + @Test public void testCreateChange() { - // non-existent zone - LocalDnsHelper.Response response = - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - assertEquals(404, response.code()); - // existent zone - assertNotNull(LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null)); - assertNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE_NAME1, "1")); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - assertEquals(200, response.code()); - assertNotNull(LOCAL_DNS_HELPER.findChange(PROJECT_ID1, ZONE_NAME1, "1")); - } - - @Test - public void testCreateChangeUsingRpc() { // non-existent zone try { RPC.applyChangeRequest(ZONE_NAME1, CHANGE1, EMPTY_RPC_OPTIONS); + fail("Zone was not created yet."); } catch (DnsException ex) { assertEquals(404, ex.code()); } @@ -637,23 +497,6 @@ public void testCreateChangeUsingRpc() { @Test public void testGetChange() { - // existent - assertEquals(200, LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null).code()); - assertEquals(200, LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null).code()); - assertEquals(200, LOCAL_DNS_HELPER.getChange(PROJECT_ID1, ZONE_NAME1, "1", null).code()); - // non-existent - LocalDnsHelper.Response response = - LOCAL_DNS_HELPER.getChange(PROJECT_ID1, ZONE_NAME1, "2", null); - assertEquals(404, response.code()); - assertTrue(response.body().contains("parameters.changeId")); - // non-existent zone - response = LOCAL_DNS_HELPER.getChange(PROJECT_ID1, ZONE_NAME2, "1", null); - assertEquals(404, response.code()); - assertTrue(response.body().contains("parameters.managedZone")); - } - - @Test - public void testGetChangeUsingRpc() { // existent RPC.create(ZONE1, EMPTY_RPC_OPTIONS); Change created = RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); @@ -664,9 +507,11 @@ public void testGetChangeUsingRpc() { // non-existent zone try { RPC.getChangeRequest(ZONE_NAME2, "1", EMPTY_RPC_OPTIONS); + fail(); } catch (DnsException ex) { // expected assertEquals(404, ex.code()); + assertTrue(ex.getMessage().contains("managedZone")); } // field options RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); @@ -711,43 +556,6 @@ public void testGetChangeUsingRpc() { @Test public void testListZones() { - // only interested in no exceptions and non-null response here - optionsMap.put("dnsName", null); - optionsMap.put("fields", null); - optionsMap.put("pageToken", null); - optionsMap.put("maxResults", null); - LocalDnsHelper.Response response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - // some zones exists - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE2, null); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - // error in options - optionsMap.put("maxResults", "aaa"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "0"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "-1"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "15"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("dnsName", "aaa"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("dnsName", "aaa."); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - } - - @Test - public void testListZonesUsingRpc() { Iterable results = RPC.listZones(EMPTY_RPC_OPTIONS).results(); ImmutableList zones = ImmutableList.copyOf(results); assertEquals(0, zones.size()); @@ -767,32 +575,38 @@ public void testListZonesUsingRpc() { options.put(DnsRpc.Option.PAGE_SIZE, 0); try { RPC.listZones(options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.maxResults")); } options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, -1); try { RPC.listZones(options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.maxResults")); } // ok size options = new HashMap<>(); - options.put(DnsRpc.Option.PAGE_SIZE, 1); + options.put(DnsRpc.Option.PAGE_SIZE, 335); results = RPC.listZones(options).results(); zones = ImmutableList.copyOf(results); - assertEquals(1, zones.size()); + assertEquals(2, zones.size()); // dns name problems options = new HashMap<>(); options.put(DnsRpc.Option.DNS_NAME, "aaa"); try { RPC.listZones(options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.dnsName")); } // ok name options = new HashMap<>(); @@ -848,9 +662,9 @@ public void testListZonesUsingRpc() { assertNull(zone.getNameServerSet()); assertNull(zone.getId()); options.put(DnsRpc.Option.FIELDS, "managedZones(nameServerSet)"); - DnsRpc.ListResult managedZoneListResult = RPC.listZones(options); - zone = managedZoneListResult.results().iterator().next(); - assertNull(managedZoneListResult.pageToken()); + DnsRpc.ListResult listResult = RPC.listZones(options); + zone = listResult.results().iterator().next(); + assertNull(listResult.pageToken()); assertNull(zone.getCreationTime()); assertNull(zone.getName()); assertNull(zone.getDnsName()); @@ -862,8 +676,8 @@ public void testListZonesUsingRpc() { options.put(DnsRpc.Option.FIELDS, "managedZones(nameServerSet,description,id,name),nextPageToken"); options.put(DnsRpc.Option.PAGE_SIZE, 1); - managedZoneListResult = RPC.listZones(options); - zone = managedZoneListResult.results().iterator().next(); + listResult = RPC.listZones(options); + zone = listResult.results().iterator().next(); assertNull(zone.getCreationTime()); assertNotNull(zone.getName()); assertNull(zone.getDnsName()); @@ -871,80 +685,19 @@ public void testListZonesUsingRpc() { assertNull(zone.getNameServers()); assertNotNull(zone.getNameServerSet()); assertNotNull(zone.getId()); - assertEquals(zone.getName(), managedZoneListResult.pageToken()); - // paging - options = new HashMap<>(); - options.put(DnsRpc.Option.PAGE_SIZE, 1); - managedZoneListResult = RPC.listZones(options); - ImmutableList page1 = ImmutableList.copyOf(managedZoneListResult.results()); - assertEquals(1, page1.size()); - options.put(DnsRpc.Option.PAGE_TOKEN, managedZoneListResult.pageToken()); - managedZoneListResult = RPC.listZones(options); - ImmutableList page2 = ImmutableList.copyOf(managedZoneListResult.results()); - assertEquals(1, page2.size()); - assertNotEquals(page1.get(0), page2.get(0)); + assertEquals(zone.getName(), listResult.pageToken()); } @Test public void testListDnsRecords() { - // only interested in no exceptions and non-null response here - optionsMap.put("name", null); - optionsMap.put("fields", null); - optionsMap.put("type", null); - optionsMap.put("pageToken", null); - optionsMap.put("maxResults", null); - // no zone exists - LocalDnsHelper.Response response = LOCAL_DNS_HELPER.listDnsRecords(PROJECT_ID1, ZONE_NAME1, - optionsMap); - assertEquals(404, response.code()); - // zone exists but has no records - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - LOCAL_DNS_HELPER.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); - // zone has records - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - response = LOCAL_DNS_HELPER.listDnsRecords(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - // error in options - optionsMap.put("maxResults", "aaa"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "0"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "-1"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "15"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("name", "aaa"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("name", "aaa."); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("name", null); - optionsMap.put("type", "A"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("name", "aaa."); - optionsMap.put("type", "a"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("name", "aaaa."); - optionsMap.put("type", "A"); - response = LOCAL_DNS_HELPER.listZones(PROJECT_ID1, optionsMap); - assertEquals(200, response.code()); - } - - @Test - public void testListDnsRecordsUsingRpc() { // no zone exists try { RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS); + fail(); } catch (DnsException ex) { // expected assertEquals(404, ex.code()); + assertTrue(ex.getMessage().contains("managedZone")); } // zone exists but has no records RPC.create(ZONE1, EMPTY_RPC_OPTIONS); @@ -962,34 +715,35 @@ public void testListDnsRecordsUsingRpc() { options.put(DnsRpc.Option.PAGE_SIZE, 0); try { RPC.listDnsRecords(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, -1); try { RPC.listDnsRecords(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.maxResults")); } - options.put(DnsRpc.Option.PAGE_SIZE, 1); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); - records = ImmutableList.copyOf(results); - assertEquals(1, records.size()); options.put(DnsRpc.Option.PAGE_SIZE, 15); results = RPC.listDnsRecords(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(3, records.size()); - // dnsName filter options = new HashMap<>(); options.put(DnsRpc.Option.NAME, "aaa"); try { RPC.listDnsRecords(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.name")); } options.put(DnsRpc.Option.NAME, "aaa."); results = RPC.listDnsRecords(ZONE1.getName(), options).results(); @@ -999,17 +753,21 @@ public void testListDnsRecordsUsingRpc() { options.put(DnsRpc.Option.DNS_TYPE, "A"); try { RPC.listDnsRecords(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.name")); } options.put(DnsRpc.Option.NAME, "aaa."); options.put(DnsRpc.Option.DNS_TYPE, "a"); try { RPC.listDnsRecords(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.type")); } options.put(DnsRpc.Option.NAME, DNS_NAME); options.put(DnsRpc.Option.DNS_TYPE, "SOA"); @@ -1019,137 +777,74 @@ public void testListDnsRecordsUsingRpc() { // field options options = new HashMap<>(); options.put(DnsRpc.Option.FIELDS, "rrsets(name)"); - DnsRpc.ListResult resourceRecordSetListResult = + DnsRpc.ListResult listResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + records = ImmutableList.copyOf(listResult.results()); ResourceRecordSet record = records.get(0); assertNotNull(record.getName()); assertNull(record.getRrdatas()); assertNull(record.getType()); assertNull(record.getTtl()); - assertNull(resourceRecordSetListResult.pageToken()); + assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(rrdatas)"); - resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + listResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); assertNotNull(record.getRrdatas()); assertNull(record.getType()); assertNull(record.getTtl()); - assertNull(resourceRecordSetListResult.pageToken()); + assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(ttl)"); - resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + listResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); assertNull(record.getRrdatas()); assertNull(record.getType()); assertNotNull(record.getTtl()); - assertNull(resourceRecordSetListResult.pageToken()); + assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(type)"); - resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + listResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); assertNull(record.getRrdatas()); assertNotNull(record.getType()); assertNull(record.getTtl()); - assertNull(resourceRecordSetListResult.pageToken()); + assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "nextPageToken"); - resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + listResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); assertNull(record.getRrdatas()); assertNull(record.getType()); assertNull(record.getTtl()); - assertNull(resourceRecordSetListResult.pageToken()); + assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "nextPageToken,rrsets(name,rrdatas)"); options.put(DnsRpc.Option.PAGE_SIZE, 1); - resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); + listResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); record = records.get(0); assertNotNull(record.getName()); assertNotNull(record.getRrdatas()); assertNull(record.getType()); assertNull(record.getTtl()); - assertNotNull(resourceRecordSetListResult.pageToken()); - // paging - options.put(DnsRpc.Option.PAGE_TOKEN, resourceRecordSetListResult.pageToken()); - resourceRecordSetListResult = RPC.listDnsRecords(ZONE1.getName(), options); - records = ImmutableList.copyOf(resourceRecordSetListResult.results()); - assertEquals(1, records.size()); - ResourceRecordSet nextRecord = records.get(0); - assertNotEquals(record, nextRecord); + assertNotNull(listResult.pageToken()); } @Test public void testListChanges() { - optionsMap.put("sortBy", null); - optionsMap.put("sortOrder", null); - optionsMap.put("fields", null); - optionsMap.put("pageToken", null); - optionsMap.put("maxResults", null); - // no such zone exists - LocalDnsHelper.Response response = - LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(404, response.code()); - assertTrue(response.body().contains("managedZone")); - // zone exists but has no changes - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - assertNotNull(LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); - // zone has changes - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - assertNotNull(LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE1, null); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, CHANGE2, null); - assertNotNull(LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap)); - // error in options - optionsMap.put("maxResults", "aaa"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "0"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "-1"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(400, response.code()); - optionsMap.put("maxResults", "15"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("sortBy", "changeSequence"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("sortBy", "something else"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(400, response.code()); - assertTrue(response.body().contains("Allowed values: [changesequence]")); - optionsMap.put("sortBy", "ChAnGeSeQuEnCe"); // is not case sensitive - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("sortOrder", "ascending"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("sortBy", null); - optionsMap.put("sortOrder", "descending"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(200, response.code()); - optionsMap.put("sortOrder", "somethingelse"); - response = LOCAL_DNS_HELPER.listChanges(PROJECT_ID1, ZONE_NAME1, optionsMap); - assertEquals(400, response.code()); - assertTrue(response.body().contains("parameters.sortOrder")); - } - - @Test - public void testListChangesUsingRpc() { // no such zone exists try { RPC.listChangeRequests(ZONE_NAME1, EMPTY_RPC_OPTIONS); + fail(); } catch (DnsException ex) { // expected assertEquals(404, ex.code()); + assertTrue(ex.getMessage().contains("managedZone")); } // zone exists but has no changes RPC.create(ZONE1, EMPTY_RPC_OPTIONS); @@ -1168,24 +863,25 @@ public void testListChangesUsingRpc() { options.put(DnsRpc.Option.PAGE_SIZE, 0); try { RPC.listChangeRequests(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, -1); try { RPC.listChangeRequests(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, 15); - try { - RPC.listChangeRequests(ZONE1.getName(), options); - } catch (DnsException ex) { - // expected - assertEquals(400, ex.code()); - } + results = RPC.listChangeRequests(ZONE1.getName(), options).results(); + changes = ImmutableList.copyOf(results); + assertEquals(3, changes.size()); options = new HashMap<>(); options.put(DnsRpc.Option.SORTING_ORDER, "descending"); results = RPC.listChangeRequests(ZONE1.getName(), options).results(); @@ -1200,17 +896,18 @@ public void testListChangesUsingRpc() { options.put(DnsRpc.Option.SORTING_ORDER, "something else"); try { RPC.listChangeRequests(ZONE1.getName(), options); + fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); + assertTrue(ex.getMessage().contains("parameters.sortOrder")); } // field options RPC.applyChangeRequest(ZONE1.getName(), CHANGE_COMPLEX, EMPTY_RPC_OPTIONS); options = new HashMap<>(); options.put(DnsRpc.Option.SORTING_ORDER, "descending"); options.put(DnsRpc.Option.FIELDS, "changes(additions)"); - DnsRpc.ListResult changeListResult = - RPC.listChangeRequests(ZONE1.getName(), options); + DnsRpc.ListResult changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); changes = ImmutableList.copyOf(changeListResult.results()); Change complex = changes.get(0); assertNotNull(complex.getAdditions()); @@ -1270,20 +967,68 @@ public void testListChangesUsingRpc() { assertNull(complex.getStartTime()); assertNull(complex.getStatus()); assertNotNull(changeListResult.pageToken()); - // paging - options.put(DnsRpc.Option.FIELDS, "nextPageToken,changes(id)"); + } + + @Test + public void testDnsRecordPaging() { + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + List complete = ImmutableList.copyOf( + RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results()); + Map options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, 1); - changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); - changes = ImmutableList.copyOf(changeListResult.results()); + DnsRpc.ListResult listResult = RPC.listDnsRecords(ZONE1.getName(), options); + ImmutableList records = ImmutableList.copyOf(listResult.results()); + assertEquals(1, records.size()); + assertEquals(complete.get(0), records.get(0)); + options.put(DnsRpc.Option.PAGE_TOKEN, listResult.pageToken()); + listResult = RPC.listDnsRecords(ZONE1.getName(), options); + records = ImmutableList.copyOf(listResult.results()); + assertEquals(1, records.size()); + assertEquals(complete.get(1), records.get(0)); + } + + @Test + public void testZonePaging() { + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + RPC.create(ZONE2, EMPTY_RPC_OPTIONS); + ImmutableList complete = ImmutableList.copyOf( + RPC.listZones(EMPTY_RPC_OPTIONS).results()); + Map options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + DnsRpc.ListResult listResult = RPC.listZones(options); + ImmutableList page1 = ImmutableList.copyOf(listResult.results()); + assertEquals(1, page1.size()); + assertEquals(complete.get(0), page1.get(0)); + assertEquals(page1.get(0).getName(), listResult.pageToken()); + options.put(DnsRpc.Option.PAGE_TOKEN, listResult.pageToken()); + listResult = RPC.listZones(options); + ImmutableList page2 = ImmutableList.copyOf(listResult.results()); + assertEquals(1, page2.size()); + assertEquals(complete.get(1), page2.get(0)); + assertNull(listResult.pageToken()); + } + + @Test + public void testChangePaging() { + RPC.create(ZONE1, EMPTY_RPC_OPTIONS); + RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); + RPC.applyChangeRequest(ZONE1.getName(), CHANGE2, EMPTY_RPC_OPTIONS); + RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); + ImmutableList complete = + ImmutableList.copyOf(RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results()); + Map options = new HashMap<>(); + options.put(DnsRpc.Option.PAGE_SIZE, 1); + DnsRpc.ListResult changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); + List changes = ImmutableList.copyOf(changeListResult.results()); assertEquals(1, changes.size()); - final Change first = changes.get(0); - assertNotNull(changeListResult.pageToken()); + assertEquals(complete.get(0), changes.get(0)); + assertEquals(complete.get(0).getId(), changeListResult.pageToken()); options.put(DnsRpc.Option.PAGE_TOKEN, changeListResult.pageToken()); changeListResult = RPC.listChangeRequests(ZONE1.getName(), options); changes = ImmutableList.copyOf(changeListResult.results()); assertEquals(1, changes.size()); - Change second = changes.get(0); - assertNotEquals(first, second); + assertEquals(complete.get(1), changes.get(0)); + assertEquals(complete.get(1).getId(), changeListResult.pageToken()); } @Test @@ -1303,95 +1048,71 @@ public void testToListResponse() { } @Test - public void testCheckZone() { + public void testCreateZoneValidation() { + ManagedZone minimalZone = copyZone(ZONE1); // no name ManagedZone copy = copyZone(minimalZone); copy.setName(null); - LocalDnsHelper.Response response = LocalDnsHelper.checkZone(copy); + LocalDnsHelper.Response response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.name")); // no description copy = copyZone(minimalZone); copy.setDescription(null); - response = LocalDnsHelper.checkZone(copy); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.description")); - // no description + // no dns name copy = copyZone(minimalZone); copy.setDnsName(null); - response = LocalDnsHelper.checkZone(copy); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.dnsName")); - // zone name is a number + // zone name does not start with a letter copy = copyZone(minimalZone); - copy.setName("123456"); - response = LocalDnsHelper.checkZone(copy); + copy.setName("1aaaaaa"); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.name")); assertTrue(response.body().contains("Invalid")); - // dns name does not end with period + // zone name is too long copy = copyZone(minimalZone); - copy.setDnsName("aaaaaa.com"); - response = LocalDnsHelper.checkZone(copy); + copy.setName("123456aaaa123456aaaa123456aaaa123456aaaa123456aaaa123456aaaa123456aaaa123456aa"); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); - assertTrue(response.body().contains("entity.managedZone.dnsName")); + assertTrue(response.body().contains("entity.managedZone.name")); assertTrue(response.body().contains("Invalid")); - // dns name is reserved - copy = copyZone(minimalZone); - copy.setDnsName("com."); - response = LocalDnsHelper.checkZone(copy); - assertEquals(400, response.code()); - assertTrue(response.body().contains("not available to be created.")); - // empty description should pass + // zone name contains invalid characters copy = copyZone(minimalZone); - copy.setDescription(""); - assertNull(LocalDnsHelper.checkZone(copy)); - } - - @Test - public void testCreateZoneValidatesZone() { - // no name - ManagedZone copy = copyZone(minimalZone); - copy.setName(null); - LocalDnsHelper.Response response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); + copy.setName("x1234AA6aa"); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.name")); - // no description - copy = copyZone(minimalZone); - copy.setDescription(null); - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("entity.managedZone.description")); - // no dns name - copy = copyZone(minimalZone); - copy.setDnsName(null); - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("entity.managedZone.dnsName")); - // zone name is a number + assertTrue(response.body().contains("Invalid")); + // zone name contains invalid characters copy = copyZone(minimalZone); - copy.setName("123456"); - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); + copy.setName("x a"); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.name")); assertTrue(response.body().contains("Invalid")); // dns name does not end with period copy = copyZone(minimalZone); copy.setDnsName("aaaaaa.com"); - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("entity.managedZone.dnsName")); assertTrue(response.body().contains("Invalid")); // dns name is reserved copy = copyZone(minimalZone); copy.setDnsName("com."); - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(400, response.code()); assertTrue(response.body().contains("not available to be created.")); // empty description should pass copy = copyZone(minimalZone); copy.setDescription(""); - response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy, null); + response = LOCAL_DNS_HELPER.createZone(PROJECT_ID1, copy); assertEquals(200, response.code()); } @@ -1474,8 +1195,8 @@ public void testCheckRrset() { valid.setTtl(500); Change validChange = new Change(); validChange.setAdditions(ImmutableList.of(valid)); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange); // delete with field mismatch LocalDnsHelper.ZoneContainer zone = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1); valid.setTtl(valid.getTtl() + 20); @@ -1501,11 +1222,10 @@ public void testCheckRrdata() { assertFalse(LocalDnsHelper.checkRrData("111.255.12", "A")); assertFalse(LocalDnsHelper.checkRrData("111.255.12.11.11", "A")); // AAAA - assertTrue(LocalDnsHelper.checkRrData(":::::::", "AAAA")); - assertTrue(LocalDnsHelper.checkRrData("1F:fa:09fd::343:aaaa:AAAA:", "AAAA")); - assertTrue(LocalDnsHelper.checkRrData("0000:FFFF:09fd::343:aaaa:AAAA:", "AAAA")); + assertTrue(LocalDnsHelper.checkRrData("1F:fa:09fd::343:aaaa:AAAA:0", "AAAA")); + assertTrue(LocalDnsHelper.checkRrData("0000:FFFF:09fd::343:aaaa:AAAA:0", "AAAA")); assertFalse(LocalDnsHelper.checkRrData("-2:::::::", "AAAA")); - assertTrue(LocalDnsHelper.checkRrData("0:::::::", "AAAA")); + assertTrue(LocalDnsHelper.checkRrData("0::0", "AAAA")); assertFalse(LocalDnsHelper.checkRrData("::1FFFF:::::", "AAAA")); assertFalse(LocalDnsHelper.checkRrData("::aqaa:::::", "AAAA")); assertFalse(LocalDnsHelper.checkRrData("::::::::", "AAAA")); // too long @@ -1587,62 +1307,59 @@ public void testCheckChange() { ResourceRecordSet nonExistent = new ResourceRecordSet(); nonExistent.setName(ZONE1.getDnsName()); nonExistent.setType("AAAA"); - nonExistent.setRrdatas(ImmutableList.of(":::::::")); + nonExistent.setRrdatas(ImmutableList.of("0:0:0:0:5::6")); Change delete = new Change(); delete.setDeletions(ImmutableList.of(nonExistent)); response = LocalDnsHelper.checkChange(delete, zoneContainer); assertEquals(404, response.code()); assertTrue(response.body().contains("deletions[0]")); - } @Test - public void testAdditionsMeetDeletions() { + public void testCheckAdditionsDeletions() { ResourceRecordSet validA = new ResourceRecordSet(); validA.setName(ZONE1.getDnsName()); validA.setType("A"); validA.setRrdatas(ImmutableList.of("0.255.1.5")); Change validChange = new Change(); validChange.setAdditions(ImmutableList.of(validA)); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange); LocalDnsHelper.ZoneContainer container = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1); LocalDnsHelper.Response response = - LocalDnsHelper.additionsMeetDeletions(ImmutableList.of(validA), null, container); + LocalDnsHelper.checkAdditionsDeletions(ImmutableList.of(validA), null, container); assertEquals(409, response.code()); assertTrue(response.body().contains("already exists")); - } @Test - public void testCreateChangeValidatesChangeContent() { + public void testCreateChangeContentValidation() { ResourceRecordSet validA = new ResourceRecordSet(); validA.setName(ZONE1.getDnsName()); validA.setType("A"); validA.setRrdatas(ImmutableList.of("0.255.1.5")); Change validChange = new Change(); validChange.setAdditions(ImmutableList.of(validA)); - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange); LocalDnsHelper.Response response = - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); + LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange); assertEquals(409, response.code()); assertTrue(response.body().contains("already exists")); // delete with field mismatch Change delete = new Change(); validA.setTtl(20); // mismatch delete.setDeletions(ImmutableList.of(validA)); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete); assertEquals(412, response.code()); assertTrue(response.body().contains("entity.change.deletions[0]")); // delete and add SOA Change addition = new Change(); - ImmutableList rrsetWrappers - = LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get(ZONE_NAME1); + ImmutableCollection dnsRecords = + LOCAL_DNS_HELPER.findZone(PROJECT_ID1, ZONE_NAME1).dnsRecords().get().values(); LinkedList deletions = new LinkedList<>(); LinkedList additions = new LinkedList<>(); - for (LocalDnsHelper.RrsetWrapper wrapper : rrsetWrappers) { - ResourceRecordSet rrset = wrapper.rrset(); + for (ResourceRecordSet rrset : dnsRecords) { if (rrset.getType().equals("SOA")) { deletions.add(rrset); ResourceRecordSet copy = copyRrset(rrset); @@ -1653,12 +1370,12 @@ public void testCreateChangeValidatesChangeContent() { } delete.setDeletions(deletions); addition.setAdditions(additions); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'SOA' at the apex")); assertTrue(response.body().contains("deletions[0]")); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'SOA' at the apex")); @@ -1666,8 +1383,7 @@ public void testCreateChangeValidatesChangeContent() { // delete NS deletions = new LinkedList<>(); additions = new LinkedList<>(); - for (LocalDnsHelper.RrsetWrapper wrapper : rrsetWrappers) { - ResourceRecordSet rrset = wrapper.rrset(); + for (ResourceRecordSet rrset : dnsRecords) { if (rrset.getType().equals("NS")) { deletions.add(rrset); ResourceRecordSet copy = copyRrset(rrset); @@ -1678,96 +1394,38 @@ public void testCreateChangeValidatesChangeContent() { } delete.setDeletions(deletions); addition.setAdditions(additions); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'NS' at the apex")); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition); assertEquals(400, response.code()); assertTrue(response.body().contains( "zone must contain exactly one resource record set of type 'NS' at the apex")); assertTrue(response.body().contains("additions[0]")); // change (delete + add) addition.setDeletions(deletions); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition, null); + response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, addition); assertEquals(200, response.code()); } @Test - public void testCreateChangeValidatesChange() { - LOCAL_DNS_HELPER.createZone(PROJECT_ID1, ZONE1, null); - ResourceRecordSet validA = new ResourceRecordSet(); - validA.setName(ZONE1.getDnsName()); - validA.setType("A"); - validA.setRrdatas(ImmutableList.of("0.255.1.5")); - ResourceRecordSet invalidA = new ResourceRecordSet(); - invalidA.setName(ZONE1.getDnsName()); - invalidA.setType("A"); - invalidA.setRrdatas(ImmutableList.of("0.-255.1.5")); - Change validChange = new Change(); - validChange.setAdditions(ImmutableList.of(validA)); - Change invalidChange = new Change(); - invalidChange.setAdditions(ImmutableList.of(invalidA)); - LocalDnsHelper.Response response = - LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(200, response.code()); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, invalidChange, null); - assertEquals(400, response.code()); - // only empty additions/deletions - Change empty = new Change(); - empty.setAdditions(ImmutableList.of()); - empty.setDeletions(ImmutableList.of()); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, empty, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains( - "The 'entity.change' parameter is required but was missing.")); - // non-matching name - validA.setName(ZONE1.getDnsName() + ".aaa."); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("additions[0].name")); - // wrong type - validA.setName(ZONE1.getDnsName()); // revert - validA.setType("ABCD"); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("additions[0].type")); - // wrong ttl - validA.setType("A"); // revert - validA.setTtl(-1); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("additions[0].ttl")); - validA.setTtl(null); // revert - // null name - validA.setName(null); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("additions[0].name")); - validA.setName(ZONE1.getDnsName()); - // null type - validA.setType(null); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("additions[0].type")); - validA.setType("A"); - // null rrdata - final List temp = validA.getRrdatas(); // preserve - validA.setRrdatas(null); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, validChange, null); - assertEquals(400, response.code()); - assertTrue(response.body().contains("additions[0].rrdata")); - validA.setRrdatas(temp); - // delete non-existent - ResourceRecordSet nonExistent = new ResourceRecordSet(); - nonExistent.setName(ZONE1.getDnsName()); - nonExistent.setType("AAAA"); - nonExistent.setRrdatas(ImmutableList.of(":::::::")); - Change delete = new Change(); - delete.setDeletions(ImmutableList.of(nonExistent)); - response = LOCAL_DNS_HELPER.createChange(PROJECT_ID1, ZONE_NAME1, delete, null); - assertEquals(404, response.code()); - assertTrue(response.body().contains("deletions[0]")); + public void testMatchesCriteria() { + assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), RRSET1.getType())); + assertFalse(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), "anothertype")); + assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, null, RRSET1.getType())); + assertTrue(LocalDnsHelper.matchesCriteria(RRSET1, RRSET1.getName(), null)); + assertFalse(LocalDnsHelper.matchesCriteria(RRSET1, "anothername", RRSET1.getType())); + } + + @Test + public void testGetUniqueId() { + assertNotNull(LocalDnsHelper.getUniqueId(new HashSet())); + } + + @Test + public void testRandomNameServers() { + assertEquals(4, LocalDnsHelper.randomNameservers().size()); } private static ManagedZone copyZone(ManagedZone original) { From 3cf07229834282f96f84cd783b4487a323967bfc Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 1 Mar 2016 14:41:17 -0800 Subject: [PATCH 61/74] Switched ZoneInfo.builder(). to ZoneInfo.of(). Fixes #698. --- .../java/com/google/gcloud/dns/ZoneInfo.java | 6 +-- .../com/google/gcloud/dns/DnsImplTest.java | 3 +- .../google/gcloud/dns/SerializationTest.java | 10 ++--- .../com/google/gcloud/dns/ZoneInfoTest.java | 42 ++++++++--------- .../java/com/google/gcloud/dns/ZoneTest.java | 9 ++-- .../com/google/gcloud/dns/it/ITDnsTest.java | 45 +++---------------- 6 files changed, 38 insertions(+), 77 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java index 7dffbcdd365c..38a88b67777e 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ZoneInfo.java @@ -185,10 +185,10 @@ public ZoneInfo build() { } /** - * Returns a builder for {@code ZoneInfo} with an assigned {@code name}. + * Returns a ZoneInfo object with assigned {@code name}, {@code dnsName} and {@code description}. */ - public static Builder builder(String name) { - return new BuilderImpl(name); + public static ZoneInfo of(String name, String dnsName, String description) { + return new BuilderImpl(name).dnsName(dnsName).description(description).build(); } /** diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index e1974d6cccfd..9205de8d99dd 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -44,6 +44,7 @@ public class DnsImplTest { // Dns entities private static final String ZONE_NAME = "some zone name"; private static final String DNS_NAME = "example.com."; + private static final String DESCRIPTION = "desc"; private static final String CHANGE_ID = "some change id"; private static final DnsRecord DNS_RECORD1 = DnsRecord.builder("Something", DnsRecord.Type.AAAA) .build(); @@ -51,7 +52,7 @@ public class DnsImplTest { .build(); private static final Integer MAX_SIZE = 20; private static final String PAGE_TOKEN = "some token"; - private static final ZoneInfo ZONE_INFO = ZoneInfo.builder(ZONE_NAME).build(); + private static final ZoneInfo ZONE_INFO = ZoneInfo.of(ZONE_NAME, DNS_NAME, DESCRIPTION); private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder() .add(DNS_RECORD1) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java index adf5744d854e..c2bf9cfca0bb 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -35,16 +35,15 @@ public class SerializationTest { - private static final ZoneInfo FULL_ZONE_INFO = Zone.builder("some zone name") + private static final ZoneInfo FULL_ZONE_INFO = Zone.of("some zone name", "www.example.com", + "some descriptions").toBuilder() .creationTimeMillis(132L) - .description("some descriptions") - .dnsName("www.example.com") .id("123333") .nameServers(ImmutableList.of("server 1", "server 2")) .nameServerSet("specificationstring") .build(); - private static final ZoneInfo PARTIAL_ZONE_INFO = Zone.builder("some zone name") - .build(); + private static final ZoneInfo PARTIAL_ZONE_INFO = Zone.of("some zone name", "www.example.com", + "some descriptions").toBuilder().build(); private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.builder().id("13").build(); private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.builder() .id("342") @@ -87,7 +86,6 @@ public class SerializationTest { .startTimeMillis(132L) .build(); - @Test public void testModelAndRequests() throws Exception { Serializable[] objects = {FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java index 227916b46f96..b743bd385274 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java @@ -41,25 +41,23 @@ public class ZoneInfoTest { private static final String NS2 = "name server 2"; private static final String NS3 = "name server 3"; private static final List NAME_SERVERS = ImmutableList.of(NS1, NS2, NS3); - private static final ZoneInfo INFO = ZoneInfo.builder(NAME) + private static final ZoneInfo INFO = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() .creationTimeMillis(CREATION_TIME_MILLIS) .id(ID) - .dnsName(DNS_NAME) - .description(DESCRIPTION) .nameServerSet(NAME_SERVER_SET) .nameServers(NAME_SERVERS) .build(); @Test public void testDefaultBuilders() { - ZoneInfo zone = ZoneInfo.builder(NAME).build(); + ZoneInfo zone = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertTrue(zone.nameServers().isEmpty()); assertEquals(NAME, zone.name()); assertNull(zone.id()); assertNull(zone.creationTimeMillis()); assertNull(zone.nameServerSet()); - assertNull(zone.description()); - assertNull(zone.dnsName()); + assertEquals(DESCRIPTION, zone.description()); + assertEquals(DNS_NAME, zone.dnsName()); } @Test @@ -109,42 +107,38 @@ public void testSameHashCodeOnEquals() { @Test public void testToBuilder() { assertEquals(INFO, INFO.toBuilder().build()); - ZoneInfo partial = ZoneInfo.builder(NAME).build(); + ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.builder(NAME).id(ID).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().id(ID).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.builder(NAME).description(DESCRIPTION).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() + .creationTimeMillis(CREATION_TIME_MILLIS).build(); assertEquals(partial, partial.toBuilder().build()); List nameServers = new LinkedList<>(); nameServers.add(NS1); - partial = ZoneInfo.builder(NAME).nameServers(nameServers).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServers(nameServers).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServerSet(NAME_SERVER_SET) + .build(); assertEquals(partial, partial.toBuilder().build()); } @Test public void testToAndFromPb() { assertEquals(INFO, ZoneInfo.fromPb(INFO.toPb())); - ZoneInfo partial = ZoneInfo.builder(NAME).build(); - assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.builder(NAME).id(ID).build(); - assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.builder(NAME).description(DESCRIPTION).build(); + ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.builder(NAME).dnsName(DNS_NAME).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().id(ID).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.builder(NAME).creationTimeMillis(CREATION_TIME_MILLIS).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() + .creationTimeMillis(CREATION_TIME_MILLIS).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); List nameServers = new LinkedList<>(); nameServers.add(NS1); - partial = ZoneInfo.builder(NAME).nameServers(nameServers).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServers(nameServers).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.builder(NAME).nameServerSet(NAME_SERVER_SET).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServerSet(NAME_SERVER_SET) + .build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 5164dfb6001c..759c34fc1167 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -43,13 +43,13 @@ public class ZoneTest { private static final String ZONE_NAME = "dns-zone-name"; private static final String ZONE_ID = "123"; - private static final ZoneInfo ZONE_INFO = Zone.builder(ZONE_NAME) + private static final ZoneInfo ZONE_INFO = Zone.of(ZONE_NAME, "example.com", "description") + .toBuilder() .id(ZONE_ID) - .dnsName("example.com") .creationTimeMillis(123478946464L) .build(); - private static final ZoneInfo NO_ID_INFO = ZoneInfo.builder(ZONE_NAME) - .dnsName("another-example.com") + private static final ZoneInfo NO_ID_INFO = + ZoneInfo.of(ZONE_NAME, "another-example.com", "description").toBuilder() .creationTimeMillis(893123464L) .build(); private static final Dns.ZoneOption ZONE_FIELD_OPTIONS = @@ -71,7 +71,6 @@ public class ZoneTest { private Zone zone; private Zone zoneNoId; - @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index fda579a4a94b..4ad17fa8b217 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -60,29 +60,14 @@ public class ITDnsTest { private static final String ZONE_DNS_NAME1 = ZONE_NAME1 + ".com."; private static final String ZONE_DNS_EMPTY_DESCRIPTION = ZONE_NAME_EMPTY_DESCRIPTION + ".com."; private static final String ZONE_DNS_NAME_NO_PERIOD = ZONE_NAME1 + ".com"; - private static final ZoneInfo ZONE1 = ZoneInfo.builder(ZONE_NAME1) - .description(ZONE_DESCRIPTION1) - .dnsName(ZONE_DNS_EMPTY_DESCRIPTION) - .build(); + private static final ZoneInfo ZONE1 = + ZoneInfo.of(ZONE_NAME1, ZONE_DNS_EMPTY_DESCRIPTION, ZONE_DESCRIPTION1); private static final ZoneInfo ZONE_EMPTY_DESCRIPTION = - ZoneInfo.builder(ZONE_NAME_EMPTY_DESCRIPTION) - .description(ZONE_DESCRIPTION1) - .dnsName(ZONE_DNS_NAME1) - .build(); - private static final ZoneInfo ZONE_NAME_ERROR = ZoneInfo.builder(ZONE_NAME_TOO_LONG) - .description(ZONE_DESCRIPTION1) - .dnsName(ZONE_DNS_NAME1) - .build(); - private static final ZoneInfo ZONE_MISSING_DESCRIPTION = ZoneInfo.builder(ZONE_NAME1) - .dnsName(ZONE_DNS_NAME1) - .build(); - private static final ZoneInfo ZONE_MISSING_DNS_NAME = ZoneInfo.builder(ZONE_NAME1) - .description(ZONE_DESCRIPTION1) - .build(); - private static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.builder(ZONE_NAME1) - .description(ZONE_DESCRIPTION1) - .dnsName(ZONE_DNS_NAME_NO_PERIOD) - .build(); + ZoneInfo.of(ZONE_NAME_EMPTY_DESCRIPTION, ZONE_DNS_NAME1, ZONE_DESCRIPTION1); + private static final ZoneInfo ZONE_NAME_ERROR = + ZoneInfo.of(ZONE_NAME_TOO_LONG, ZONE_DNS_NAME1, ZONE_DESCRIPTION1); + private static final ZoneInfo ZONE_DNS_NO_PERIOD = + ZoneInfo.of(ZONE_NAME1, ZONE_DNS_NAME_NO_PERIOD, ZONE_DESCRIPTION1); private static final DnsRecord A_RECORD_ZONE1 = DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) .records(ImmutableList.of("123.123.55.1")) @@ -211,20 +196,6 @@ public void testCreateValidZone() { @Test public void testCreateZoneWithErrors() { try { - try { - DNS.create(ZONE_MISSING_DNS_NAME); - fail("Zone is missing DNS name. The service returns an error."); - } catch (DnsException ex) { - // expected - // todo(mderka) test non-retryable when implemented within #593 - } - try { - DNS.create(ZONE_MISSING_DESCRIPTION); - fail("Zone is missing description name. The service returns an error."); - } catch (DnsException ex) { - // expected - // todo(mderka) test non-retryable when implemented within #593 - } try { DNS.create(ZONE_NAME_ERROR); fail("Zone name is missing a period. The service returns an error."); @@ -240,8 +211,6 @@ public void testCreateZoneWithErrors() { // todo(mderka) test non-retryable when implemented within #593 } } finally { - DNS.delete(ZONE_MISSING_DNS_NAME.name()); - DNS.delete(ZONE_MISSING_DESCRIPTION.name()); DNS.delete(ZONE_NAME_ERROR.name()); DNS.delete(ZONE_DNS_NO_PERIOD.name()); } From 90897f35fc7102456b0faecccad0a1171accc804 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 10 Mar 2016 08:01:04 -0800 Subject: [PATCH 62/74] Renamed a test method and a variable. --- .../com/google/gcloud/dns/ZoneInfoTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java index b743bd385274..923672bb85a7 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneInfoTest.java @@ -49,15 +49,15 @@ public class ZoneInfoTest { .build(); @Test - public void testDefaultBuilders() { - ZoneInfo zone = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); - assertTrue(zone.nameServers().isEmpty()); - assertEquals(NAME, zone.name()); - assertNull(zone.id()); - assertNull(zone.creationTimeMillis()); - assertNull(zone.nameServerSet()); - assertEquals(DESCRIPTION, zone.description()); - assertEquals(DNS_NAME, zone.dnsName()); + public void testOf() { + ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); + assertTrue(partial.nameServers().isEmpty()); + assertEquals(NAME, partial.name()); + assertNull(partial.id()); + assertNull(partial.creationTimeMillis()); + assertNull(partial.nameServerSet()); + assertEquals(DESCRIPTION, partial.description()); + assertEquals(DNS_NAME, partial.dnsName()); } @Test From 767be657b14e8f6e86167389e9af8d65a7fff19d Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 14 Mar 2016 09:53:34 -0700 Subject: [PATCH 63/74] LocalDnsHelper adds the default change upon creating a zone. This now matches the behaviour of the service. Fixes #672. --- .../gcloud/dns/testing/LocalDnsHelper.java | 17 +++++++++++++---- .../gcloud/dns/testing/LocalDnsHelperTest.java | 8 ++++---- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java index f9cd1a11281e..3b18ec5ce55b 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java @@ -680,7 +680,15 @@ Response createZone(String projectId, ManagedZone zone, String... fields) { completeZone.setId(BigInteger.valueOf(Math.abs(ID_GENERATOR.nextLong() % Long.MAX_VALUE))); completeZone.setNameServers(randomNameservers()); ZoneContainer zoneContainer = new ZoneContainer(completeZone); - zoneContainer.dnsRecords().set(defaultRecords(completeZone)); + ImmutableSortedMap defaultsRecords = defaultRecords(completeZone); + zoneContainer.dnsRecords().set(defaultsRecords); + Change change = new Change(); + change.setAdditions(ImmutableList.copyOf(defaultsRecords.values())); + change.setStatus("done"); + change.setId("0"); + change.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC() + .print(System.currentTimeMillis())); + zoneContainer.changes().add(change); ProjectContainer projectContainer = findProject(projectId); ZoneContainer oldValue = projectContainer.zones().putIfAbsent( completeZone.getName(), zoneContainer); @@ -718,8 +726,9 @@ Response createChange(String projectId, String zoneName, Change change, String.. completeChange.setDeletions(ImmutableList.copyOf(change.getDeletions())); } /* We need to set ID for the change. We are working in concurrent environment. We know that the - element fell on an index between 0 and maxId, so we will reset all IDs in this range (all of - them are valid for the respective objects). */ + element fell on an index between 1 and maxId (index 0 is the default change which creates SOA + and NS), so we will reset all IDs between 0 and maxId (all of them are valid for the respective + objects). */ ConcurrentLinkedQueue changeSequence = zoneContainer.changes(); changeSequence.add(completeChange); int maxId = changeSequence.size(); @@ -728,7 +737,7 @@ Response createChange(String projectId, String zoneName, Change change, String.. if (index == maxId) { break; } - c.setId(String.valueOf(++index)); + c.setId(String.valueOf(index++)); } completeChange.setStatus("pending"); completeChange.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC() diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java index 2d049e4ffeea..15fa437eb631 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java @@ -850,14 +850,14 @@ public void testListChanges() { RPC.create(ZONE1, EMPTY_RPC_OPTIONS); Iterable results = RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); ImmutableList changes = ImmutableList.copyOf(results); - assertEquals(0, changes.size()); + assertEquals(1, changes.size()); // zone has changes RPC.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); RPC.applyChangeRequest(ZONE1.getName(), CHANGE2, EMPTY_RPC_OPTIONS); RPC.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); results = RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); changes = ImmutableList.copyOf(results); - assertEquals(3, changes.size()); + assertEquals(4, changes.size()); // error in options Map options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, 0); @@ -881,14 +881,14 @@ public void testListChanges() { options.put(DnsRpc.Option.PAGE_SIZE, 15); results = RPC.listChangeRequests(ZONE1.getName(), options).results(); changes = ImmutableList.copyOf(results); - assertEquals(3, changes.size()); + assertEquals(4, changes.size()); options = new HashMap<>(); options.put(DnsRpc.Option.SORTING_ORDER, "descending"); results = RPC.listChangeRequests(ZONE1.getName(), options).results(); ImmutableList descending = ImmutableList.copyOf(results); results = RPC.listChangeRequests(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); ImmutableList ascending = ImmutableList.copyOf(results); - int size = 3; + int size = 4; assertEquals(size, descending.size()); for (int i = 0; i < size; i++) { assertEquals(descending.get(i), ascending.get(size - i - 1)); From 96e380c182aa89f8c4f7dbdcb7df2d4c188c8343 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 14 Mar 2016 14:45:15 -0700 Subject: [PATCH 64/74] Moved spi package to dns.spi as per #742 --- .../com/google/gcloud/dns/AbstractOption.java | 2 +- .../main/java/com/google/gcloud/dns/Dns.java | 2 +- .../java/com/google/gcloud/dns/DnsImpl.java | 2 +- .../com/google/gcloud/dns/DnsOptions.java | 6 ++--- .../gcloud/{ => dns}/spi/DefaultDnsRpc.java | 22 +++++++++---------- .../google/gcloud/{ => dns}/spi/DnsRpc.java | 2 +- .../gcloud/{ => dns}/spi/DnsRpcFactory.java | 3 ++- .../google/gcloud/dns/AbstractOptionTest.java | 2 +- .../com/google/gcloud/dns/DnsImplTest.java | 4 ++-- .../java/com/google/gcloud/dns/DnsTest.java | 2 +- .../dns/testing/LocalDnsHelperTest.java | 4 ++-- 11 files changed, 26 insertions(+), 25 deletions(-) rename gcloud-java-dns/src/main/java/com/google/gcloud/{ => dns}/spi/DefaultDnsRpc.java (91%) rename gcloud-java-dns/src/main/java/com/google/gcloud/{ => dns}/spi/DnsRpc.java (99%) rename gcloud-java-dns/src/main/java/com/google/gcloud/{ => dns}/spi/DnsRpcFactory.java (91%) diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java index a148468d14b5..e12f7412e687 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/AbstractOption.java @@ -19,7 +19,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; -import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; import java.io.Serializable; import java.util.Objects; diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index b2cb9fbad371..6ce6b4c19994 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -20,7 +20,7 @@ import com.google.common.collect.Sets; import com.google.gcloud.Page; import com.google.gcloud.Service; -import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; import java.io.Serializable; import java.util.Set; diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index 17521c13c625..a60cfd9151da 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -33,7 +33,7 @@ import com.google.gcloud.Page; import com.google.gcloud.PageImpl; import com.google.gcloud.RetryHelper; -import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; import java.util.Map; import java.util.concurrent.Callable; 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 d9317546cea0..db922b42a3cb 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 @@ -18,9 +18,9 @@ import com.google.common.collect.ImmutableSet; import com.google.gcloud.ServiceOptions; -import com.google.gcloud.spi.DefaultDnsRpc; -import com.google.gcloud.spi.DnsRpc; -import com.google.gcloud.spi.DnsRpcFactory; +import com.google.gcloud.dns.spi.DefaultDnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpcFactory; import java.util.Set; diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java similarity index 91% rename from gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java index 1df0a8a2f831..f8b8adb87ada 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java @@ -1,13 +1,13 @@ -package com.google.gcloud.spi; - -import static com.google.gcloud.spi.DnsRpc.ListResult.of; -import static com.google.gcloud.spi.DnsRpc.Option.DNS_NAME; -import static com.google.gcloud.spi.DnsRpc.Option.DNS_TYPE; -import static com.google.gcloud.spi.DnsRpc.Option.FIELDS; -import static com.google.gcloud.spi.DnsRpc.Option.NAME; -import static com.google.gcloud.spi.DnsRpc.Option.PAGE_SIZE; -import static com.google.gcloud.spi.DnsRpc.Option.PAGE_TOKEN; -import static com.google.gcloud.spi.DnsRpc.Option.SORTING_ORDER; +package com.google.gcloud.dns.spi; + +import static com.google.gcloud.dns.spi.DnsRpc.ListResult.of; +import static com.google.gcloud.dns.spi.DnsRpc.Option.DNS_NAME; +import static com.google.gcloud.dns.spi.DnsRpc.Option.DNS_TYPE; +import static com.google.gcloud.dns.spi.DnsRpc.Option.FIELDS; +import static com.google.gcloud.dns.spi.DnsRpc.Option.NAME; +import static com.google.gcloud.dns.spi.DnsRpc.Option.PAGE_SIZE; +import static com.google.gcloud.dns.spi.DnsRpc.Option.PAGE_TOKEN; +import static com.google.gcloud.dns.spi.DnsRpc.Option.SORTING_ORDER; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import com.google.api.client.http.HttpRequestInitializer; @@ -188,7 +188,7 @@ public ListResult listChangeRequests(String zoneName, Map opt request = request.setSortBy(SORT_BY).setSortOrder(SORTING_ORDER.getString(options)); } ChangesListResponse response = request.execute(); - return ListResult.of(response.getNextPageToken(), response.getChanges()); + return of(response.getNextPageToken(), response.getChanges()); } catch (IOException ex) { throw translate(ex); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java similarity index 99% rename from gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java index addb69d24b40..bde93b99bfdd 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.google.gcloud.spi; +package com.google.gcloud.dns.spi; import com.google.api.services.dns.model.Change; import com.google.api.services.dns.model.ManagedZone; diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpcFactory.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpcFactory.java similarity index 91% rename from gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpcFactory.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpcFactory.java index 3d25f09bb1e5..ca1b1a0dd018 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/spi/DnsRpcFactory.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpcFactory.java @@ -14,9 +14,10 @@ * limitations under the License. */ -package com.google.gcloud.spi; +package com.google.gcloud.dns.spi; import com.google.gcloud.dns.DnsOptions; +import com.google.gcloud.spi.ServiceRpcFactory; /** * An interface for DnsRpc factory. Implementation will be loaded via {@link diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java index 09e35527879b..d88ea85c5846 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/AbstractOptionTest.java @@ -20,7 +20,7 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; -import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; import org.junit.Test; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index 9205de8d99dd..a97c9c408036 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -28,8 +28,8 @@ import com.google.gcloud.Page; import com.google.gcloud.RetryParams; import com.google.gcloud.ServiceOptions; -import com.google.gcloud.spi.DnsRpc; -import com.google.gcloud.spi.DnsRpcFactory; +import com.google.gcloud.dns.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpcFactory; import org.easymock.Capture; import org.easymock.EasyMock; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index c9f4df4f5bdd..2e233e2df62a 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; import org.junit.Test; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java index 15fa437eb631..59002131cc9d 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java @@ -32,8 +32,8 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.gcloud.dns.DnsException; -import com.google.gcloud.spi.DefaultDnsRpc; -import com.google.gcloud.spi.DnsRpc; +import com.google.gcloud.dns.spi.DefaultDnsRpc; +import com.google.gcloud.dns.spi.DnsRpc; import org.junit.AfterClass; import org.junit.Before; From 886a8bdf0885edcaf971bd6aca9de715727ae11c Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 2 Mar 2016 10:13:20 -0800 Subject: [PATCH 65/74] 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 66/74] 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 67/74] 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."); + } + } +} From baee7d70fd9aa93d6f95b9ce8850ada77e2ccc7f Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Mon, 14 Mar 2016 15:37:03 -0700 Subject: [PATCH 68/74] Added integration test for invalid change request. Also added checks for the exceptions being non-retryable. Closes #673. --- .../com/google/gcloud/dns/it/ITDnsTest.java | 92 ++++++++++++++++--- 1 file changed, 79 insertions(+), 13 deletions(-) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index 4ad17fa8b217..e1a7c218c1b4 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -48,8 +48,6 @@ public class ITDnsTest { - // todo(mderka) Implement test for creating invalid change when DnsException is finished. #673 - private static final String PREFIX = "gcldjvit-"; private static final Dns DNS = DnsOptions.builder().build().service(); private static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32); @@ -201,14 +199,14 @@ public void testCreateZoneWithErrors() { fail("Zone name is missing a period. The service returns an error."); } catch (DnsException ex) { // expected - // todo(mderka) test non-retryable when implemented within #593 + assertFalse(ex.retryable()); } try { DNS.create(ZONE_DNS_NO_PERIOD); fail("Zone name is missing a period. The service returns an error."); } catch (DnsException ex) { // expected - // todo(mderka) test non-retryable when implemented within #593 + assertFalse(ex.retryable()); } } finally { DNS.delete(ZONE_NAME_ERROR.name()); @@ -393,7 +391,7 @@ public void testListZones() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test not-retryable + assertFalse(ex.retryable()); } try { DNS.listZones(Dns.ZoneListOption.pageSize(-1)); @@ -401,7 +399,7 @@ public void testListZones() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test not-retryable + assertFalse(ex.retryable()); } // ok size zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll()); @@ -413,7 +411,7 @@ public void testListZones() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test not-retryable + assertFalse(ex.retryable()); } // ok name zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName())).iterateAll()); @@ -586,6 +584,74 @@ public void testCreateChange() { } } + @Test + public void testInvalidChangeRequest() { + Zone zone = DNS.create(ZONE1); + DnsRecord validA = DnsRecord.builder("subdomain." + zone.dnsName(), DnsRecord.Type.A) + .records(ImmutableList.of("0.255.1.5")) + .build(); + try { + ChangeRequest validChange = ChangeRequest.builder().add(validA).build(); + zone.applyChangeRequest(validChange); + try { + zone.applyChangeRequest(validChange); + fail("Created a record which already exists."); + } catch (DnsException ex) { + // expected + assertFalse(ex.retryable()); + assertEquals(409, ex.code()); + } + // delete with field mismatch + DnsRecord mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); + ChangeRequest deletion = ChangeRequest.builder().delete(mismatch).build(); + try { + zone.applyChangeRequest(deletion); + fail("Deleted a record without a complete match."); + } catch (DnsException ex) { + // expected + assertEquals(412, ex.code()); + assertFalse(ex.retryable()); + } + // delete and add SOA + Iterator recordIterator = zone.listDnsRecords().iterateAll(); + LinkedList deletions = new LinkedList<>(); + LinkedList additions = new LinkedList<>(); + while (recordIterator.hasNext()) { + DnsRecord record = recordIterator.next(); + if (record.type() == DnsRecord.Type.SOA) { + deletions.add(record); + // the subdomain is necessary to get 400 instead of 412 + DnsRecord copy = record.toBuilder().name("x." + record.name()).build(); + additions.add(copy); + break; + } + } + deletion = deletion.toBuilder().deletions(deletions).build(); + ChangeRequest addition = ChangeRequest.builder().additions(additions).build(); + try { + zone.applyChangeRequest(deletion); + fail("Deleted SOA."); + } catch (DnsException ex) { + // expected + assertFalse(ex.retryable()); + assertEquals(400, ex.code()); + } + try { + zone.applyChangeRequest(addition); + fail("Added second SOA."); + } catch (DnsException ex) { + // expected + assertFalse(ex.retryable()); + assertEquals(400, ex.code()); + } + } finally { + ChangeRequest deletion = ChangeRequest.builder().delete(validA).build(); + ChangeRequest request = zone.applyChangeRequest(deletion); + waitForChangeToComplete(zone.name(), request.id()); + zone.delete(); + } + } + @Test public void testListChanges() { try { @@ -596,7 +662,7 @@ public void testListChanges() { } catch (DnsException ex) { // expected assertEquals(404, ex.code()); - // todo(mderka) test retry functionality + assertFalse(ex.retryable()); } // zone exists but has no changes DNS.create(ZONE1); @@ -621,7 +687,7 @@ public void testListChanges() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test retry functionality + assertFalse(ex.retryable()); } try { DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(-1)); @@ -629,7 +695,7 @@ public void testListChanges() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test retry functionality + assertFalse(ex.retryable()); } // sorting order ImmutableList ascending = ImmutableList.copyOf(DNS.listChangeRequests( @@ -863,7 +929,7 @@ public void testListDnsRecords() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available + assertFalse(ex.retryable()); } try { DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(0)); @@ -871,7 +937,7 @@ public void testListDnsRecords() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available + assertFalse(ex.retryable()); } try { DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(-1)); @@ -879,7 +945,7 @@ public void testListDnsRecords() { } catch (DnsException ex) { // expected assertEquals(400, ex.code()); - // todo(mderka) test retry functionality when available + assertFalse(ex.retryable()); } waitForChangeToComplete(ZONE1.name(), change.id()); } finally { From f7f4de852874b04e92cff4233dfa0f635c0792c2 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 1 Mar 2016 12:58:25 -0800 Subject: [PATCH 69/74] Added READMEs. This includes: - Package README - Adjusted global gcloud-java README - Package description - Reorganizing snippets to be consistent with readme --- README.md | 74 +++- gcloud-java-dns/README.md | 385 ++++++++++++++++++ .../com/google/gcloud/dns/package-info.java | 60 +++ .../com/google/gcloud/dns/it/ITDnsTest.java | 2 +- ...rds.java => CreateOrUpdateDnsRecords.java} | 9 +- ...reateAndListZones.java => CreateZone.java} | 23 +- .../examples/dns/snippets/DeleteZone.java | 2 +- .../snippets/ManipulateZonesAndRecords.java | 157 +++++++ 8 files changed, 688 insertions(+), 24 deletions(-) create mode 100644 gcloud-java-dns/README.md create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java rename gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/{CreateAndListDnsRecords.java => CreateOrUpdateDnsRecords.java} (89%) rename gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/{CreateAndListZones.java => CreateZone.java} (70%) create mode 100644 gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java diff --git a/README.md b/README.md index 32a0f539425e..a908cef0bf35 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ This client supports the following Google Cloud Platform services: - [Google Cloud BigQuery] (#google-cloud-bigquery-alpha) (Alpha) - [Google Cloud Datastore] (#google-cloud-datastore) +- [Google Cloud DNS] (#google-cloud-dns-alpha) (Alpha) - [Google Cloud Resource Manager] (#google-cloud-resource-manager-alpha) (Alpha) - [Google Cloud Storage] (#google-cloud-storage) @@ -48,8 +49,10 @@ 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 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). - [`SparkDemo`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/managed_vms/sparkjava) - An example of using gcloud-java-datastore from within the SparkJava and App Engine Managed VM frameworks. @@ -218,6 +221,71 @@ if (entity != null) { } ``` +Google Cloud DNS (Alpha) +---------------------- +- [API Documentation][dns-api] +- [Official Documentation][cloud-dns-docs] + +*Follow the [activation instructions][cloud-dns-activation] to use the Google Cloud DNS API with your project.* + +#### Preview + +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 +[CreateZone.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java). + +```java +import com.google.gcloud.dns.Dns; +import com.google.gcloud.dns.DnsOptions; +import com.google.gcloud.dns.Zone; +import com.google.gcloud.dns.ZoneInfo; + +Dns dns = DnsOptions.defaultInstance().service(); +String zoneName = "my-unique-zone"; +String domainName = "someexampledomain.com."; +String description = "This is a gcloud-java-dns sample zone."; +ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description); +Zone zone = dns.create(zoneInfo); +``` + +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; +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; + +Dns dns = DnsOptions.defaultInstance().service(); +String zoneName = "my-unique-zone"; +Zone zone = dns.getZone(zoneName); +String ip = "12.13.14.15"; +DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) + .ttl(24, TimeUnit.HOURS) + .addRecord(ip) + .build(); +ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); + +// Verify that the 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); + } +} + +ChangeRequest changeRequest = changeBuilder.build(); +zone.applyChangeRequest(changeRequest); +``` + Google Cloud Resource Manager (Alpha) ---------------------- @@ -359,6 +427,10 @@ Apache 2.0 - See [LICENSE] for more information. [cloud-datastore-activation]: https://cloud.google.com/datastore/docs/activate [datastore-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/datastore/package-summary.html +[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 + [cloud-pubsub]: https://cloud.google.com/pubsub/ [cloud-pubsub-docs]: https://cloud.google.com/pubsub/docs diff --git a/gcloud-java-dns/README.md b/gcloud-java-dns/README.md new file mode 100644 index 000000000000..4f65d8e3b814 --- /dev/null +++ b/gcloud-java-dns/README.md @@ -0,0 +1,385 @@ +Google Cloud Java Client for DNS +================================ + +Java idiomatic client for [Google Cloud DNS] (https://cloud.google.com/dns/). + +[![Build Status](https://travis-ci.org/GoogleCloudPlatform/gcloud-java.svg?branch=master)](https://travis-ci.org/GoogleCloudPlatform/gcloud-java) +[![Coverage Status](https://coveralls.io/repos/GoogleCloudPlatform/gcloud-java/badge.svg?branch=master)](https://coveralls.io/r/GoogleCloudPlatform/gcloud-java?branch=master) +[![Maven](https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-dns.svg)]( https://img.shields.io/maven-central/v/com.google.gcloud/gcloud-java-dns.svg) +[![Codacy Badge](https://api.codacy.com/project/badge/grade/9da006ad7c3a4fe1abd142e77c003917)](https://www.codacy.com/app/mziccard/gcloud-java) +[![Dependency Status](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969/badge.svg?style=flat)](https://www.versioneye.com/user/projects/56bd8ee72a29ed002d2b0969) + +- [Homepage] (https://googlecloudplatform.github.io/gcloud-java/) +- [API Documentation] (http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/dns/package-summary.html) + +> Note: This client is a work-in-progress, and may occasionally +> make backwards-incompatible changes. + +Quickstart +---------- +If you are using Maven, add this to your pom.xml file +```xml + + com.google.gcloud + gcloud-java-dns + 0.1.5 + +``` +If you are using Gradle, add this to your dependencies +```Groovy +compile 'com.google.gcloud:gcloud-java-dns:0.1.5' +``` +If you are using SBT, add this to your dependencies +```Scala +libraryDependencies += "com.google.gcloud" % "gcloud-java-dns" % "0.1.5" +``` + +Example Application +------------------- + +[`DnsExample`](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/DnsExample.java) +is a simple command line interface that provides some of Google Cloud DNS's functionality. Read +more about using the application on the +[`DnsExample` docs page](http://googlecloudplatform.github.io/gcloud-java/apidocs/?com/google/gcloud/examples/dns/DnsExample.html). + +Authentication +-------------- + +See the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication) section +in the base directory's README. + +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. + +See the [Google Cloud DNS docs][dns-activate] for more details on how to activate +Cloud DNS for your project. + +See the [``gcloud-java-dns`` API documentation][dns-api] to learn how to interact +with the Cloud DNS using this client Library. + +Getting Started +--------------- +#### Prerequisites +For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/) +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 +in command line: `gcloud auth login` and `gcloud config set project [YOUR PROJECT ID]`. + +#### Installation and setup +You'll need to obtain the `gcloud-java-dns` library. See the [Quickstart](#quickstart) section to +add `gcloud-java-dns` as a dependency in your code. + +#### Creating an authorized service object +To make authenticated requests to Google Cloud DNS, you must create a service object with +credentials. You can then make API calls by calling methods on the DNS service object. The simplest +way to authenticate is to use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials). +These credentials are automatically inferred from your environment, so you only need the following +code to create your service object: + +```java +import com.google.gcloud.dns.Dns; +import com.google.gcloud.dns.DnsOptions; + +Dns dns = DnsOptions.defaultInstance().service(); +``` + +For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication) page. + +#### 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. `Zone`, a subclass of `ZoneInfo`, adds service-related +functionality over `ZoneInfo`. + +*Important: Zone names 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 to manage DNS records 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.dns.Zone; +import com.google.gcloud.dns.ZoneInfo; +``` + +Then add the following code to create a zone. + +```java +// 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); +System.out.printf("Zone was created and assigned ID %s.%n", zone.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 +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 prints the list of servers +assigned to the zone created above. First, import + +```java +import java.util.List; +``` + +and then add + +```java +// Print assigned name servers +List nameServers = zone.nameServers(); +for(String nameServer : nameServers) { + System.out.println(nameServer); +} +``` + +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 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 + +```java +import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.DnsRecord; + +import java.util.concurrent.TimeUnit; +``` + +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(); + +// Make a change +ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build(); + +// Build and apply the change request to our zone +changeRequest = zone.applyChangeRequest(changeRequest); +``` + +The `addRecord` method 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 in your imports + +```java +import java.util.Iterator; +``` + +and in the code + +```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 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 +ChangeRequest changeRequest = changeBuilder.build(); +zone.applyChangeRequest(changeRequest); +``` +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: + +```java +while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + try { + Thread.sleep(500L); + } catch (InterruptedException e) { + System.err.println("The thread was interrupted while waiting..."); + } + changeRequest = dns.getChangeRequest(zone.name(), changeRequest.id()); +} +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. +See more on this topic [here](https://cloud.google.com/dns/monitoring). + +#### Listing Zones and DNS Records +Suppose that you have added more zones and DNS records, and now you want to list them. +First, import the following (unless you have done so in the previous section): + +```java +import java.util.Iterator; +``` + +Then add the following code to list all your zones and DNS records. + +```java +// List all your zones +Iterator zoneIterator = dns.listZones().iterateAll(); +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 +Iterator recordIterator = zone.listDnsRecords().iterateAll(); +System.out.println(String.format("DNS records inside %s:", zone.name())); +while (recordIterator.hasNext()) { + System.out.println(recordIterator.next()); +} +``` + +You can also list the history of change requests that were applied to a zone: + +```java +// List the change requests applied to a particular zone +Iterator changeIterator = zone.listChangeRequests().iterateAll(); +System.out.println(String.format("The history of changes in %s:", zone.name())); +while (changeIterator.hasNext()) { + System.out.println(changeIterator.next()); +} +``` + +#### Deleting Zones + +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 +// 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."); +} +``` + +#### Complete Source Code + +We composed some of the aforementioned snippets into complete executable code samples. In +[CreateZones.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.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 +demonstrate how to delete a zone in [DeleteZone.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java). +Finally, in [ManipulateZonesAndRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java) +we assemble all the code snippets together and create zone, create or update a DNS record, list zones, list DNS records, list changes, and +delete a zone. The applications assume that they are running on Compute Engine or from your own desktop. To run any of these examples on App +Engine, simply move the code from the main method to your application's servlet class and change the +print statements to display on your webpage. + +Troubleshooting +--------------- + +To get help, follow the `gcloud-java` links in the `gcloud-*` [shared Troubleshooting document](https://github.com/GoogleCloudPlatform/gcloud-common/blob/master/troubleshooting/readme.md#troubleshooting). + +Java Versions +------------- + +Java 7 or above is required for using this client. + +Testing +------- + +This library has tools to help make tests for code using Cloud DNS. + +See [TESTING] to read more about testing. + +Versioning +---------- + +This library follows [Semantic Versioning] (http://semver.org/). + +It is currently in major version zero (``0.y.z``), which means that anything +may change at any time and the public API should not be considered +stable. + +Contributing +------------ + +Contributions to this library are always welcome and highly encouraged. + +See `gcloud-java`'s [CONTRIBUTING] documentation and the `gcloud-*` [shared documentation](https://github.com/GoogleCloudPlatform/gcloud-common/blob/master/contributing/readme.md#how-to-contribute-to-gcloud) for more information on how to get started. + +Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See [Code of Conduct][code-of-conduct] for more information. + +License +------- + +Apache 2.0 - See [LICENSE] for more information. + + +[CONTRIBUTING]:https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/CONTRIBUTING.md +[code-of-conduct]:https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/CODE_OF_CONDUCT.md#contributor-code-of-conduct +[LICENSE]: https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/LICENSE +[TESTING]: https://github.com/GoogleCloudPlatform/gcloud-java/blob/master/TESTING.md#testing-code-that-uses-storage +[cloud-platform]: https://cloud.google.com/ + +[cloud-dns]: https://cloud.google.com/dns/ +[dns-api]: http://googlecloudplatform.github.io/gcloud-java/apidocs/index.html?com/google/gcloud/dns/package-summary.html +[dns-activate]:https://cloud.google.com/dns/getting-started#prerequisites diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java new file mode 100644 index 000000000000..8a137285c357 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +/** + * A client to the Google Cloud DNS. + * + *

    Here are two simple usage examples from within Compute/App Engine. + * + * The first snippet shows how to create a zone resource. The complete source code can be found on + * + * CreateAndListZones.java. Note that you need to replace the {@code domainName} with a domain + * name that you own and the ownership of which you verified with Google. + * + *

     {@code
    + * Dns dns = DnsOptions.defaultInstance().service();
    + * String zoneName = "my-unique-zone";
    + * String domainName = "someexampledomain.com.";
    + * String description = "This is a gcloud-java-dns sample zone.";
    + * ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description);
    + * Zone createdZone = dns.create(zoneInfo);
    + * } 
    + * + *

    The second example shows how to create records inside a zone. The complete code can be found + * on + * CreateAndListDnsRecords.java. + * + *

     {@code
    + * Dns dns = DnsOptions.defaultInstance().service();
    + * String zoneName = "my-unique-zone";
    + * Zone zone = dns.getZone(zoneName);
    + * String ip = "12.13.14.15";
    + * DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A)
    + *   .ttl(24, TimeUnit.HOURS)
    + *   .addRecord(ip)
    + *   .build();
    + * ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build();
    + * zone.applyChangeRequest(changeRequest);
    + * } 
    + * + *

    When using gcloud-java from outside of App/Compute Engine, you have to specify a + * project ID and provide + * credentials. + * + * @see Google Cloud DNS + */ +package com.google.gcloud.dns; diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index e1a7c218c1b4..bfea46dfe039 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -49,7 +49,7 @@ public class ITDnsTest { private static final String PREFIX = "gcldjvit-"; - private static final Dns DNS = DnsOptions.builder().build().service(); + private static final Dns DNS = DnsOptions.defaultInstance().service(); private static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32); private static final String ZONE_NAME_EMPTY_DESCRIPTION = (PREFIX + UUID.randomUUID()).substring(0, 32); 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/CreateOrUpdateDnsRecords.java similarity index 89% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListDnsRecords.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java index 1e47a12fed02..71327ba98a96 100644 --- 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/CreateOrUpdateDnsRecords.java @@ -32,9 +32,9 @@ import java.util.concurrent.TimeUnit; /** - * A snippet for Google Cloud DNS showing how to create a DNS records. + * A snippet for Google Cloud DNS showing how to create and update a DNS record. */ -public class CreateAndListDnsRecords { +public class CreateOrUpdateDnsRecords { public static void main(String... args) { // Create a service object. @@ -42,7 +42,7 @@ public static void main(String... args) { Dns dns = DnsOptions.defaultInstance().service(); // Change this to a zone name that exists within your project - String zoneName = "some-sample-zone"; + String zoneName = "my-unique-zone"; // Get zone from the service Zone zone = dns.getZone(zoneName); @@ -68,6 +68,7 @@ public static void main(String... args) { } // Build and apply the change request to our zone - zone.applyChangeRequest(changeBuilder.build()); + ChangeRequest changeRequest = changeBuilder.build(); + zone.applyChangeRequest(changeRequest); } } 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/CreateZone.java similarity index 70% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateAndListZones.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.java index 21fdba2b7449..2c2ba211bd86 100644 --- 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/CreateZone.java @@ -27,14 +27,11 @@ 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. + * A snippet for Google Cloud DNS showing how to create a zone. 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 class CreateZone { public static void main(String... args) { // Create a service object @@ -42,21 +39,13 @@ public static void main(String... args) { 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 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++; - } + Zone zone = dns.create(zoneInfo); + System.out.printf("Zone was created and assigned ID %s.%n", zone.id()); } } 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 index 667a0d89e6ab..e841a4cd54ed 100644 --- 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 @@ -41,7 +41,7 @@ public static void main(String... args) { 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"; + String zoneName = "my-unique-zone"; // Get iterator for the existing records which have to be deleted before deleting the zone Iterator recordIterator = dns.listDnsRecords(zoneName).iterateAll(); diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java new file mode 100644 index 000000000000..4de262386d53 --- /dev/null +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java @@ -0,0 +1,157 @@ +/* + * 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 com.google.gcloud.dns.ZoneInfo; + +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * A complete snippet for Google Cloud DNS showing how to create and delete a zone. It also shows + * how to create, list and delete DNS records, and how to list changes. + */ +public class ManipulateZonesAndRecords { + + public static void main(String... args) { + 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 zone = dns.create(zoneInfo); + System.out.printf("Zone was created and assigned ID %s.%n", zone.id()); + + // Print assigned name servers + List nameServers = zone.nameServers(); + for (String nameServer : nameServers) { + System.out.println(nameServer); + } + + // 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(); + + // 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 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 + ChangeRequest changeRequest = changeBuilder.build(); + zone.applyChangeRequest(changeRequest); + + while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + try { + Thread.sleep(500L); + } catch (InterruptedException e) { + System.err.println("The thread was interrupted while waiting..."); + } + changeRequest = dns.getChangeRequest(zone.name(), changeRequest.id()); + } + System.out.println("The change request has been applied."); + + // List all your zones + Iterator zoneIterator = dns.listZones().iterateAll(); + 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 + recordIterator = zone.listDnsRecords().iterateAll(); + System.out.println(String.format("DNS records inside %s:", zone.name())); + while (recordIterator.hasNext()) { + System.out.println(recordIterator.next()); + } + + // List the change requests applied to a particular zone + Iterator changeIterator = zone.listChangeRequests().iterateAll(); + System.out.println(String.format("The history of changes in %s:", zone.name())); + while (changeIterator.hasNext()) { + System.out.println(changeIterator.next()); + } + + // Make a change for deleting the records + 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 = 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."); + } + } +} From e946b76d00bd174c9d0fd767915b3c2808e10e0f Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 23 Mar 2016 13:16:21 -0700 Subject: [PATCH 70/74] Updated the version in pom. --- gcloud-java-dns/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gcloud-java-dns/pom.xml b/gcloud-java-dns/pom.xml index 1a559473cc82..a690a1e509a7 100644 --- a/gcloud-java-dns/pom.xml +++ b/gcloud-java-dns/pom.xml @@ -13,7 +13,7 @@ com.google.gcloud gcloud-java-pom - 0.1.5-SNAPSHOT + 0.1.6-SNAPSHOT gcloud-java-dns From 5c3fc94f60391db0c32b6d8055101c0abb9bd0e9 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Wed, 23 Mar 2016 12:43:05 -0700 Subject: [PATCH 71/74] Refactored the serialization test to use the base test --- gcloud-java-dns/pom.xml | 7 +++ .../google/gcloud/dns/SerializationTest.java | 50 +++++++------------ 2 files changed, 25 insertions(+), 32 deletions(-) diff --git a/gcloud-java-dns/pom.xml b/gcloud-java-dns/pom.xml index a690a1e509a7..b55200b8fc7d 100644 --- a/gcloud-java-dns/pom.xml +++ b/gcloud-java-dns/pom.xml @@ -40,6 +40,13 @@ + + ${project.groupId} + gcloud-java-core + ${project.version} + test-jar + test + junit junit diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java index c2bf9cfca0bb..7a0c32036878 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -16,24 +16,17 @@ package com.google.gcloud.dns; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - import com.google.common.collect.ImmutableList; +import com.google.gcloud.AuthCredentials; +import com.google.gcloud.BaseSerializationTest; +import com.google.gcloud.Restorable; import com.google.gcloud.RetryParams; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigInteger; import java.util.concurrent.TimeUnit; -public class SerializationTest { +public class SerializationTest extends BaseSerializationTest { private static final ZoneInfo FULL_ZONE_INFO = Zone.of("some zone name", "www.example.com", "some descriptions").toBuilder() @@ -86,31 +79,24 @@ public class SerializationTest { .startTimeMillis(132L) .build(); - @Test - public void testModelAndRequests() throws Exception { - Serializable[] objects = {FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, + @Override + protected Serializable[] serializableObjects() { + DnsOptions options = DnsOptions.builder() + .authCredentials(AuthCredentials.createForAppEngine()) + .projectId("id1") + .build(); + DnsOptions otherOptions = options.toBuilder() + .authCredentials(null) + .build(); + return new Serializable[]{FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, DNS_REOCRD_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, PROJECT_OPTION, PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, OPTIONS, FULL_ZONE, PARTIAL_ZONE, OPTIONS, CHANGE_REQUEST_PARTIAL, DNS_RECORD_PARTIAL, DNS_RECORD_COMPLETE, - CHANGE_REQUEST_COMPLETE}; - for (Serializable obj : objects) { - Object copy = serializeAndDeserialize(obj); - assertEquals(obj, obj); - assertEquals(obj, copy); - assertNotSame(obj, copy); - assertEquals(copy, copy); - } + CHANGE_REQUEST_COMPLETE, options, otherOptions}; } - @SuppressWarnings("unchecked") - private T serializeAndDeserialize(T obj) throws IOException, ClassNotFoundException { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { - output.writeObject(obj); - } - try (ObjectInputStream input = - new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { - return (T) input.readObject(); - } + @Override + protected Restorable[] restorableObjects() { + return new Restorable[0]; } } From 1a5aade24d7cf0b7d0ee64eb80c3726174800446 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Tue, 22 Mar 2016 17:08:11 -0700 Subject: [PATCH 72/74] Renamed DnsRecord to RecordSet. Fixes #779. --- README.md | 12 +- gcloud-java-dns/README.md | 70 ++++---- .../com/google/gcloud/dns/ChangeRequest.java | 62 +++---- .../main/java/com/google/gcloud/dns/Dns.java | 67 +++---- .../java/com/google/gcloud/dns/DnsImpl.java | 26 +-- .../com/google/gcloud/dns/ProjectInfo.java | 23 +-- .../dns/{DnsRecord.java => RecordSet.java} | 56 +++--- .../main/java/com/google/gcloud/dns/Zone.java | 14 +- .../com/google/gcloud/dns/package-info.java | 2 +- .../google/gcloud/dns/spi/DefaultDnsRpc.java | 2 +- .../com/google/gcloud/dns/spi/DnsRpc.java | 4 +- .../gcloud/dns/testing/LocalDnsHelper.java | 44 ++--- .../gcloud/dns/testing/OptionParsers.java | 12 +- .../google/gcloud/dns/ChangeRequestTest.java | 22 +-- .../com/google/gcloud/dns/DnsImplTest.java | 36 ++-- .../java/com/google/gcloud/dns/DnsTest.java | 48 ++--- ...{DnsRecordTest.java => RecordSetTest.java} | 75 ++++---- .../google/gcloud/dns/SerializationTest.java | 20 +-- .../java/com/google/gcloud/dns/ZoneTest.java | 42 ++--- .../com/google/gcloud/dns/it/ITDnsTest.java | 170 +++++++++--------- .../dns/testing/LocalDnsHelperTest.java | 44 ++--- gcloud-java-examples/README.md | 2 +- .../gcloud/examples/dns/DnsExample.java | 36 ++-- ...rds.java => CreateOrUpdateRecordSets.java} | 16 +- .../examples/dns/snippets/DeleteZone.java | 10 +- ...java => ManipulateZonesAndRecordSets.java} | 32 ++-- 26 files changed, 477 insertions(+), 470 deletions(-) rename gcloud-java-dns/src/main/java/com/google/gcloud/dns/{DnsRecord.java => RecordSet.java} (83%) rename gcloud-java-dns/src/test/java/com/google/gcloud/dns/{DnsRecordTest.java => RecordSetTest.java} (63%) rename gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/{CreateOrUpdateDnsRecords.java => CreateOrUpdateRecordSets.java} (83%) rename gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/{ManipulateZonesAndRecords.java => ManipulateZonesAndRecordSets.java} (84%) diff --git a/README.md b/README.md index a753a96c8b21..52229f6d5d34 100644 --- a/README.md +++ b/README.md @@ -249,13 +249,13 @@ ZoneInfo zoneInfo = ZoneInfo.of(zoneName, domainName, description); Zone zone = dns.create(zoneInfo); ``` -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). +The second snippet shows how to create records inside a zone. The complete code can be found on [CreateOrUpdateRecordSets.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java). ```java 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.RecordSet; import com.google.gcloud.dns.Zone; import java.util.Iterator; @@ -265,7 +265,7 @@ Dns dns = DnsOptions.defaultInstance().service(); String zoneName = "my-unique-zone"; Zone zone = dns.getZone(zoneName); String ip = "12.13.14.15"; -DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) +RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); @@ -273,9 +273,9 @@ ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); // Verify that the 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(); +Iterator recordSetIterator = zone.listRecordSets().iterateAll(); +while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); diff --git a/gcloud-java-dns/README.md b/gcloud-java-dns/README.md index 4f65d8e3b814..a2c3238d1f8f 100644 --- a/gcloud-java-dns/README.md +++ b/gcloud-java-dns/README.md @@ -92,7 +92,7 @@ Dns dns = DnsOptions.defaultInstance().service(); For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication) page. #### Managing Zones -DNS records in `gcloud-java-dns` are managed inside containers called "zones". `ZoneInfo` is a class +Record sets 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. `Zone`, a subclass of `ZoneInfo`, adds service-related functionality over `ZoneInfo`. @@ -100,7 +100,7 @@ functionality over `ZoneInfo`. 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 to manage DNS records for domain `someexampledomain.com.` +In this code snippet, we create a new zone to manage record sets 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 @@ -128,8 +128,8 @@ Zone zone = dns.create(zoneInfo); System.out.printf("Zone was created and assigned ID %s.%n", zone.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 +You now have an empty zone hosted in Google Cloud DNS which is ready to be populated with +record sets for domain name `someexampledomain.com.` Upon creating the zone, the cloud service 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 prints the list of servers assigned to the zone created above. First, import @@ -152,15 +152,15 @@ You can now instruct your domain registrar to [update your domain 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 a zone, we can add some DNS records. The DNS records held within zones are +#### Creating Record Sets +Now that we have a zone, we can add some record sets. The record sets 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 +our zone that creates a record set of type A and points URL www.someexampledomain.com to IP address 12.13.14.15. Start by adding ```java import com.google.gcloud.dns.ChangeRequest; -import com.google.gcloud.dns.DnsRecord; +import com.google.gcloud.dns.RecordSet; import java.util.concurrent.TimeUnit; ``` @@ -168,9 +168,9 @@ import java.util.concurrent.TimeUnit; and proceed with: ```java -// Prepare a www.someexampledomain.com. type A record with ttl of 24 hours +// Prepare a www.someexampledomain.com. type A record set with ttl of 24 hours String ip = "12.13.14.15"; -DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) +RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); @@ -182,12 +182,12 @@ ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build(); changeRequest = zone.applyChangeRequest(changeRequest); ``` -The `addRecord` method 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). +The `addRecord` method of `RecordSet.Builder` accepts records in the form of +strings. The format of the strings depends on the type of the record sets to be added. +More information on the supported record set 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 +If you already have a record set, Cloud DNS will return an error upon an attempt to create a duplicate of it. +You can modify the code above to create a record set or update it if it already exists by making the following adjustment in your imports ```java @@ -202,9 +202,9 @@ 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 recordIterator = zone.listDnsRecords().iterateAll(); -while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); +Iterator recordSetIterator = zone.listRecordSets().iterateAll(); +while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } @@ -235,15 +235,15 @@ Change requests are applied atomically to all the assigned DNS servers at once. 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 have added more zones and DNS records, and now you want to list them. +#### Listing Zones and Record Sets +Suppose that you have added more zones and record sets, and now you want to list them. First, import the following (unless you have done so in the previous section): ```java import java.util.Iterator; ``` -Then add the following code to list all your zones and DNS records. +Then add the following code to list all your zones and record sets. ```java // List all your zones @@ -254,11 +254,11 @@ while (zoneIterator.hasNext()) { counter++; } -// List the DNS records in a particular zone -Iterator recordIterator = zone.listDnsRecords().iterateAll(); -System.out.println(String.format("DNS records inside %s:", zone.name())); -while (recordIterator.hasNext()) { - System.out.println(recordIterator.next()); +// List the record sets in a particular zone +recordSetIterator = zone.listRecordSets().iterateAll(); +System.out.println(String.format("Record sets inside %s:", zone.name())); +while (recordSetIterator.hasNext()) { + System.out.println(recordSetIterator.next()); } ``` @@ -276,15 +276,15 @@ while (changeIterator.hasNext()) { #### Deleting Zones 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. +First, you need to empty the zone by deleting all its records except for the default SOA and NS record sets. ```java -// Make a change for deleting the records -ChangeRequest.Builder changeBuilder = ChangeRequest.builder(); +// Make a change for deleting the record sets +changeBuilder = ChangeRequest.builder(); while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted - if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { changeBuilder.delete(current); } } @@ -324,11 +324,11 @@ if (result) { We composed some of the aforementioned snippets into complete executable code samples. In [CreateZones.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateZone.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 +we create a zone. In [CreateOrUpdateRecordSets.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java) +we create a type A record set for a zone, or update an existing type A record set to a new IP address. We demonstrate how to delete a zone in [DeleteZone.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/DeleteZone.java). -Finally, in [ManipulateZonesAndRecords.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java) -we assemble all the code snippets together and create zone, create or update a DNS record, list zones, list DNS records, list changes, and +Finally, in [ManipulateZonesAndRecordSets.java](../gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java) +we assemble all the code snippets together and create zone, create or update a record set, list zones, list record sets, list changes, and delete a zone. The applications assume that they are running on Compute Engine or from your own desktop. To run any of these examples on App Engine, simply move the code from the main method to your application's servlet class and change the print statements to display on your webpage. diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index 76d231b704c4..757d844cc3da 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -33,7 +33,7 @@ import java.util.Objects; /** - * A class representing an atomic update to a collection of {@link DnsRecord}s within a {@code + * A class representing an atomic update to a collection of {@link RecordSet}s within a {@code * Zone}. * * @see Google Cloud DNS documentation @@ -48,8 +48,8 @@ public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { } }; private static final long serialVersionUID = -9027378042756366333L; - private final List additions; - private final List deletions; + private final List additions; + private final List deletions; private final String id; private final Long startTimeMillis; private final Status status; @@ -70,8 +70,8 @@ public enum Status { */ public static class Builder { - private List additions = new LinkedList<>(); - private List deletions = new LinkedList<>(); + private List additions = new LinkedList<>(); + private List deletions = new LinkedList<>(); private String id; private Long startTimeMillis; private Status status; @@ -88,43 +88,43 @@ private Builder() { } /** - * Sets a collection of {@link DnsRecord}s which are to be added to the zone upon executing this + * Sets a collection of {@link RecordSet}s which are to be added to the zone upon executing this * {@code ChangeRequest}. */ - public Builder additions(List additions) { + public Builder additions(List additions) { this.additions = Lists.newLinkedList(checkNotNull(additions)); return this; } /** - * Sets a collection of {@link DnsRecord}s which are to be deleted from the zone upon executing + * Sets a collection of {@link RecordSet}s which are to be deleted from the zone upon executing * this {@code ChangeRequest}. */ - public Builder deletions(List deletions) { + public Builder deletions(List deletions) { this.deletions = Lists.newLinkedList(checkNotNull(deletions)); return this; } /** - * Adds a {@link DnsRecord} to be added to the zone upon executing this {@code + * Adds a {@link RecordSet} to be added to the zone upon executing this {@code * ChangeRequest}. */ - public Builder add(DnsRecord record) { - this.additions.add(checkNotNull(record)); + public Builder add(RecordSet recordSet) { + this.additions.add(checkNotNull(recordSet)); return this; } /** - * Adds a {@link DnsRecord} to be deleted to the zone upon executing this + * Adds a {@link RecordSet} to be deleted to the zone upon executing this * {@code ChangeRequest}. */ - public Builder delete(DnsRecord record) { - this.deletions.add(checkNotNull(record)); + public Builder delete(RecordSet recordSet) { + this.deletions.add(checkNotNull(recordSet)); return this; } /** - * Clears the collection of {@link DnsRecord}s which are to be added to the zone upon executing + * Clears the collection of {@link RecordSet}s which are to be added to the zone upon executing * this {@code ChangeRequest}. */ public Builder clearAdditions() { @@ -133,7 +133,7 @@ public Builder clearAdditions() { } /** - * Clears the collection of {@link DnsRecord}s which are to be deleted from the zone upon + * Clears the collection of {@link RecordSet}s which are to be deleted from the zone upon * executing this {@code ChangeRequest}. */ public Builder clearDeletions() { @@ -142,20 +142,20 @@ public Builder clearDeletions() { } /** - * Removes a single {@link DnsRecord} from the collection of records to be + * Removes a single {@link RecordSet} from the collection of records to be * added to the zone upon executing this {@code ChangeRequest}. */ - public Builder removeAddition(DnsRecord record) { - this.additions.remove(record); + public Builder removeAddition(RecordSet recordSet) { + this.additions.remove(recordSet); return this; } /** - * Removes a single {@link DnsRecord} from the collection of records to be + * Removes a single {@link RecordSet} from the collection of records to be * deleted from the zone upon executing this {@code ChangeRequest}. */ - public Builder removeDeletion(DnsRecord record) { - this.deletions.remove(record); + public Builder removeDeletion(RecordSet recordSet) { + this.deletions.remove(recordSet); return this; } @@ -215,18 +215,18 @@ public Builder toBuilder() { } /** - * Returns the list of {@link DnsRecord}s to be added to the zone upon submitting this {@code + * Returns the list of {@link RecordSet}s to be added to the zone upon submitting this {@code * ChangeRequest}. */ - public List additions() { + public List additions() { return additions; } /** - * Returns the list of {@link DnsRecord}s to be deleted from the zone upon submitting this {@code + * Returns the list of {@link RecordSet}s to be deleted from the zone upon submitting this {@code * ChangeRequest}. */ - public List deletions() { + public List deletions() { return deletions; } @@ -267,9 +267,9 @@ com.google.api.services.dns.model.Change toPb() { pb.setStatus(status().name().toLowerCase()); } // set a list of additions - pb.setAdditions(Lists.transform(additions(), DnsRecord.TO_PB_FUNCTION)); + pb.setAdditions(Lists.transform(additions(), RecordSet.TO_PB_FUNCTION)); // set a list of deletions - pb.setDeletions(Lists.transform(deletions(), DnsRecord.TO_PB_FUNCTION)); + pb.setDeletions(Lists.transform(deletions(), RecordSet.TO_PB_FUNCTION)); return pb; } @@ -286,10 +286,10 @@ static ChangeRequest fromPb(com.google.api.services.dns.model.Change pb) { builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); } if (pb.getDeletions() != null) { - builder.deletions(Lists.transform(pb.getDeletions(), DnsRecord.FROM_PB_FUNCTION)); + builder.deletions(Lists.transform(pb.getDeletions(), RecordSet.FROM_PB_FUNCTION)); } if (pb.getAdditions() != null) { - builder.additions(Lists.transform(pb.getAdditions(), DnsRecord.FROM_PB_FUNCTION)); + builder.additions(Lists.transform(pb.getAdditions(), RecordSet.FROM_PB_FUNCTION)); } return builder.build(); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index 6ce6b4c19994..f8614a8d6169 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -101,13 +101,13 @@ static String selector(ZoneField... fields) { } /** - * The fields of a DNS record. + * The fields of a record set. * *

    These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#listDnsRecords(String, DnsRecordListOption...)}. The name and type are always + * {@link Dns#listRecordSets(String, RecordSetListOption...)}. The name and type are always * returned even if not selected. */ - enum DnsRecordField { + enum RecordSetField { DNS_RECORDS("rrdatas"), NAME("name"), TTL("ttl"), @@ -115,7 +115,7 @@ enum DnsRecordField { private final String selector; - DnsRecordField(String selector) { + RecordSetField(String selector) { this.selector = selector; } @@ -123,11 +123,11 @@ String selector() { return selector; } - static String selector(DnsRecordField... fields) { + static String selector(RecordSetField... fields) { Set fieldStrings = Sets.newHashSetWithExpectedSize(fields.length + 1); fieldStrings.add(NAME.selector()); fieldStrings.add(TYPE.selector()); - for (DnsRecordField field : fields) { + for (RecordSetField field : fields) { fieldStrings.add(field.selector()); } return Joiner.on(',').join(fieldStrings); @@ -180,28 +180,29 @@ public String selector() { } /** - * Class that for specifying DNS record options. + * Class for specifying record set listing options. */ - class DnsRecordListOption extends AbstractOption implements Serializable { + class RecordSetListOption extends AbstractOption implements Serializable { private static final long serialVersionUID = 1009627025381096098L; - DnsRecordListOption(DnsRpc.Option option, Object value) { + RecordSetListOption(DnsRpc.Option option, Object value) { super(option, value); } /** - * Returns an option to specify the DNS record's fields to be returned by the RPC call. + * Returns an option to specify the record set's fields to be returned by the RPC call. * *

    If this option is not provided all record fields are returned. {@code - * DnsRecordField.fields} can be used to specify only the fields of interest. The name of the - * DNS record always returned, even if not specified. {@link DnsRecordField} provides a list of - * fields that can be used. + * RecordSetField.fields} can be used to specify only the fields of interest. The name of the + * record set in always returned, even if not specified. {@link RecordSetField} provides a list + * of fields that can be used. */ - public static DnsRecordListOption fields(DnsRecordField... fields) { + public static RecordSetListOption fields(RecordSetField... fields) { StringBuilder builder = new StringBuilder(); - builder.append("nextPageToken,rrsets(").append(DnsRecordField.selector(fields)).append(')'); - return new DnsRecordListOption(DnsRpc.Option.FIELDS, builder.toString()); + builder.append("nextPageToken,rrsets(").append(RecordSetField.selector(fields)) + .append(')'); + return new RecordSetListOption(DnsRpc.Option.FIELDS, builder.toString()); } /** @@ -210,33 +211,33 @@ public static DnsRecordListOption fields(DnsRecordField... fields) { *

    The page token (returned from a previous call to list) indicates from where listing should * continue. */ - public static DnsRecordListOption pageToken(String pageToken) { - return new DnsRecordListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); + public static RecordSetListOption pageToken(String pageToken) { + return new RecordSetListOption(DnsRpc.Option.PAGE_TOKEN, pageToken); } /** - * The maximum number of DNS records to return per RPC. + * The maximum number of record sets to return per RPC. * - *

    The server can return fewer records than requested. When there are more results than the - * page size, the server will return a page token that can be used to fetch other results. + *

    The server can return fewer record sets than requested. When there are more results than + * the page size, the server will return a page token that can be used to fetch other results. */ - public static DnsRecordListOption pageSize(int pageSize) { - return new DnsRecordListOption(DnsRpc.Option.PAGE_SIZE, pageSize); + public static RecordSetListOption pageSize(int pageSize) { + return new RecordSetListOption(DnsRpc.Option.PAGE_SIZE, pageSize); } /** - * Restricts the list to only DNS records with this fully qualified domain name. + * Restricts the list to only record sets with this fully qualified domain name. */ - public static DnsRecordListOption dnsName(String dnsName) { - return new DnsRecordListOption(DnsRpc.Option.NAME, dnsName); + public static RecordSetListOption dnsName(String dnsName) { + return new RecordSetListOption(DnsRpc.Option.NAME, dnsName); } /** - * Restricts the list to return only records of this type. If present, {@link - * Dns.DnsRecordListOption#dnsName(String)} must also be present. + * Restricts the list to return only record sets of this type. If present, {@link + * RecordSetListOption#dnsName(String)} must also be present. */ - public static DnsRecordListOption type(DnsRecord.Type type) { - return new DnsRecordListOption(DnsRpc.Option.DNS_TYPE, type.name()); + public static RecordSetListOption type(RecordSet.Type type) { + return new RecordSetListOption(DnsRpc.Option.DNS_TYPE, type.name()); } } @@ -478,16 +479,16 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { boolean delete(String zoneName); // delete does not admit any options /** - * Lists the DNS records in the zone identified by name. + * Lists the record sets in the zone identified by name. * *

    The fields to be returned, page size and page tokens can be specified using {@link - * DnsRecordListOption}s. + * RecordSetListOption}s. * * @throws DnsException upon failure or if the zone cannot be found * @see Cloud DNS * ResourceRecordSets: list */ - Page listDnsRecords(String zoneName, DnsRecordListOption... options); + Page listRecordSets(String zoneName, RecordSetListOption... options); /** * Retrieves the information about the current project. The returned fields can be optionally diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index a60cfd9151da..2fbf4e8b5a79 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -85,7 +85,7 @@ public Page nextPage() { } } - private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher { + private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher { private static final long serialVersionUID = -6039369212511530846L; private final Map requestOptions; @@ -101,8 +101,8 @@ private static class DnsRecordPageFetcher implements PageImpl.NextPageFetcher nextPage() { - return listDnsRecords(zoneName, serviceOptions, requestOptions); + public Page nextPage() { + return listRecordSets(zoneName, serviceOptions, requestOptions); } } @@ -178,29 +178,29 @@ public DnsRpc.ListResult call() { } @Override - public Page listDnsRecords(String zoneName, DnsRecordListOption... options) { - return listDnsRecords(zoneName, options(), optionMap(options)); + public Page listRecordSets(String zoneName, RecordSetListOption... options) { + return listRecordSets(zoneName, options(), optionMap(options)); } - private static Page listDnsRecords(final String zoneName, + private static Page listRecordSets(final String zoneName, final DnsOptions serviceOptions, final Map optionsMap) { try { - // get a list of resource record sets + // get a list of record sets final DnsRpc rpc = serviceOptions.rpc(); DnsRpc.ListResult result = runWithRetries( new Callable>() { @Override public DnsRpc.ListResult call() { - return rpc.listDnsRecords(zoneName, optionsMap); + return rpc.listRecordSets(zoneName, optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER); String cursor = result.pageToken(); - // transform that list into dns records - Iterable records = result.results() == null - ? ImmutableList.of() - : Iterables.transform(result.results(), DnsRecord.FROM_PB_FUNCTION); + // transform that list into record sets + Iterable recordSets = result.results() == null + ? ImmutableList.of() + : Iterables.transform(result.results(), RecordSet.FROM_PB_FUNCTION); return new PageImpl<>(new DnsRecordPageFetcher(zoneName, serviceOptions, cursor, optionsMap), - cursor, records); + cursor, recordSets); } catch (RetryHelperException e) { throw DnsException.translateAndThrow(e); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java index f7b12b94bae8..319f06ad2444 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ProjectInfo.java @@ -26,8 +26,8 @@ /** * The class provides the Google Cloud DNS information associated with this project. A project is a - * top level container for resources including {@code Zone}s. Projects can be created only in - * the APIs console. + * top level container for resources including {@code Zone}s. Projects can be created only in the + * APIs console. * * @see Google Cloud DNS documentation */ @@ -62,11 +62,11 @@ public static class Quota implements Serializable { * builder. */ Quota(int zones, - int resourceRecordsPerRrset, - int rrsetAdditionsPerChange, - int rrsetDeletionsPerChange, - int rrsetsPerZone, - int totalRrdataSizePerChange) { + int resourceRecordsPerRrset, + int rrsetAdditionsPerChange, + int rrsetDeletionsPerChange, + int rrsetsPerZone, + int totalRrdataSizePerChange) { this.zones = zones; this.resourceRecordsPerRrset = resourceRecordsPerRrset; this.rrsetAdditionsPerChange = rrsetAdditionsPerChange; @@ -83,21 +83,22 @@ public int zones() { } /** - * Returns the maximum allowed number of records per {@link DnsRecord}. + * Returns the maximum allowed number of records per {@link RecordSet}. */ public int resourceRecordsPerRrset() { return resourceRecordsPerRrset; } /** - * Returns the maximum allowed number of {@link DnsRecord}s to add per {@link ChangeRequest}. + * Returns the maximum allowed number of {@link RecordSet}s to add per {@link + * ChangeRequest}. */ public int rrsetAdditionsPerChange() { return rrsetAdditionsPerChange; } /** - * Returns the maximum allowed number of {@link DnsRecord}s to delete per {@link + * Returns the maximum allowed number of {@link RecordSet}s to delete per {@link * ChangeRequest}. */ public int rrsetDeletionsPerChange() { @@ -105,7 +106,7 @@ public int rrsetDeletionsPerChange() { } /** - * Returns the maximum allowed number of {@link DnsRecord}s per {@link ZoneInfo} in the + * Returns the maximum allowed number of {@link RecordSet}s per {@link ZoneInfo} in the * project. */ public int rrsetsPerZone() { diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/RecordSet.java similarity index 83% rename from gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java rename to gcloud-java-dns/src/main/java/com/google/gcloud/dns/RecordSet.java index c4e710bd0365..dc6d956406c3 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsRecord.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/RecordSet.java @@ -35,28 +35,28 @@ /** * A class that represents a Google Cloud DNS record set. * - *

    A {@code DnsRecord} is the unit of data that will be returned by the DNS servers upon a DNS - * request for a specific domain. The {@code DnsRecord} holds the current state of the DNS records + *

    A {@code RecordSet} is the unit of data that will be returned by the DNS servers upon a DNS + * request for a specific domain. The {@code RecordSet} holds the current state of the DNS records * that make up a zone. You can read the records but you cannot modify them directly. Rather, you - * edit the records in a zone by creating a ChangeRequest. + * edit the records in a zone by creating a {@link ChangeRequest}. * * @see Google Cloud DNS * documentation */ -public class DnsRecord implements Serializable { +public class RecordSet implements Serializable { - static final Function FROM_PB_FUNCTION = - new Function() { + static final Function FROM_PB_FUNCTION = + new Function() { @Override - public DnsRecord apply(com.google.api.services.dns.model.ResourceRecordSet pb) { - return DnsRecord.fromPb(pb); + public RecordSet apply(ResourceRecordSet pb) { + return RecordSet.fromPb(pb); } }; - static final Function TO_PB_FUNCTION = - new Function() { + static final Function TO_PB_FUNCTION = + new Function() { @Override - public com.google.api.services.dns.model.ResourceRecordSet apply(DnsRecord error) { - return error.toPb(); + public ResourceRecordSet apply(RecordSet recordSet) { + return recordSet.toPb(); } }; private static final long serialVersionUID = 8148009870800115261L; @@ -124,7 +124,7 @@ public enum Type { } /** - * A builder of {@link DnsRecord}. + * A builder for {@link RecordSet}. */ public static class Builder { @@ -140,9 +140,9 @@ private Builder(String name, Type type) { /** * Creates a builder and pre-populates attributes with the values from the provided {@code - * DnsRecord} instance. + * RecordSet} instance. */ - private Builder(DnsRecord record) { + private Builder(RecordSet record) { this.name = record.name; this.ttl = record.ttl; this.type = record.type; @@ -186,7 +186,7 @@ public Builder records(List records) { } /** - * Sets name for this DNS record set. For example, www.example.com. + * Sets the name for this record set. For example, www.example.com. */ public Builder name(String name) { this.name = checkNotNull(name); @@ -198,7 +198,7 @@ public Builder name(String name) { * The maximum duration must be equivalent to at most {@link Integer#MAX_VALUE} seconds. * * @param duration A non-negative number of time units - * @param unit The unit of the ttl parameter + * @param unit The unit of the ttl parameter */ public Builder ttl(int duration, TimeUnit unit) { checkArgument(duration >= 0, @@ -219,14 +219,14 @@ public Builder type(Type type) { } /** - * Builds the DNS record. + * Builds the record set. */ - public DnsRecord build() { - return new DnsRecord(this); + public RecordSet build() { + return new RecordSet(this); } } - private DnsRecord(Builder builder) { + private RecordSet(Builder builder) { this.name = builder.name; this.rrdatas = ImmutableList.copyOf(builder.rrdatas); this.ttl = builder.ttl; @@ -241,35 +241,35 @@ public Builder toBuilder() { } /** - * Creates a {@code DnsRecord} builder for the given {@code name} and {@code type}. + * Creates a {@code RecordSet} builder for the given {@code name} and {@code type}. */ public static Builder builder(String name, Type type) { return new Builder(name, type); } /** - * Returns the user-assigned name of this DNS record. + * Returns the user-assigned name of this record set. */ public String name() { return name; } /** - * Returns a list of DNS record stored in this record set. + * Returns a list of records stored in this record set. */ public List records() { return rrdatas; } /** - * Returns the number of seconds that this DnsResource can be cached by resolvers. + * Returns the number of seconds that this record set can be cached by resolvers. */ public Integer ttl() { return ttl; } /** - * Returns the type of this DNS record. + * Returns the type of this record set. */ public Type type() { return type; @@ -282,7 +282,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - return (obj instanceof DnsRecord) && Objects.equals(this.toPb(), ((DnsRecord) obj).toPb()); + return obj instanceof RecordSet && Objects.equals(this.toPb(), ((RecordSet) obj).toPb()); } com.google.api.services.dns.model.ResourceRecordSet toPb() { @@ -295,7 +295,7 @@ com.google.api.services.dns.model.ResourceRecordSet toPb() { return pb; } - static DnsRecord fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) { + static RecordSet fromPb(com.google.api.services.dns.model.ResourceRecordSet pb) { Builder builder = builder(pb.getName(), Type.valueOf(pb.getType())); if (pb.getRrdatas() != null) { builder.records(pb.getRrdatas()); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 41507647543a..aed99dbd0001 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -28,10 +28,10 @@ /** * A Google Cloud DNS Zone object. * - *

    A zone is the container for all of your DNS records that share the same DNS name prefix, for + *

    A zone is the container for all of your record sets that share the same DNS name prefix, for * example, example.com. Zones are automatically assigned a set of name servers when they are * created to handle responding to DNS queries for that zone. A zone has quotas for the number of - * resource records that it can include. + * record sets that it can include. * * @see Google Cloud DNS managed zone * documentation @@ -135,14 +135,14 @@ public boolean delete() { } /** - * Lists all {@link DnsRecord}s associated with this zone. The method searches for zone by name. + * Lists all {@link RecordSet}s associated with this zone. The method searches for zone by name. * - * @param options optional restriction on listing and fields of {@link DnsRecord}s returned - * @return a page of DNS records + * @param options optional restriction on listing and fields of {@link RecordSet}s returned + * @return a page of record sets * @throws DnsException upon failure or if the zone is not found */ - public Page listDnsRecords(Dns.DnsRecordListOption... options) { - return dns.listDnsRecords(name(), options); + public Page listRecordSets(Dns.RecordSetListOption... options) { + return dns.listRecordSets(name(), options); } /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java index 8a137285c357..69bee930df62 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java @@ -42,7 +42,7 @@ * String zoneName = "my-unique-zone"; * Zone zone = dns.getZone(zoneName); * String ip = "12.13.14.15"; - * DnsRecord toCreate = DnsRecord.builder("www.someexampledomain.com.", DnsRecord.Type.A) + * RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) * .ttl(24, TimeUnit.HOURS) * .addRecord(ip) * .build(); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java index f8b8adb87ada..cbebd19d0d73 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DefaultDnsRpc.java @@ -112,7 +112,7 @@ public boolean deleteZone(String zoneName) throws DnsException { } @Override - public ListResult listDnsRecords(String zoneName, Map options) + public ListResult listRecordSets(String zoneName, Map options) throws DnsException { // options are fields, page token, dns name, type try { diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java index bde93b99bfdd..c7478016db27 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/spi/DnsRpc.java @@ -120,13 +120,13 @@ public String pageToken() { boolean deleteZone(String zoneName) throws DnsException; /** - * Lists DNS records for a given zone. + * Lists record sets for a given zone. * * @param zoneName name of the zone to be listed * @param options a map of options for the service call * @throws DnsException upon failure or if zone was not found */ - ListResult listDnsRecords(String zoneName, Map options) + ListResult listRecordSets(String zoneName, Map options) throws DnsException; /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java index 3b18ec5ce55b..0ae2c37b9b4d 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/LocalDnsHelper.java @@ -90,8 +90,8 @@ * privileges to manipulate any project. Similarly, the local simulation does not require * verification of domain name ownership. Any request for creating a managed zone will be approved. * The mock does not track quota and will allow the user to exceed it. The mock provides only basic - * validation of the DNS data for records of type A and AAAA. It does not validate any other record - * types. + * validation of the DNS data for record sets of type A and AAAA. It does not validate any other + * record set types. */ public class LocalDnsHelper { @@ -470,7 +470,7 @@ static Response toListResponse(List serializedObjects, String context, S } /** - * Prepares DNS records that are created by default for each zone. + * Prepares record sets that are created by default for each zone. */ private static ImmutableSortedMap defaultRecords(ManagedZone zone) { ResourceRecordSet soa = new ResourceRecordSet(); @@ -508,7 +508,7 @@ static List randomNameservers() { } /** - * Returns a hex string id (used for a dns record) unique within the set of ids. + * Returns a hex string id (used for a record set) unique within the set of ids. */ @VisibleForTesting static String getUniqueId(Set ids) { @@ -521,14 +521,14 @@ static String getUniqueId(Set ids) { } /** - * Tests if a DNS record matches name and type (if provided). Used for filtering. + * Tests if a record set matches name and type (if provided). Used for filtering. */ @VisibleForTesting - static boolean matchesCriteria(ResourceRecordSet record, String name, String type) { - if (type != null && !record.getType().equals(type)) { + static boolean matchesCriteria(ResourceRecordSet recordSet, String name, String type) { + if (type != null && !recordSet.getType().equals(type)) { return false; } - return name == null || record.getName().equals(name); + return name == null || recordSet.getName().equals(name); } /** @@ -871,7 +871,7 @@ Response listZones(String projectId, String query) { } /** - * Lists DNS records for a zone. Next page token is the ID of the last record listed. + * Lists record sets for a zone. Next page token is the ID of the last record listed. */ @VisibleForTesting Response listDnsRecords(String projectId, String zoneName, String query) { @@ -898,18 +898,18 @@ Response listDnsRecords(String projectId, String zoneName, String query) { boolean hasMorePages = false; LinkedList serializedRrsets = new LinkedList<>(); String lastRecordId = null; - for (String recordId : fragment.keySet()) { - ResourceRecordSet record = fragment.get(recordId); - if (matchesCriteria(record, name, type)) { + for (String recordSetId : fragment.keySet()) { + ResourceRecordSet recordSet = fragment.get(recordSetId); + if (matchesCriteria(recordSet, name, type)) { if (sizeReached) { // we do not add this, just note that there would be more and there should be a token hasMorePages = true; break; } else { - lastRecordId = recordId; + lastRecordId = recordSetId; try { serializedRrsets.addLast(jsonFactory.toString( - OptionParsers.extractFields(record, fields))); + OptionParsers.extractFields(recordSet, fields))); } catch (IOException e) { return Error.INTERNAL_ERROR.response(String.format( "Error when serializing resource record set in managed zone %s in project %s", @@ -1128,8 +1128,8 @@ static Response checkRrset(ResourceRecordSet rrset, ZoneContainer zone, int inde } /** - * Checks against duplicate additions (for each record to be added that already exists, we must - * have a matching deletion. Furthermore, check that mandatory SOA and NS records stay. + * Checks against duplicate additions (for each record set to be added that already exists, we + * must have a matching deletion. Furthermore, check that mandatory SOA and NS records stay. */ static Response checkAdditionsDeletions(List additions, List deletions, ZoneContainer zone) { @@ -1139,7 +1139,7 @@ static Response checkAdditionsDeletions(List additions, for (ResourceRecordSet wrappedRrset : zone.dnsRecords().get().values()) { if (rrset.getName().equals(wrappedRrset.getName()) && rrset.getType().equals(wrappedRrset.getType()) - // such a record exist and we must have a deletion + // such a record set exists and we must have a deletion && (deletions == null || !deletions.contains(wrappedRrset))) { return Error.ALREADY_EXISTS.response(String.format( "The 'entity.change.additions[%s]' resource named '%s (%s)' already exists.", @@ -1181,10 +1181,10 @@ static Response checkAdditionsDeletions(List additions, /** * Helper for searching rrsets in a collection. */ - private static ResourceRecordSet findByNameAndType(Iterable records, + private static ResourceRecordSet findByNameAndType(Iterable recordSets, String name, String type) { - if (records != null) { - for (ResourceRecordSet rrset : records) { + if (recordSets != null) { + for (ResourceRecordSet rrset : recordSets) { if ((name == null || name.equals(rrset.getName())) && (type == null || type.equals(rrset.getType()))) { return rrset; @@ -1195,7 +1195,7 @@ private static ResourceRecordSet findByNameAndType(Iterable r } /** - * We only provide the most basic validation for A and AAAA records. + * We only provide the most basic validation for A and AAAA record sets. */ static boolean checkRrData(String data, String type) { switch (type) { @@ -1233,7 +1233,7 @@ static Response checkListOptions(Map options) { return Error.INVALID.response(String.format( "Invalid value for 'parameters.dnsName': '%s'", dnsName)); } - // for listing dns records, name must be fully qualified + // for listing record sets, name must be fully qualified String name = (String) options.get("name"); if (name != null && !name.endsWith(".")) { return Error.INVALID.response(String.format( diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java index ecd7e8179efe..578a0b52db3d 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/testing/OptionParsers.java @@ -166,26 +166,26 @@ static ResourceRecordSet extractFields(ResourceRecordSet fullRecord, String... f if (fields == null || fields.length == 0) { return fullRecord; } - ResourceRecordSet record = new ResourceRecordSet(); + ResourceRecordSet recordSet = new ResourceRecordSet(); for (String field : fields) { switch (field) { case "name": - record.setName(fullRecord.getName()); + recordSet.setName(fullRecord.getName()); break; case "rrdatas": - record.setRrdatas(fullRecord.getRrdatas()); + recordSet.setRrdatas(fullRecord.getRrdatas()); break; case "type": - record.setType(fullRecord.getType()); + recordSet.setType(fullRecord.getType()); break; case "ttl": - record.setTtl(fullRecord.getTtl()); + recordSet.setTtl(fullRecord.getTtl()); break; default: break; } } - return record; + return recordSet; } static Map parseListChangesOptions(String query) { diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java index 8b40a4dcff34..fe726acb7c10 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java @@ -35,16 +35,16 @@ public class ChangeRequestTest { private static final Long START_TIME_MILLIS = 12334567890L; private static final ChangeRequest.Status STATUS = ChangeRequest.Status.PENDING; private static final String NAME1 = "dns1"; - private static final DnsRecord.Type TYPE1 = DnsRecord.Type.A; + private static final RecordSet.Type TYPE1 = RecordSet.Type.A; private static final String NAME2 = "dns2"; - private static final DnsRecord.Type TYPE2 = DnsRecord.Type.AAAA; + private static final RecordSet.Type TYPE2 = RecordSet.Type.AAAA; private static final String NAME3 = "dns3"; - private static final DnsRecord.Type TYPE3 = DnsRecord.Type.MX; - private static final DnsRecord RECORD1 = DnsRecord.builder(NAME1, TYPE1).build(); - private static final DnsRecord RECORD2 = DnsRecord.builder(NAME2, TYPE2).build(); - private static final DnsRecord RECORD3 = DnsRecord.builder(NAME3, TYPE3).build(); - private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); - private static final List DELETIONS = ImmutableList.of(RECORD3); + private static final RecordSet.Type TYPE3 = RecordSet.Type.MX; + private static final RecordSet RECORD1 = RecordSet.builder(NAME1, TYPE1).build(); + private static final RecordSet RECORD2 = RecordSet.builder(NAME2, TYPE2).build(); + private static final RecordSet RECORD3 = RecordSet.builder(NAME3, TYPE3).build(); + private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); + private static final List DELETIONS = ImmutableList.of(RECORD3); private static final ChangeRequest CHANGE = ChangeRequest.builder() .add(RECORD1) .add(RECORD2) @@ -70,7 +70,7 @@ public void testBuilder() { assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); assertEquals(ADDITIONS, CHANGE.additions()); assertEquals(DELETIONS, CHANGE.deletions()); - List recordList = ImmutableList.of(RECORD1); + List recordList = ImmutableList.of(RECORD1); ChangeRequest another = CHANGE.toBuilder().additions(recordList).build(); assertEquals(recordList, another.additions()); assertEquals(CHANGE.deletions(), another.deletions()); @@ -160,7 +160,7 @@ public void testClearAdditions() { public void testAddAddition() { try { CHANGE.toBuilder().add(null); - fail("Should not be able to add null DnsRecord."); + fail("Should not be able to add null RecordSet."); } catch (NullPointerException e) { // expected } @@ -172,7 +172,7 @@ public void testAddAddition() { public void testAddDeletion() { try { CHANGE.toBuilder().delete(null); - fail("Should not be able to delete null DnsRecord."); + fail("Should not be able to delete null RecordSet."); } catch (NullPointerException e) { // expected } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index a97c9c408036..ab2dba0a566c 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -21,7 +21,6 @@ import com.google.api.services.dns.model.Change; import com.google.api.services.dns.model.ManagedZone; -import com.google.api.services.dns.model.ResourceRecordSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; @@ -46,10 +45,10 @@ public class DnsImplTest { private static final String DNS_NAME = "example.com."; private static final String DESCRIPTION = "desc"; private static final String CHANGE_ID = "some change id"; - private static final DnsRecord DNS_RECORD1 = DnsRecord.builder("Something", DnsRecord.Type.AAAA) - .build(); - private static final DnsRecord DNS_RECORD2 = DnsRecord.builder("Different", DnsRecord.Type.AAAA) - .build(); + private static final RecordSet DNS_RECORD1 = + RecordSet.builder("Something", RecordSet.Type.AAAA).build(); + private static final RecordSet DNS_RECORD2 = + RecordSet.builder("Different", RecordSet.Type.AAAA).build(); private static final Integer MAX_SIZE = 20; private static final String PAGE_TOKEN = "some token"; private static final ZoneInfo ZONE_INFO = ZoneInfo.of(ZONE_NAME, DNS_NAME, DESCRIPTION); @@ -70,7 +69,8 @@ public class DnsImplTest { CHANGE_REQUEST_PARTIAL.toPb())); private static final DnsRpc.ListResult LIST_RESULT_OF_PB_ZONES = DnsRpc.ListResult.of("cursor", ImmutableList.of(ZONE_INFO.toPb())); - private static final DnsRpc.ListResult LIST_OF_PB_DNS_RECORDS = + private static final DnsRpc.ListResult + LIST_OF_PB_DNS_RECORDS = DnsRpc.ListResult.of("cursor", ImmutableList.of(DNS_RECORD1.toPb(), DNS_RECORD2.toPb())); // Field options @@ -91,12 +91,12 @@ public class DnsImplTest { Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN), Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)}; - private static final Dns.DnsRecordListOption[] DNS_RECORD_LIST_OPTIONS = { - Dns.DnsRecordListOption.pageSize(MAX_SIZE), - Dns.DnsRecordListOption.pageToken(PAGE_TOKEN), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL), - Dns.DnsRecordListOption.dnsName(DNS_NAME), - Dns.DnsRecordListOption.type(DnsRecord.Type.AAAA)}; + private static final Dns.RecordSetListOption[] DNS_RECORD_LIST_OPTIONS = { + Dns.RecordSetListOption.pageSize(MAX_SIZE), + Dns.RecordSetListOption.pageToken(PAGE_TOKEN), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TTL), + Dns.RecordSetListOption.dnsName(DNS_NAME), + Dns.RecordSetListOption.type(RecordSet.Type.AAAA)}; // Other private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); @@ -338,11 +338,11 @@ public void testListZonesWithOptions() { @Test public void testListDnsRecords() { - EasyMock.expect(dnsRpcMock.listDnsRecords(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(dnsRpcMock.listRecordSets(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) .andReturn(LIST_OF_PB_DNS_RECORDS); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Page dnsPage = dns.listDnsRecords(ZONE_INFO.name()); + Page dnsPage = dns.listRecordSets(ZONE_INFO.name()); assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); @@ -351,11 +351,11 @@ public void testListDnsRecords() { @Test public void testListDnsRecordsWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(dnsRpcMock.listDnsRecords(EasyMock.eq(ZONE_NAME), + EasyMock.expect(dnsRpcMock.listRecordSets(EasyMock.eq(ZONE_NAME), EasyMock.capture(capturedOptions))).andReturn(LIST_OF_PB_DNS_RECORDS); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Page dnsPage = dns.listDnsRecords(ZONE_NAME, DNS_RECORD_LIST_OPTIONS); + Page dnsPage = dns.listRecordSets(ZONE_NAME, DNS_RECORD_LIST_OPTIONS); assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); @@ -365,8 +365,8 @@ public void testListDnsRecordsWithOptions() { .get(DNS_RECORD_LIST_OPTIONS[1].rpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[2].rpcOption()); - assertTrue(selector.contains(Dns.DnsRecordField.NAME.selector())); - assertTrue(selector.contains(Dns.DnsRecordField.TTL.selector())); + assertTrue(selector.contains(Dns.RecordSetField.NAME.selector())); + assertTrue(selector.contains(Dns.RecordSetField.TTL.selector())); selector = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[3].rpcOption()); assertEquals(DNS_RECORD_LIST_OPTIONS[3].value(), selector); String type = (String) capturedOptions.getValue().get(DNS_RECORD_LIST_OPTIONS[4] diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java index 2e233e2df62a..df86d6ebd495 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsTest.java @@ -30,36 +30,36 @@ public class DnsTest { private static final String DNS_NAME = "www.example.com."; @Test - public void testDnsRecordListOption() { + public void testRecordSetListOption() { // dns name String dnsName = "some name"; - Dns.DnsRecordListOption dnsRecordListOption = Dns.DnsRecordListOption.dnsName(dnsName); - assertEquals(dnsName, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.NAME, dnsRecordListOption.rpcOption()); + Dns.RecordSetListOption recordSetListOption = Dns.RecordSetListOption.dnsName(dnsName); + assertEquals(dnsName, recordSetListOption.value()); + assertEquals(DnsRpc.Option.NAME, recordSetListOption.rpcOption()); // page token - dnsRecordListOption = Dns.DnsRecordListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.PAGE_TOKEN, dnsRecordListOption.rpcOption()); + recordSetListOption = Dns.RecordSetListOption.pageToken(PAGE_TOKEN); + assertEquals(PAGE_TOKEN, recordSetListOption.value()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, recordSetListOption.rpcOption()); // page size - dnsRecordListOption = Dns.DnsRecordListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.PAGE_SIZE, dnsRecordListOption.rpcOption()); + recordSetListOption = Dns.RecordSetListOption.pageSize(PAGE_SIZE); + assertEquals(PAGE_SIZE, recordSetListOption.value()); + assertEquals(DnsRpc.Option.PAGE_SIZE, recordSetListOption.rpcOption()); // record type - DnsRecord.Type recordType = DnsRecord.Type.AAAA; - dnsRecordListOption = Dns.DnsRecordListOption.type(recordType); - assertEquals(recordType.name(), dnsRecordListOption.value()); - assertEquals(DnsRpc.Option.DNS_TYPE, dnsRecordListOption.rpcOption()); + RecordSet.Type recordType = RecordSet.Type.AAAA; + recordSetListOption = Dns.RecordSetListOption.type(recordType); + assertEquals(recordType.name(), recordSetListOption.value()); + assertEquals(DnsRpc.Option.DNS_TYPE, recordSetListOption.rpcOption()); // fields - dnsRecordListOption = Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME, - Dns.DnsRecordField.TTL); - assertEquals(DnsRpc.Option.FIELDS, dnsRecordListOption.rpcOption()); - assertTrue(dnsRecordListOption.value() instanceof String); - assertTrue(((String) dnsRecordListOption.value()).contains( - Dns.DnsRecordField.NAME.selector())); - assertTrue(((String) dnsRecordListOption.value()).contains( - Dns.DnsRecordField.TTL.selector())); - assertTrue(((String) dnsRecordListOption.value()).contains( - Dns.DnsRecordField.NAME.selector())); + recordSetListOption = Dns.RecordSetListOption.fields(Dns.RecordSetField.NAME, + Dns.RecordSetField.TTL); + assertEquals(DnsRpc.Option.FIELDS, recordSetListOption.rpcOption()); + assertTrue(recordSetListOption.value() instanceof String); + assertTrue(((String) recordSetListOption.value()).contains( + Dns.RecordSetField.NAME.selector())); + assertTrue(((String) recordSetListOption.value()).contains( + Dns.RecordSetField.TTL.selector())); + assertTrue(((String) recordSetListOption.value()).contains( + Dns.RecordSetField.NAME.selector())); } @Test diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/RecordSetTest.java similarity index 63% rename from gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java rename to gcloud-java-dns/src/test/java/com/google/gcloud/dns/RecordSetTest.java index 5fc972cede78..369e078a48c7 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsRecordTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/RecordSetTest.java @@ -16,7 +16,7 @@ package com.google.gcloud.dns; -import static com.google.gcloud.dns.DnsRecord.builder; +import static com.google.gcloud.dns.RecordSet.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; @@ -26,35 +26,35 @@ import java.util.concurrent.TimeUnit; -public class DnsRecordTest { +public class RecordSetTest { private static final String NAME = "example.com."; private static final Integer TTL = 3600; private static final TimeUnit UNIT = TimeUnit.HOURS; private static final Integer UNIT_TTL = 1; - private static final DnsRecord.Type TYPE = DnsRecord.Type.AAAA; - private static final DnsRecord record = builder(NAME, TYPE) + private static final RecordSet.Type TYPE = RecordSet.Type.AAAA; + private static final RecordSet recordSet = builder(NAME, TYPE) .ttl(UNIT_TTL, UNIT) .build(); @Test public void testDefaultDnsRecord() { - DnsRecord record = builder(NAME, TYPE).build(); - assertEquals(0, record.records().size()); - assertEquals(TYPE, record.type()); - assertEquals(NAME, record.name()); + RecordSet recordSet = builder(NAME, TYPE).build(); + assertEquals(0, recordSet.records().size()); + assertEquals(TYPE, recordSet.type()); + assertEquals(NAME, recordSet.name()); } @Test public void testBuilder() { - assertEquals(NAME, record.name()); - assertEquals(TTL, record.ttl()); - assertEquals(TYPE, record.type()); - assertEquals(0, record.records().size()); + assertEquals(NAME, recordSet.name()); + assertEquals(TTL, recordSet.ttl()); + assertEquals(TYPE, recordSet.type()); + assertEquals(0, recordSet.records().size()); // verify that one can add records to the record set - String testingRecord = "Testing record"; - String anotherTestingRecord = "Another record 123"; - DnsRecord anotherRecord = record.toBuilder() + String testingRecord = "Testing recordSet"; + String anotherTestingRecord = "Another recordSet 123"; + RecordSet anotherRecord = recordSet.toBuilder() .addRecord(testingRecord) .addRecord(anotherTestingRecord) .build(); @@ -79,47 +79,47 @@ public void testValidTtl() { } catch (IllegalArgumentException e) { // expected } - DnsRecord record = DnsRecord.builder(NAME, TYPE).ttl(UNIT_TTL, UNIT).build(); + RecordSet record = RecordSet.builder(NAME, TYPE).ttl(UNIT_TTL, UNIT).build(); assertEquals(TTL, record.ttl()); } @Test public void testEqualsAndNotEquals() { - DnsRecord clone = record.toBuilder().build(); - assertEquals(record, clone); - clone = record.toBuilder().addRecord("another record").build(); - assertNotEquals(record, clone); + RecordSet clone = recordSet.toBuilder().build(); + assertEquals(recordSet, clone); + clone = recordSet.toBuilder().addRecord("another recordSet").build(); + assertNotEquals(recordSet, clone); String differentName = "totally different name"; - clone = record.toBuilder().name(differentName).build(); - assertNotEquals(record, clone); - clone = record.toBuilder().ttl(record.ttl() + 1, TimeUnit.SECONDS).build(); - assertNotEquals(record, clone); - clone = record.toBuilder().type(DnsRecord.Type.TXT).build(); - assertNotEquals(record, clone); + clone = recordSet.toBuilder().name(differentName).build(); + assertNotEquals(recordSet, clone); + clone = recordSet.toBuilder().ttl(recordSet.ttl() + 1, TimeUnit.SECONDS).build(); + assertNotEquals(recordSet, clone); + clone = recordSet.toBuilder().type(RecordSet.Type.TXT).build(); + assertNotEquals(recordSet, clone); } @Test public void testSameHashCodeOnEquals() { - int hash = record.hashCode(); - DnsRecord clone = record.toBuilder().build(); + int hash = recordSet.hashCode(); + RecordSet clone = recordSet.toBuilder().build(); assertEquals(clone.hashCode(), hash); } @Test public void testToAndFromPb() { - assertEquals(record, DnsRecord.fromPb(record.toPb())); - DnsRecord partial = builder(NAME, TYPE).build(); - assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + assertEquals(recordSet, RecordSet.fromPb(recordSet.toPb())); + RecordSet partial = builder(NAME, TYPE).build(); + assertEquals(partial, RecordSet.fromPb(partial.toPb())); partial = builder(NAME, TYPE).addRecord("test").build(); - assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + assertEquals(partial, RecordSet.fromPb(partial.toPb())); partial = builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); - assertEquals(partial, DnsRecord.fromPb(partial.toPb())); + assertEquals(partial, RecordSet.fromPb(partial.toPb())); } @Test public void testToBuilder() { - assertEquals(record, record.toBuilder().build()); - DnsRecord partial = builder(NAME, TYPE).build(); + assertEquals(recordSet, recordSet.toBuilder().build()); + RecordSet partial = builder(NAME, TYPE).build(); assertEquals(partial, partial.toBuilder().build()); partial = builder(NAME, TYPE).addRecord("test").build(); assertEquals(partial, partial.toBuilder().build()); @@ -130,7 +130,8 @@ public void testToBuilder() { @Test public void clearRecordSet() { // make sure that we are starting not empty - DnsRecord clone = record.toBuilder().addRecord("record").addRecord("another").build(); + RecordSet clone = + recordSet.toBuilder().addRecord("record").addRecord("another").build(); assertNotEquals(0, clone.records().size()); clone = clone.toBuilder().clearRecords().build(); assertEquals(0, clone.records().size()); @@ -141,7 +142,7 @@ public void clearRecordSet() { public void removeFromRecordSet() { String recordString = "record"; // make sure that we are starting not empty - DnsRecord clone = record.toBuilder().addRecord(recordString).build(); + RecordSet clone = recordSet.toBuilder().addRecord(recordString).build(); assertNotEquals(0, clone.records().size()); clone = clone.toBuilder().removeRecord(recordString).build(); assertEquals(0, clone.records().size()); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java index 7a0c32036878..c06cd096bf1e 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -45,8 +45,8 @@ public class SerializationTest extends BaseSerializationTest { .build(); private static final Dns.ZoneListOption ZONE_LIST_OPTION = Dns.ZoneListOption.dnsName("www.example.com."); - private static final Dns.DnsRecordListOption DNS_REOCRD_LIST_OPTION = - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL); + private static final Dns.RecordSetListOption RECORD_SET_LIST_OPTION = + Dns.RecordSetListOption.fields(Dns.RecordSetField.TTL); private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTION = Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.STATUS); private static final Dns.ZoneOption ZONE_OPTION = @@ -64,16 +64,16 @@ public class SerializationTest extends BaseSerializationTest { private static final Zone PARTIAL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(PARTIAL_ZONE_INFO)); private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder().build(); - private static final DnsRecord DNS_RECORD_PARTIAL = - DnsRecord.builder("www.www.com", DnsRecord.Type.AAAA).build(); - private static final DnsRecord DNS_RECORD_COMPLETE = - DnsRecord.builder("www.sadfa.com", DnsRecord.Type.A) + private static final RecordSet RECORD_SET_PARTIAL = + RecordSet.builder("www.www.com", RecordSet.Type.AAAA).build(); + private static final RecordSet RECORD_SET_COMPLETE = + RecordSet.builder("www.sadfa.com", RecordSet.Type.A) .ttl(12, TimeUnit.HOURS) .addRecord("record") .build(); private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() - .add(DNS_RECORD_COMPLETE) - .delete(DNS_RECORD_PARTIAL) + .add(RECORD_SET_COMPLETE) + .delete(RECORD_SET_PARTIAL) .status(ChangeRequest.Status.PENDING) .id("some id") .startTimeMillis(132L) @@ -89,9 +89,9 @@ protected Serializable[] serializableObjects() { .authCredentials(null) .build(); return new Serializable[]{FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, - DNS_REOCRD_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, + RECORD_SET_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, PROJECT_OPTION, PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, OPTIONS, FULL_ZONE, PARTIAL_ZONE, - OPTIONS, CHANGE_REQUEST_PARTIAL, DNS_RECORD_PARTIAL, DNS_RECORD_COMPLETE, + OPTIONS, CHANGE_REQUEST_PARTIAL, RECORD_SET_PARTIAL, RECORD_SET_COMPLETE, CHANGE_REQUEST_COMPLETE, options, otherOptions}; } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 759c34fc1167..bd59f8c140e9 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -50,12 +50,12 @@ public class ZoneTest { .build(); private static final ZoneInfo NO_ID_INFO = ZoneInfo.of(ZONE_NAME, "another-example.com", "description").toBuilder() - .creationTimeMillis(893123464L) - .build(); + .creationTimeMillis(893123464L) + .build(); private static final Dns.ZoneOption ZONE_FIELD_OPTIONS = Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); - private static final Dns.DnsRecordListOption DNS_RECORD_OPTIONS = - Dns.DnsRecordListOption.dnsName("some-dns"); + private static final Dns.RecordSetListOption DNS_RECORD_OPTIONS = + Dns.RecordSetListOption.dnsName("some-dns"); private static final Dns.ChangeRequestOption CHANGE_REQUEST_FIELD_OPTIONS = Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME); private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTIONS = @@ -120,51 +120,51 @@ public void deleteByNameAndNotFound() { @Test public void listDnsRecordsByNameAndFound() { @SuppressWarnings("unchecked") - Page pageMock = createStrictMock(Page.class); + Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); - expect(dns.listDnsRecords(ZONE_NAME)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME)).andReturn(pageMock); // again for options - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); replay(dns); - Page result = zone.listDnsRecords(); + Page result = zone.listRecordSets(); assertSame(pageMock, result); - result = zoneNoId.listDnsRecords(); + result = zoneNoId.listRecordSets(); assertSame(pageMock, result); verify(pageMock); - zone.listDnsRecords(DNS_RECORD_OPTIONS); // check options - zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + zone.listRecordSets(DNS_RECORD_OPTIONS); // check options + zoneNoId.listRecordSets(DNS_RECORD_OPTIONS); // check options } @Test public void listDnsRecordsByNameAndNotFound() { - expect(dns.listDnsRecords(ZONE_NAME)).andThrow(EXCEPTION); - expect(dns.listDnsRecords(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME)).andThrow(EXCEPTION); // again for options - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); - expect(dns.listDnsRecords(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); replay(dns); try { - zoneNoId.listDnsRecords(); + zoneNoId.listRecordSets(); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.listDnsRecords(); + zone.listRecordSets(); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zoneNoId.listDnsRecords(DNS_RECORD_OPTIONS); // check options + zoneNoId.listRecordSets(DNS_RECORD_OPTIONS); // check options fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.listDnsRecords(DNS_RECORD_OPTIONS); // check options + zone.listRecordSets(DNS_RECORD_OPTIONS); // check options fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index bfea46dfe039..8f7626a5ae0a 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -29,8 +29,8 @@ import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsException; import com.google.gcloud.dns.DnsOptions; -import com.google.gcloud.dns.DnsRecord; import com.google.gcloud.dns.ProjectInfo; +import com.google.gcloud.dns.RecordSet; import com.google.gcloud.dns.Zone; import com.google.gcloud.dns.ZoneInfo; @@ -66,13 +66,13 @@ public class ITDnsTest { ZoneInfo.of(ZONE_NAME_TOO_LONG, ZONE_DNS_NAME1, ZONE_DESCRIPTION1); private static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.of(ZONE_NAME1, ZONE_DNS_NAME_NO_PERIOD, ZONE_DESCRIPTION1); - private static final DnsRecord A_RECORD_ZONE1 = - DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.A) + private static final RecordSet A_RECORD_ZONE1 = + RecordSet.builder("www." + ZONE1.dnsName(), RecordSet.Type.A) .records(ImmutableList.of("123.123.55.1")) .ttl(25, TimeUnit.SECONDS) .build(); - private static final DnsRecord AAAA_RECORD_ZONE1 = - DnsRecord.builder("www." + ZONE1.dnsName(), DnsRecord.Type.AAAA) + private static final RecordSet AAAA_RECORD_ZONE1 = + RecordSet.builder("www." + ZONE1.dnsName(), RecordSet.Type.AAAA) .records(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) .ttl(25, TimeUnit.SECONDS) .build(); @@ -98,12 +98,13 @@ private static void clear() { while (iterator.hasNext()) { waitForChangeToComplete(zoneName, iterator.next().id()); } - Iterator recordIterator = zone.listDnsRecords().iterateAll(); - List toDelete = new LinkedList<>(); - while (recordIterator.hasNext()) { - DnsRecord record = recordIterator.next(); - if (!ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA).contains(record.type())) { - toDelete.add(record); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + List toDelete = new LinkedList<>(); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + if (!ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA) + .contains(recordSet.type())) { + toDelete.add(recordSet); } } if (!toDelete.isEmpty()) { @@ -587,41 +588,42 @@ public void testCreateChange() { @Test public void testInvalidChangeRequest() { Zone zone = DNS.create(ZONE1); - DnsRecord validA = DnsRecord.builder("subdomain." + zone.dnsName(), DnsRecord.Type.A) - .records(ImmutableList.of("0.255.1.5")) - .build(); + RecordSet validA = + RecordSet.builder("subdomain." + zone.dnsName(), RecordSet.Type.A) + .records(ImmutableList.of("0.255.1.5")) + .build(); try { ChangeRequest validChange = ChangeRequest.builder().add(validA).build(); zone.applyChangeRequest(validChange); try { zone.applyChangeRequest(validChange); - fail("Created a record which already exists."); + fail("Created a record set which already exists."); } catch (DnsException ex) { // expected assertFalse(ex.retryable()); assertEquals(409, ex.code()); } // delete with field mismatch - DnsRecord mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); + RecordSet mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); ChangeRequest deletion = ChangeRequest.builder().delete(mismatch).build(); try { zone.applyChangeRequest(deletion); - fail("Deleted a record without a complete match."); + fail("Deleted a record set without a complete match."); } catch (DnsException ex) { // expected assertEquals(412, ex.code()); assertFalse(ex.retryable()); } // delete and add SOA - Iterator recordIterator = zone.listDnsRecords().iterateAll(); - LinkedList deletions = new LinkedList<>(); - LinkedList additions = new LinkedList<>(); - while (recordIterator.hasNext()) { - DnsRecord record = recordIterator.next(); - if (record.type() == DnsRecord.Type.SOA) { - deletions.add(record); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + LinkedList deletions = new LinkedList<>(); + LinkedList additions = new LinkedList<>(); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + if (recordSet.type() == RecordSet.Type.SOA) { + deletions.add(recordSet); // the subdomain is necessary to get 400 instead of 412 - DnsRecord copy = record.toBuilder().name("x." + record.name()).build(); + RecordSet copy = recordSet.toBuilder().name("x." + recordSet.name()).build(); additions.add(copy); break; } @@ -831,92 +833,93 @@ public void testGetProject() { public void testListDnsRecords() { try { Zone zone = DNS.create(ZONE1); - ImmutableList dnsRecords = ImmutableList.copyOf( - DNS.listDnsRecords(zone.name()).iterateAll()); - assertEquals(2, dnsRecords.size()); - ImmutableList defaultRecords = - ImmutableList.of(DnsRecord.Type.NS, DnsRecord.Type.SOA); - for (DnsRecord record : dnsRecords) { - assertTrue(defaultRecords.contains(record.type())); + ImmutableList recordSets = ImmutableList.copyOf( + DNS.listRecordSets(zone.name()).iterateAll()); + assertEquals(2, recordSets.size()); + ImmutableList defaultRecords = + ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA); + for (RecordSet recordSet : recordSets) { + assertTrue(defaultRecords.contains(recordSet.type())); } // field options - Iterator dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TTL)).iterateAll(); + Iterator recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TTL)).iterateAll(); int counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).ttl(), record.ttl()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).ttl(), recordSet.ttl()); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertTrue(recordSet.records().isEmpty()); counter++; } assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.NAME)).iterateAll(); + recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.NAME)).iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertTrue(recordSet.records().isEmpty()); + assertNull(recordSet.ttl()); counter++; } assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.DNS_RECORDS)).iterateAll(); + recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.DNS_RECORDS)) + .iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).records(), record.records()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertNull(record.ttl()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).records(), recordSet.records()); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertNull(recordSet.ttl()); counter++; } assertEquals(2, counter); - dnsRecordIterator = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)).iterateAll(); // also test paging + recordSetIterator = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TYPE), + Dns.RecordSetListOption.pageSize(1)).iterateAll(); // also test paging counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(dnsRecords.get(counter).type(), record.type()); - assertEquals(dnsRecords.get(counter).name(), record.name()); - assertTrue(record.records().isEmpty()); - assertNull(record.ttl()); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(recordSets.get(counter).type(), recordSet.type()); + assertEquals(recordSets.get(counter).name(), recordSet.name()); + assertTrue(recordSet.records().isEmpty()); + assertNull(recordSet.ttl()); counter++; } assertEquals(2, counter); // test page size - Page dnsRecordPage = DNS.listDnsRecords(zone.name(), - Dns.DnsRecordListOption.fields(Dns.DnsRecordField.TYPE), - Dns.DnsRecordListOption.pageSize(1)); - assertEquals(1, ImmutableList.copyOf(dnsRecordPage.values().iterator()).size()); + Page recordSetPage = DNS.listRecordSets(zone.name(), + Dns.RecordSetListOption.fields(Dns.RecordSetField.TYPE), + Dns.RecordSetListOption.pageSize(1)); + assertEquals(1, ImmutableList.copyOf(recordSetPage.values().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.name(), change.id()); - dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); + recordSetIterator = DNS.listRecordSets(ZONE1.name(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) - .contains(record.type())); + .contains(recordSet.type())); counter++; } assertEquals(2, counter); // test type filter waitForChangeToComplete(ZONE1.name(), change.id()); - dnsRecordIterator = DNS.listDnsRecords(ZONE1.name(), - Dns.DnsRecordListOption.dnsName(A_RECORD_ZONE1.name()), - Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())) + recordSetIterator = DNS.listRecordSets(ZONE1.name(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name()), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())) .iterateAll(); counter = 0; - while (dnsRecordIterator.hasNext()) { - DnsRecord record = dnsRecordIterator.next(); - assertEquals(A_RECORD_ZONE1, record); + while (recordSetIterator.hasNext()) { + RecordSet recordSet = recordSetIterator.next(); + assertEquals(A_RECORD_ZONE1, recordSet); counter++; } assertEquals(1, counter); @@ -924,7 +927,8 @@ public void testListDnsRecords() { // check wrong arguments try { // name is not set - DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.type(A_RECORD_ZONE1.type())); + DNS.listRecordSets(ZONE1.name(), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())); fail(); } catch (DnsException ex) { // expected @@ -932,7 +936,7 @@ public void testListDnsRecords() { assertFalse(ex.retryable()); } try { - DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(0)); + DNS.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected @@ -940,7 +944,7 @@ public void testListDnsRecords() { assertFalse(ex.retryable()); } try { - DNS.listDnsRecords(ZONE1.name(), Dns.DnsRecordListOption.pageSize(-1)); + DNS.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java index 59002131cc9d..44516f47c657 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/testing/LocalDnsHelperTest.java @@ -131,7 +131,7 @@ public void testCreateZone() { ManagedZone created = RPC.create(ZONE1, EMPTY_RPC_OPTIONS); // check that default records were created DnsRpc.ListResult listResult - = RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS); + = RPC.listRecordSets(ZONE1.getName(), EMPTY_RPC_OPTIONS); ImmutableList defaultTypes = ImmutableList.of("SOA", "NS"); Iterator iterator = listResult.results().iterator(); assertTrue(defaultTypes.contains(iterator.next().getType())); @@ -395,7 +395,7 @@ private static void executeCreateAndApplyChangeTest(DnsRpc rpc) { rpc.applyChangeRequest(ZONE1.getName(), CHANGE_KEEP, EMPTY_RPC_OPTIONS); waitForChangeToComplete(rpc, ZONE1.getName(), "3"); Iterable results = - rpc.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); + rpc.listRecordSets(ZONE1.getName(), EMPTY_RPC_OPTIONS).results(); List defaults = ImmutableList.of("SOA", "NS"); boolean rrsetKeep = false; boolean rrset1 = false; @@ -692,7 +692,7 @@ public void testListZones() { public void testListDnsRecords() { // no zone exists try { - RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS); + RPC.listRecordSets(ZONE_NAME1, EMPTY_RPC_OPTIONS); fail(); } catch (DnsException ex) { // expected @@ -702,19 +702,19 @@ public void testListDnsRecords() { // zone exists but has no records RPC.create(ZONE1, EMPTY_RPC_OPTIONS); Iterable results = - RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); + RPC.listRecordSets(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); ImmutableList records = ImmutableList.copyOf(results); assertEquals(2, records.size()); // contains default NS and SOA // zone has records RPC.applyChangeRequest(ZONE_NAME1, CHANGE_KEEP, EMPTY_RPC_OPTIONS); - results = RPC.listDnsRecords(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); + results = RPC.listRecordSets(ZONE_NAME1, EMPTY_RPC_OPTIONS).results(); records = ImmutableList.copyOf(results); assertEquals(3, records.size()); // error in options Map options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, 0); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -723,7 +723,7 @@ public void testListDnsRecords() { } options.put(DnsRpc.Option.PAGE_SIZE, -1); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -731,14 +731,14 @@ public void testListDnsRecords() { assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, 15); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + results = RPC.listRecordSets(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(3, records.size()); // dnsName filter options = new HashMap<>(); options.put(DnsRpc.Option.NAME, "aaa"); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -746,13 +746,13 @@ public void testListDnsRecords() { assertTrue(ex.getMessage().contains("parameters.name")); } options.put(DnsRpc.Option.NAME, "aaa."); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + results = RPC.listRecordSets(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(0, records.size()); options.put(DnsRpc.Option.NAME, null); options.put(DnsRpc.Option.DNS_TYPE, "A"); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -762,7 +762,7 @@ public void testListDnsRecords() { options.put(DnsRpc.Option.NAME, "aaa."); options.put(DnsRpc.Option.DNS_TYPE, "a"); try { - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); fail(); } catch (DnsException ex) { // expected @@ -771,14 +771,14 @@ public void testListDnsRecords() { } options.put(DnsRpc.Option.NAME, DNS_NAME); options.put(DnsRpc.Option.DNS_TYPE, "SOA"); - results = RPC.listDnsRecords(ZONE1.getName(), options).results(); + results = RPC.listRecordSets(ZONE1.getName(), options).results(); records = ImmutableList.copyOf(results); assertEquals(1, records.size()); // field options options = new HashMap<>(); options.put(DnsRpc.Option.FIELDS, "rrsets(name)"); DnsRpc.ListResult listResult = - RPC.listDnsRecords(ZONE1.getName(), options); + RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); ResourceRecordSet record = records.get(0); assertNotNull(record.getName()); @@ -787,7 +787,7 @@ public void testListDnsRecords() { assertNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(rrdatas)"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -796,7 +796,7 @@ record = records.get(0); assertNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(ttl)"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -805,7 +805,7 @@ record = records.get(0); assertNotNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "rrsets(type)"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -814,7 +814,7 @@ record = records.get(0); assertNull(record.getTtl()); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "nextPageToken"); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); record = records.get(0); assertNull(record.getName()); @@ -824,7 +824,7 @@ record = records.get(0); assertNull(listResult.pageToken()); options.put(DnsRpc.Option.FIELDS, "nextPageToken,rrsets(name,rrdatas)"); options.put(DnsRpc.Option.PAGE_SIZE, 1); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); record = records.get(0); @@ -973,15 +973,15 @@ public void testListChanges() { public void testDnsRecordPaging() { RPC.create(ZONE1, EMPTY_RPC_OPTIONS); List complete = ImmutableList.copyOf( - RPC.listDnsRecords(ZONE1.getName(), EMPTY_RPC_OPTIONS).results()); + RPC.listRecordSets(ZONE1.getName(), EMPTY_RPC_OPTIONS).results()); Map options = new HashMap<>(); options.put(DnsRpc.Option.PAGE_SIZE, 1); - DnsRpc.ListResult listResult = RPC.listDnsRecords(ZONE1.getName(), options); + DnsRpc.ListResult listResult = RPC.listRecordSets(ZONE1.getName(), options); ImmutableList records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); assertEquals(complete.get(0), records.get(0)); options.put(DnsRpc.Option.PAGE_TOKEN, listResult.pageToken()); - listResult = RPC.listDnsRecords(ZONE1.getName(), options); + listResult = RPC.listRecordSets(ZONE1.getName(), options); records = ImmutableList.copyOf(listResult.results()); assertEquals(1, records.size()); assertEquals(complete.get(1), records.get(0)); diff --git a/gcloud-java-examples/README.md b/gcloud-java-examples/README.md index fc9ce9ef653d..8084cee562f0 100644 --- a/gcloud-java-examples/README.md +++ b/gcloud-java-examples/README.md @@ -75,7 +75,7 @@ To run examples from your command line: 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. + Also, note that the example creates and deletes record sets 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" 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 1b6ba8f179da..40ce61b07281 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 @@ -21,8 +21,8 @@ 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.RecordSet; import com.google.gcloud.dns.Zone; import com.google.gcloud.dns.ZoneInfo; @@ -38,8 +38,8 @@ /** * 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. + *

    This example creates, deletes, gets, and lists zones. It also creates and deletes + * record sets of type A, and lists record sets. * *

    Steps needed for running the example: *

      @@ -203,12 +203,12 @@ public void run(Dns dns, String... args) { if (args.length > 3) { ttl = Integer.parseInt(args[3]); } - DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) + RecordSet recordSet = RecordSet.builder(recordName, RecordSet.Type.A) .records(ImmutableList.of(ip)) .ttl(ttl, TimeUnit.SECONDS) .build(); ChangeRequest changeRequest = ChangeRequest.builder() - .delete(record) + .delete(recordSet) .build(); changeRequest = dns.applyChangeRequest(zoneName, changeRequest); System.out.printf("The request for deleting A record %s for zone %s was successfully " @@ -238,7 +238,7 @@ 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. If ttl is not + * Adds a record set 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 @@ -250,11 +250,11 @@ public void run(Dns dns, String... args) { if (args.length > 3) { ttl = Integer.parseInt(args[3]); } - DnsRecord record = DnsRecord.builder(recordName, DnsRecord.Type.A) + RecordSet recordSet = RecordSet.builder(recordName, RecordSet.Type.A) .records(ImmutableList.of(ip)) .ttl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequest changeRequest = ChangeRequest.builder().add(record).build(); + ChangeRequest changeRequest = ChangeRequest.builder().add(recordSet).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()); @@ -283,21 +283,21 @@ public boolean check(String... args) { private static class ListDnsRecordsAction implements DnsAction { /** - * Lists all the DNS records in the given zone. + * Lists all the record sets in the given zone. */ @Override public void run(Dns dns, String... args) { String zoneName = args[0]; - Iterator iterator = dns.listDnsRecords(zoneName).iterateAll(); + Iterator iterator = dns.listRecordSets(zoneName).iterateAll(); if (iterator.hasNext()) { - System.out.printf("DNS records for zone %s:%n", zoneName); + System.out.printf("Record sets 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())); + RecordSet recordSet = iterator.next(); + System.out.printf("%nRecord name: %s%nTTL: %s%nRecords: %s%n", recordSet.name(), + recordSet.ttl(), Joiner.on(", ").join(recordSet.records())); } } else { - System.out.printf("Zone %s has no DNS records.%n", zoneName); + System.out.printf("Zone %s has no record sets records.%n", zoneName); } } @@ -361,8 +361,8 @@ 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. + * parameter provided, lists both record sets and changes. Otherwise, invokes listing + * changes or zones based on the parameter provided. */ @Override public void run(Dns dns, String... args) { @@ -406,7 +406,7 @@ public void run(Dns dns, String... args) { 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 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()); diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java similarity index 83% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java index 71327ba98a96..74647daf666e 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateDnsRecords.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java @@ -25,16 +25,16 @@ 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.RecordSet; 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 and update a DNS record. + * A snippet for Google Cloud DNS showing how to create and update a resource record set. */ -public class CreateOrUpdateDnsRecords { +public class CreateOrUpdateRecordSets { public static void main(String... args) { // Create a service object. @@ -47,9 +47,9 @@ public static void main(String... args) { // Get zone from the service Zone zone = dns.getZone(zoneName); - // Prepare a www.. type A record with ttl of 24 hours + // Prepare a www.. type A record set with ttl of 24 hours String ip = "12.13.14.15"; - DnsRecord toCreate = DnsRecord.builder("www." + zone.dnsName(), DnsRecord.Type.A) + RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); @@ -59,9 +59,9 @@ public static void main(String... args) { // 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(); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } 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 index e841a4cd54ed..27377345b62f 100644 --- 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 @@ -25,7 +25,7 @@ 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.RecordSet; import java.util.Iterator; @@ -43,15 +43,15 @@ public static void main(String... args) { // Change this to a zone name that exists within your project and that you want to delete. String zoneName = "my-unique-zone"; - // Get iterator for the existing records which have to be deleted before deleting the zone - Iterator recordIterator = dns.listDnsRecords(zoneName).iterateAll(); + // Get iterator for the existing record sets which have to be deleted before deleting the zone + Iterator recordIterator = dns.listRecordSets(zoneName).iterateAll(); // Make a change for deleting the records ChangeRequest.Builder changeBuilder = ChangeRequest.builder(); while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted - if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { changeBuilder.delete(current); } } diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java similarity index 84% rename from gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java rename to gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java index 4de262386d53..6d9d09d704a6 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecords.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java @@ -25,7 +25,7 @@ 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.RecordSet; import com.google.gcloud.dns.Zone; import com.google.gcloud.dns.ZoneInfo; @@ -35,9 +35,9 @@ /** * A complete snippet for Google Cloud DNS showing how to create and delete a zone. It also shows - * how to create, list and delete DNS records, and how to list changes. + * how to create, list and delete record sets, and how to list changes. */ -public class ManipulateZonesAndRecords { +public class ManipulateZonesAndRecordSets { public static void main(String... args) { Dns dns = DnsOptions.defaultInstance().service(); @@ -60,7 +60,7 @@ public static void main(String... args) { // 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) + RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); @@ -70,9 +70,9 @@ public static void main(String... args) { // Verify the 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(); + Iterator recordSetIterator = zone.listRecordSets().iterateAll(); + while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { changeBuilder.delete(current); } @@ -100,11 +100,11 @@ public static void main(String... args) { counter++; } - // List the DNS records in a particular zone - recordIterator = zone.listDnsRecords().iterateAll(); - System.out.println(String.format("DNS records inside %s:", zone.name())); - while (recordIterator.hasNext()) { - System.out.println(recordIterator.next()); + // List the record sets in a particular zone + recordSetIterator = zone.listRecordSets().iterateAll(); + System.out.println(String.format("Record sets inside %s:", zone.name())); + while (recordSetIterator.hasNext()) { + System.out.println(recordSetIterator.next()); } // List the change requests applied to a particular zone @@ -114,12 +114,12 @@ public static void main(String... args) { System.out.println(changeIterator.next()); } - // Make a change for deleting the records + // Make a change for deleting the record sets changeBuilder = ChangeRequest.builder(); - while (recordIterator.hasNext()) { - DnsRecord current = recordIterator.next(); + while (recordSetIterator.hasNext()) { + RecordSet current = recordSetIterator.next(); // SOA and NS records cannot be deleted - if (!DnsRecord.Type.SOA.equals(current.type()) && !DnsRecord.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { changeBuilder.delete(current); } } From 01e23100fb12bf855f31b2ab8c4d12e43de9aab8 Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Thu, 24 Mar 2016 16:46:09 -0700 Subject: [PATCH 73/74] Turned ChangeRequest into a functional object. --- .../com/google/gcloud/dns/ChangeRequest.java | 265 ++++--------- .../google/gcloud/dns/ChangeRequestInfo.java | 347 ++++++++++++++++++ .../main/java/com/google/gcloud/dns/Dns.java | 4 +- .../java/com/google/gcloud/dns/DnsImpl.java | 11 +- .../main/java/com/google/gcloud/dns/Zone.java | 2 +- .../gcloud/dns/ChangeRequestInfoTest.java | 218 +++++++++++ .../google/gcloud/dns/ChangeRequestTest.java | 269 +++++--------- .../com/google/gcloud/dns/DnsImplTest.java | 4 +- .../google/gcloud/dns/SerializationTest.java | 14 +- .../java/com/google/gcloud/dns/ZoneTest.java | 44 ++- .../com/google/gcloud/dns/it/ITDnsTest.java | 13 +- 11 files changed, 791 insertions(+), 400 deletions(-) create mode 100644 gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java create mode 100644 gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index 757d844cc3da..ad1c65f7cb0f 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -16,19 +16,11 @@ package com.google.gcloud.dns; -import static com.google.common.base.Preconditions.checkNotNull; - import com.google.api.services.dns.model.Change; import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import org.joda.time.DateTime; -import org.joda.time.format.ISODateTimeFormat; -import java.io.Serializable; -import java.util.LinkedList; +import java.io.IOException; +import java.io.ObjectInputStream; import java.util.List; import java.util.Objects; @@ -38,21 +30,12 @@ * * @see Google Cloud DNS documentation */ -public class ChangeRequest implements Serializable { +public class ChangeRequest extends ChangeRequestInfo { - static final Function FROM_PB_FUNCTION = - new Function() { - @Override - public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { - return ChangeRequest.fromPb(pb); - } - }; private static final long serialVersionUID = -9027378042756366333L; - private final List additions; - private final List deletions; - private final String id; - private final Long startTimeMillis; - private final Status status; + private final DnsOptions options; + private final String zoneName; + private transient Dns dns; /** * This enumerates the possible states of a {@code ChangeRequest}. @@ -68,250 +51,152 @@ public enum Status { /** * A builder for {@code ChangeRequest}s. */ - public static class Builder { + public static class Builder extends ChangeRequestInfo.Builder { - private List additions = new LinkedList<>(); - private List deletions = new LinkedList<>(); - private String id; - private Long startTimeMillis; - private Status status; + private final Dns dns; + private final String zoneName; + private final ChangeRequestInfo.BuilderImpl infoBuilder; private Builder(ChangeRequest cr) { - this.additions = Lists.newLinkedList(cr.additions()); - this.deletions = Lists.newLinkedList(cr.deletions()); - this.id = cr.id(); - this.startTimeMillis = cr.startTimeMillis(); - this.status = cr.status(); + this.dns = cr.dns; + this.zoneName = cr.zoneName; + this.infoBuilder = new ChangeRequestInfo.BuilderImpl(cr); } - private Builder() { - } - - /** - * Sets a collection of {@link RecordSet}s which are to be added to the zone upon executing this - * {@code ChangeRequest}. - */ + @Override public Builder additions(List additions) { - this.additions = Lists.newLinkedList(checkNotNull(additions)); + infoBuilder.additions(additions); return this; } - /** - * Sets a collection of {@link RecordSet}s which are to be deleted from the zone upon executing - * this {@code ChangeRequest}. - */ + @Override public Builder deletions(List deletions) { - this.deletions = Lists.newLinkedList(checkNotNull(deletions)); + infoBuilder.deletions(deletions); return this; } - /** - * Adds a {@link RecordSet} to be added to the zone upon executing this {@code - * ChangeRequest}. - */ + @Override public Builder add(RecordSet recordSet) { - this.additions.add(checkNotNull(recordSet)); + infoBuilder.add(recordSet); return this; } - /** - * Adds a {@link RecordSet} to be deleted to the zone upon executing this - * {@code ChangeRequest}. - */ + @Override public Builder delete(RecordSet recordSet) { - this.deletions.add(checkNotNull(recordSet)); + infoBuilder.delete(recordSet); return this; } - /** - * Clears the collection of {@link RecordSet}s which are to be added to the zone upon executing - * this {@code ChangeRequest}. - */ + @Override public Builder clearAdditions() { - this.additions.clear(); + infoBuilder.clearAdditions(); return this; } - /** - * Clears the collection of {@link RecordSet}s which are to be deleted from the zone upon - * executing this {@code ChangeRequest}. - */ + @Override public Builder clearDeletions() { - this.deletions.clear(); + infoBuilder.clearDeletions(); return this; } - /** - * Removes a single {@link RecordSet} from the collection of records to be - * added to the zone upon executing this {@code ChangeRequest}. - */ + @Override public Builder removeAddition(RecordSet recordSet) { - this.additions.remove(recordSet); + infoBuilder.removeAddition(recordSet); return this; } - /** - * Removes a single {@link RecordSet} from the collection of records to be - * deleted from the zone upon executing this {@code ChangeRequest}. - */ + @Override public Builder removeDeletion(RecordSet recordSet) { - this.deletions.remove(recordSet); + infoBuilder.removeDeletion(recordSet); return this; } - /** - * Associates a server-assigned id to this {@code ChangeRequest}. - */ + @Override Builder id(String id) { - this.id = checkNotNull(id); + infoBuilder.id(id); return this; } - /** - * Sets the time when this {@code ChangeRequest} was started by a server. - */ + @Override Builder startTimeMillis(long startTimeMillis) { - this.startTimeMillis = startTimeMillis; + infoBuilder.startTimeMillis(startTimeMillis); return this; } - /** - * Sets the current status of this {@code ChangeRequest}. - */ + @Override Builder status(Status status) { - this.status = checkNotNull(status); + infoBuilder.status(status); return this; } - /** - * Creates a {@code ChangeRequest} instance populated by the values associated with this - * builder. - */ + @Override public ChangeRequest build() { - return new ChangeRequest(this); + return new ChangeRequest(dns, zoneName, infoBuilder); } } - private ChangeRequest(Builder builder) { - this.additions = ImmutableList.copyOf(builder.additions); - this.deletions = ImmutableList.copyOf(builder.deletions); - this.id = builder.id; - this.startTimeMillis = builder.startTimeMillis; - this.status = builder.status; - } - - /** - * Returns an empty builder for the {@code ChangeRequest} class. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Creates a builder populated with values of this {@code ChangeRequest}. - */ - public Builder toBuilder() { - return new Builder(this); - } - - /** - * Returns the list of {@link RecordSet}s to be added to the zone upon submitting this {@code - * ChangeRequest}. - */ - public List additions() { - return additions; + ChangeRequest(Dns dns, String zoneName, ChangeRequest.BuilderImpl infoBuilder) { + super(infoBuilder); + this.zoneName = zoneName; + this.dns = dns; + this.options = dns.options(); } - /** - * Returns the list of {@link RecordSet}s to be deleted from the zone upon submitting this {@code - * ChangeRequest}. - */ - public List deletions() { - return deletions; + static Function fromPbFunction(final Dns dns, final String zoneName) { + return new Function() { + @Override + public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { + return ChangeRequest.fromPb(dns, zoneName, pb); + } + }; } /** - * Returns the id assigned to this {@code ChangeRequest} by the server. + * Returns the name of the {@link Zone} associated with this change request. */ - public String id() { - return id; + public String zoneName() { + return this.zoneName; } /** - * Returns the time when this {@code ChangeRequest} was started by the server. + * Returns the {@link Dns} service object associated with this change request. */ - public Long startTimeMillis() { - return startTimeMillis; + public Dns dns() { + return dns; } /** - * Returns the status of this {@code ChangeRequest}. + * Applies this change request to a zone that it is associated with. */ - public Status status() { - return status; + public ChangeRequest applyTo(Dns.ChangeRequestOption... options) { + return dns.applyChangeRequest(zoneName, this, options); } - com.google.api.services.dns.model.Change toPb() { - com.google.api.services.dns.model.Change pb = - new com.google.api.services.dns.model.Change(); - // set id - if (id() != null) { - pb.setId(id()); - } - // set timestamp - if (startTimeMillis() != null) { - pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(startTimeMillis())); - } - // set status - if (status() != null) { - pb.setStatus(status().name().toLowerCase()); - } - // set a list of additions - pb.setAdditions(Lists.transform(additions(), RecordSet.TO_PB_FUNCTION)); - // set a list of deletions - pb.setDeletions(Lists.transform(deletions(), RecordSet.TO_PB_FUNCTION)); - return pb; - } - - static ChangeRequest fromPb(com.google.api.services.dns.model.Change pb) { - Builder builder = builder(); - if (pb.getId() != null) { - builder.id(pb.getId()); - } - if (pb.getStartTime() != null) { - builder.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); - } - if (pb.getStatus() != null) { - // we are assuming that status indicated in pb is a lower case version of the enum name - builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); - } - if (pb.getDeletions() != null) { - builder.deletions(Lists.transform(pb.getDeletions(), RecordSet.FROM_PB_FUNCTION)); - } - if (pb.getAdditions() != null) { - builder.additions(Lists.transform(pb.getAdditions(), RecordSet.FROM_PB_FUNCTION)); - } - return builder.build(); + @Override + public Builder toBuilder() { + return new Builder(this); } @Override - public boolean equals(Object other) { - return (other instanceof ChangeRequest) && toPb().equals(((ChangeRequest) other).toPb()); + public boolean equals(Object obj) { + return obj instanceof ChangeRequest && Objects.equals(toPb(), ((ChangeRequest) obj).toPb()) + && Objects.equals(options, ((ChangeRequest) obj).options) + && Objects.equals(zoneName, ((ChangeRequest) obj).zoneName); } @Override public int hashCode() { - return Objects.hash(additions, deletions, id, startTimeMillis, status); + return Objects.hash(super.hashCode(), options, zoneName); } - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("additions", additions) - .add("deletions", deletions) - .add("id", id) - .add("startTimeMillis", startTimeMillis) - .add("status", status) - .toString(); + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + this.dns = options.service(); + } + + static ChangeRequest fromPb(Dns dns, String zoneName, + com.google.api.services.dns.model.Change pb) { + ChangeRequestInfo info = ChangeRequestInfo.fromPb(pb); + return new ChangeRequest(dns, zoneName, new ChangeRequestInfo.BuilderImpl(info)); } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java new file mode 100644 index 000000000000..25b915521b13 --- /dev/null +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java @@ -0,0 +1,347 @@ +/* + * 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.dns; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.api.services.dns.model.Change; +import com.google.common.base.Function; +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; + +/** + * A class representing an atomic update to a collection of {@link RecordSet}s within a {@code + * Zone}. + * + * @see Google Cloud DNS documentation + */ +public class ChangeRequestInfo implements Serializable { + + static final Function FROM_PB_FUNCTION = + new Function() { + @Override + public ChangeRequestInfo apply(Change pb) { + return ChangeRequestInfo.fromPb(pb); + } + }; + private static final long serialVersionUID = -9027378042756366333L; + private final List additions; + private final List deletions; + private final String id; + private final Long startTimeMillis; + private final ChangeRequest.Status status; + + /** + * A builder for {@code ChangeRequestInfo}. + */ + public abstract static class Builder { + + /** + * Sets a collection of {@link RecordSet}s which are to be added to the zone upon executing this + * {@code ChangeRequestInfo}. + */ + public abstract Builder additions(List additions); + + /** + * Sets a collection of {@link RecordSet}s which are to be deleted from the zone upon executing + * this {@code ChangeRequestInfo}. + */ + public abstract Builder deletions(List deletions); + + /** + * Adds a {@link RecordSet} to be added to the zone upon executing this {@code + * ChangeRequestInfo}. + */ + public abstract Builder add(RecordSet recordSet); + + /** + * Adds a {@link RecordSet} to be deleted to the zone upon executing this + * {@code ChangeRequestInfo}. + */ + public abstract Builder delete(RecordSet recordSet); + + /** + * Clears the collection of {@link RecordSet}s which are to be added to the zone upon executing + * this {@code ChangeRequestInfo}. + */ + public abstract Builder clearAdditions(); + + /** + * Clears the collection of {@link RecordSet}s which are to be deleted from the zone upon + * executing this {@code ChangeRequestInfo}. + */ + public abstract Builder clearDeletions(); + + /** + * Removes a single {@link RecordSet} from the collection of records to be + * added to the zone upon executing this {@code ChangeRequestInfo}. + */ + public abstract Builder removeAddition(RecordSet recordSet); + + /** + * Removes a single {@link RecordSet} from the collection of records to be + * deleted from the zone upon executing this {@code ChangeRequestInfo}. + */ + public abstract Builder removeDeletion(RecordSet recordSet); + + /** + * Associates a server-assigned id to this {@code ChangeRequestInfo}. + */ + abstract Builder id(String id); + + /** + * Sets the time when this change request was started by a server. + */ + abstract Builder startTimeMillis(long startTimeMillis); + + /** + * Sets the current status of this {@code ChangeRequest}. + */ + abstract Builder status(ChangeRequest.Status status); + + /** + * Creates a {@code ChangeRequestInfo} instance populated by the values associated with this + * builder. + */ + public abstract ChangeRequestInfo build(); + } + + static class BuilderImpl extends Builder { + private List additions; + private List deletions; + private String id; + private Long startTimeMillis; + private ChangeRequest.Status status; + + BuilderImpl() { + this.additions = new LinkedList<>(); + this.deletions = new LinkedList<>(); + } + + BuilderImpl(ChangeRequestInfo info) { + this.additions = Lists.newLinkedList(info.additions()); + this.deletions = Lists.newLinkedList(info.deletions()); + this.id = info.id(); + this.startTimeMillis = info.startTimeMillis; + this.status = info.status; + } + + @Override + public Builder additions(List additions) { + this.additions = Lists.newLinkedList(checkNotNull(additions)); + return this; + } + + @Override + public Builder deletions(List deletions) { + this.deletions = Lists.newLinkedList(checkNotNull(deletions)); + return this; + } + + @Override + public Builder add(RecordSet recordSet) { + this.additions.add(checkNotNull(recordSet)); + return this; + } + + @Override + public Builder delete(RecordSet recordSet) { + this.deletions.add(checkNotNull(recordSet)); + return this; + } + + @Override + public Builder clearAdditions() { + this.additions.clear(); + return this; + } + + @Override + public Builder clearDeletions() { + this.deletions.clear(); + return this; + } + + @Override + public Builder removeAddition(RecordSet recordSet) { + this.additions.remove(recordSet); + return this; + } + + @Override + public Builder removeDeletion(RecordSet recordSet) { + this.deletions.remove(recordSet); + return this; + } + + @Override + public ChangeRequestInfo build() { + return new ChangeRequestInfo(this); + } + + @Override + Builder id(String id) { + this.id = checkNotNull(id); + return this; + } + + @Override + Builder startTimeMillis(long startTimeMillis) { + this.startTimeMillis = startTimeMillis; + return this; + } + + @Override + Builder status(ChangeRequest.Status status) { + this.status = checkNotNull(status); + return this; + } + } + + ChangeRequestInfo(BuilderImpl builder) { + this.additions = ImmutableList.copyOf(builder.additions); + this.deletions = ImmutableList.copyOf(builder.deletions); + this.id = builder.id; + this.startTimeMillis = builder.startTimeMillis; + this.status = builder.status; + } + + /** + * Returns an empty builder for the {@code ChangeRequestInfo} class. + */ + public static Builder builder() { + return new BuilderImpl(); + } + + /** + * Creates a builder populated with values of this {@code ChangeRequestInfo}. + */ + public Builder toBuilder() { + return new BuilderImpl(this); + } + + /** + * Returns the list of {@link RecordSet}s to be added to the zone upon submitting this change + * request. + */ + public List additions() { + return additions; + } + + /** + * Returns the list of {@link RecordSet}s to be deleted from the zone upon submitting this change + * request. + */ + public List deletions() { + return deletions; + } + + /** + * Returns the id assigned to this {@code ChangeRequest} by the server. + */ + public String id() { + return id; + } + + /** + * Returns the time when this {@code ChangeRequest} was started by the server. + */ + public Long startTimeMillis() { + return startTimeMillis; + } + + /** + * Returns the status of this {@code ChangeRequest}. + */ + public ChangeRequest.Status status() { + return status; + } + + com.google.api.services.dns.model.Change toPb() { + com.google.api.services.dns.model.Change pb = + new com.google.api.services.dns.model.Change(); + // set id + if (id() != null) { + pb.setId(id()); + } + // set timestamp + if (startTimeMillis() != null) { + pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(startTimeMillis())); + } + // set status + if (status() != null) { + pb.setStatus(status().name().toLowerCase()); + } + // set a list of additions + pb.setAdditions(Lists.transform(additions(), RecordSet.TO_PB_FUNCTION)); + // set a list of deletions + pb.setDeletions(Lists.transform(deletions(), RecordSet.TO_PB_FUNCTION)); + return pb; + } + + static ChangeRequestInfo fromPb(com.google.api.services.dns.model.Change pb) { + Builder builder = builder(); + if (pb.getId() != null) { + builder.id(pb.getId()); + } + if (pb.getStartTime() != null) { + builder.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); + } + if (pb.getStatus() != null) { + // we are assuming that status indicated in pb is a lower case version of the enum name + builder.status(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); + } + if (pb.getDeletions() != null) { + builder.deletions(Lists.transform(pb.getDeletions(), RecordSet.FROM_PB_FUNCTION)); + } + if (pb.getAdditions() != null) { + builder.additions(Lists.transform(pb.getAdditions(), RecordSet.FROM_PB_FUNCTION)); + } + return builder.build(); + } + + @Override + public boolean equals(Object other) { + return (other instanceof ChangeRequestInfo) + && toPb().equals(((ChangeRequestInfo) other).toPb()); + } + + @Override + public int hashCode() { + return Objects.hash(additions, deletions, id, startTimeMillis, status); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("additions", additions) + .add("deletions", deletions) + .add("id", id) + .add("startTimeMillis", startTimeMillis) + .add("status", status) + .toString(); + } +} diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java index f8614a8d6169..f2b42f30a9f6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Dns.java @@ -138,7 +138,7 @@ static String selector(RecordSetField... fields) { * The fields of a change request. * *

      These values can be used to specify the fields to include in a partial response when calling - * {@link Dns#applyChangeRequest(String, ChangeRequest, ChangeRequestOption...)} The ID is always + * {@link Dns#applyChangeRequest(String, ChangeRequestInfo, ChangeRequestOption...)} The ID is always * returned even if not selected. */ enum ChangeRequestField { @@ -508,7 +508,7 @@ public static ChangeRequestListOption sortOrder(SortingOrder order) { * @throws DnsException upon failure if zone is not found * @see Cloud DNS Changes: create */ - ChangeRequest applyChangeRequest(String zoneName, ChangeRequest changeRequest, + ChangeRequest applyChangeRequest(String zoneName, ChangeRequestInfo changeRequest, ChangeRequestOption... options); /** diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index 2fbf4e8b5a79..4e2bd1b207d5 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -169,7 +169,8 @@ public DnsRpc.ListResult call() { // transform that list into change request objects Iterable changes = result.results() == null ? ImmutableList.of() - : Iterables.transform(result.results(), ChangeRequest.FROM_PB_FUNCTION); + : Iterables.transform(result.results(), + ChangeRequest.fromPbFunction(serviceOptions.service(), zoneName)); return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, changes); } catch (RetryHelperException e) { @@ -272,8 +273,8 @@ public com.google.api.services.dns.model.Project call() { } @Override - public ChangeRequest applyChangeRequest(final String zoneName, final ChangeRequest changeRequest, - Dns.ChangeRequestOption... options) { + public ChangeRequest applyChangeRequest(final String zoneName, + final ChangeRequestInfo changeRequest, ChangeRequestOption... options) { final Map optionsMap = optionMap(options); try { com.google.api.services.dns.model.Change answer = @@ -284,7 +285,7 @@ public com.google.api.services.dns.model.Change call() { return dnsRpc.applyChangeRequest(zoneName, changeRequest.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); - return answer == null ? null : fromPb(answer); // should never be null + return answer == null ? null : fromPb(this, zoneName, answer); // should never be null } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } @@ -303,7 +304,7 @@ public com.google.api.services.dns.model.Change call() { return dnsRpc.getChangeRequest(zoneName, changeRequestId, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); - return answer == null ? null : fromPb(answer); + return answer == null ? null : ChangeRequest.fromPb(this, zoneName, answer); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index aed99dbd0001..88b9e7273e9c 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -153,7 +153,7 @@ public Page listRecordSets(Dns.RecordSetListOption... options) { * @return ChangeRequest with server-assigned ID * @throws DnsException upon failure or if the zone is not found */ - public ChangeRequest applyChangeRequest(ChangeRequest changeRequest, + public ChangeRequest applyChangeRequest(ChangeRequestInfo changeRequest, Dns.ChangeRequestOption... options) { checkNotNull(changeRequest); return dns.applyChangeRequest(name(), changeRequest, options); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java new file mode 100644 index 000000000000..55f2af0824ec --- /dev/null +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestInfoTest.java @@ -0,0 +1,218 @@ +/* + * 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.dns; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.common.collect.ImmutableList; + +import org.junit.Test; + +import java.util.List; + +public class ChangeRequestInfoTest { + + private static final String ID = "cr-id-1"; + private static final Long START_TIME_MILLIS = 12334567890L; + private static final ChangeRequest.Status STATUS = ChangeRequest.Status.PENDING; + private static final String NAME1 = "dns1"; + private static final RecordSet.Type TYPE1 = RecordSet.Type.A; + private static final String NAME2 = "dns2"; + private static final RecordSet.Type TYPE2 = RecordSet.Type.AAAA; + private static final String NAME3 = "dns3"; + private static final RecordSet.Type TYPE3 = RecordSet.Type.MX; + private static final RecordSet RECORD1 = RecordSet.builder(NAME1, TYPE1).build(); + private static final RecordSet RECORD2 = RecordSet.builder(NAME2, TYPE2).build(); + private static final RecordSet RECORD3 = RecordSet.builder(NAME3, TYPE3).build(); + private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); + private static final List DELETIONS = ImmutableList.of(RECORD3); + private static final ChangeRequestInfo CHANGE = ChangeRequest.builder() + .add(RECORD1) + .add(RECORD2) + .delete(RECORD3) + .startTimeMillis(START_TIME_MILLIS) + .status(STATUS) + .id(ID) + .build(); + + @Test + public void testEmptyBuilder() { + ChangeRequestInfo cr = ChangeRequest.builder().build(); + assertNotNull(cr.deletions()); + assertTrue(cr.deletions().isEmpty()); + assertNotNull(cr.additions()); + assertTrue(cr.additions().isEmpty()); + } + + @Test + public void testBuilder() { + assertEquals(ID, CHANGE.id()); + assertEquals(STATUS, CHANGE.status()); + assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); + assertEquals(ADDITIONS, CHANGE.additions()); + assertEquals(DELETIONS, CHANGE.deletions()); + List recordList = ImmutableList.of(RECORD1); + ChangeRequestInfo another = CHANGE.toBuilder().additions(recordList).build(); + assertEquals(recordList, another.additions()); + assertEquals(CHANGE.deletions(), another.deletions()); + another = CHANGE.toBuilder().deletions(recordList).build(); + assertEquals(recordList, another.deletions()); + assertEquals(CHANGE.additions(), another.additions()); + } + + @Test + public void testEqualsAndNotEquals() { + ChangeRequestInfo clone = CHANGE.toBuilder().build(); + assertEquals(CHANGE, clone); + clone = ChangeRequest.fromPb(CHANGE.toPb()); + assertEquals(CHANGE, clone); + clone = CHANGE.toBuilder().id("some-other-id").build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().startTimeMillis(CHANGE.startTimeMillis() + 1).build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().add(RECORD3).build(); + assertNotEquals(CHANGE, clone); + clone = CHANGE.toBuilder().delete(RECORD1).build(); + assertNotEquals(CHANGE, clone); + ChangeRequestInfo empty = ChangeRequest.builder().build(); + assertNotEquals(CHANGE, empty); + assertEquals(empty, ChangeRequest.builder().build()); + } + + @Test + public void testSameHashCodeOnEquals() { + ChangeRequestInfo clone = CHANGE.toBuilder().build(); + assertEquals(CHANGE, clone); + assertEquals(CHANGE.hashCode(), clone.hashCode()); + ChangeRequestInfo empty = ChangeRequest.builder().build(); + assertEquals(empty.hashCode(), ChangeRequest.builder().build().hashCode()); + } + + @Test + public void testToAndFromPb() { + assertEquals(CHANGE, ChangeRequest.fromPb(CHANGE.toPb())); + ChangeRequestInfo partial = ChangeRequest.builder().build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().id(ID).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().add(RECORD1).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().delete(RECORD1).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().additions(ADDITIONS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().deletions(DELETIONS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + partial = ChangeRequest.builder().status(STATUS).build(); + assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); + } + + @Test + public void testToBuilder() { + assertEquals(CHANGE, CHANGE.toBuilder().build()); + ChangeRequestInfo partial = ChangeRequest.builder().build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().id(ID).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().add(RECORD1).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().delete(RECORD1).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().additions(ADDITIONS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().deletions(DELETIONS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + assertEquals(partial, partial.toBuilder().build()); + partial = ChangeRequest.builder().status(STATUS).build(); + assertEquals(partial, partial.toBuilder().build()); + } + + @Test + public void testClearAdditions() { + ChangeRequestInfo clone = CHANGE.toBuilder().clearAdditions().build(); + assertTrue(clone.additions().isEmpty()); + assertFalse(clone.deletions().isEmpty()); + } + + @Test + public void testAddAddition() { + try { + CHANGE.toBuilder().add(null); + fail("Should not be able to add null RecordSet."); + } catch (NullPointerException e) { + // expected + } + ChangeRequestInfo clone = CHANGE.toBuilder().add(RECORD1).build(); + assertEquals(CHANGE.additions().size() + 1, clone.additions().size()); + } + + @Test + public void testAddDeletion() { + try { + CHANGE.toBuilder().delete(null); + fail("Should not be able to delete null RecordSet."); + } catch (NullPointerException e) { + // expected + } + ChangeRequestInfo clone = CHANGE.toBuilder().delete(RECORD1).build(); + assertEquals(CHANGE.deletions().size() + 1, clone.deletions().size()); + } + + @Test + public void testClearDeletions() { + ChangeRequestInfo clone = CHANGE.toBuilder().clearDeletions().build(); + assertTrue(clone.deletions().isEmpty()); + assertFalse(clone.additions().isEmpty()); + } + + @Test + public void testRemoveAddition() { + ChangeRequestInfo clone = CHANGE.toBuilder().removeAddition(RECORD1).build(); + assertTrue(clone.additions().contains(RECORD2)); + assertFalse(clone.additions().contains(RECORD1)); + assertTrue(clone.deletions().contains(RECORD3)); + clone = CHANGE.toBuilder().removeAddition(RECORD2).removeAddition(RECORD1).build(); + assertFalse(clone.additions().contains(RECORD2)); + assertFalse(clone.additions().contains(RECORD1)); + assertTrue(clone.additions().isEmpty()); + assertTrue(clone.deletions().contains(RECORD3)); + } + + @Test + public void testRemoveDeletion() { + ChangeRequestInfo clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); + assertTrue(clone.deletions().isEmpty()); + } + + @Test + public void testDateParsing() { + String startTime = "2016-01-26T18:33:43.512Z"; // obtained from service + com.google.api.services.dns.model.Change change = CHANGE.toPb().setStartTime(startTime); + ChangeRequestInfo converted = ChangeRequest.fromPb(change); + assertNotNull(converted.startTimeMillis()); + assertEquals(change, converted.toPb()); + assertEquals(change.getStartTime(), converted.toPb().getStartTime()); + } +} diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java index fe726acb7c10..8d6cc799cad8 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java @@ -16,203 +16,132 @@ package com.google.gcloud.dns; +import static org.easymock.EasyMock.createStrictMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reset; +import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import java.util.List; - public class ChangeRequestTest { - private static final String ID = "cr-id-1"; - private static final Long START_TIME_MILLIS = 12334567890L; - private static final ChangeRequest.Status STATUS = ChangeRequest.Status.PENDING; - private static final String NAME1 = "dns1"; - private static final RecordSet.Type TYPE1 = RecordSet.Type.A; - private static final String NAME2 = "dns2"; - private static final RecordSet.Type TYPE2 = RecordSet.Type.AAAA; - private static final String NAME3 = "dns3"; - private static final RecordSet.Type TYPE3 = RecordSet.Type.MX; - private static final RecordSet RECORD1 = RecordSet.builder(NAME1, TYPE1).build(); - private static final RecordSet RECORD2 = RecordSet.builder(NAME2, TYPE2).build(); - private static final RecordSet RECORD3 = RecordSet.builder(NAME3, TYPE3).build(); - private static final List ADDITIONS = ImmutableList.of(RECORD1, RECORD2); - private static final List DELETIONS = ImmutableList.of(RECORD3); - private static final ChangeRequest CHANGE = ChangeRequest.builder() - .add(RECORD1) - .add(RECORD2) - .delete(RECORD3) - .startTimeMillis(START_TIME_MILLIS) - .status(STATUS) - .id(ID) + private static final String ZONE_NAME = "dns-zone-name"; + private static final ChangeRequestInfo CHANGE_REQUEST_INFO = ChangeRequest.builder() + .add(RecordSet.builder("name", RecordSet.Type.A).build()) + .delete(RecordSet.builder("othername", RecordSet.Type.AAAA).build()) .build(); - - @Test - public void testEmptyBuilder() { - ChangeRequest cr = ChangeRequest.builder().build(); - assertNotNull(cr.deletions()); - assertTrue(cr.deletions().isEmpty()); - assertNotNull(cr.additions()); - assertTrue(cr.additions().isEmpty()); - } - - @Test - public void testBuilder() { - assertEquals(ID, CHANGE.id()); - assertEquals(STATUS, CHANGE.status()); - assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); - assertEquals(ADDITIONS, CHANGE.additions()); - assertEquals(DELETIONS, CHANGE.deletions()); - List recordList = ImmutableList.of(RECORD1); - ChangeRequest another = CHANGE.toBuilder().additions(recordList).build(); - assertEquals(recordList, another.additions()); - assertEquals(CHANGE.deletions(), another.deletions()); - another = CHANGE.toBuilder().deletions(recordList).build(); - assertEquals(recordList, another.deletions()); - assertEquals(CHANGE.additions(), another.additions()); - } - - @Test - public void testEqualsAndNotEquals() { - ChangeRequest clone = CHANGE.toBuilder().build(); - assertEquals(CHANGE, clone); - clone = ChangeRequest.fromPb(CHANGE.toPb()); - assertEquals(CHANGE, clone); - clone = CHANGE.toBuilder().id("some-other-id").build(); - assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().startTimeMillis(CHANGE.startTimeMillis() + 1).build(); - assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().add(RECORD3).build(); - assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().delete(RECORD1).build(); - assertNotEquals(CHANGE, clone); - ChangeRequest empty = ChangeRequest.builder().build(); - assertNotEquals(CHANGE, empty); - assertEquals(empty, ChangeRequest.builder().build()); - } - - @Test - public void testSameHashCodeOnEquals() { - ChangeRequest clone = CHANGE.toBuilder().build(); - assertEquals(CHANGE, clone); - assertEquals(CHANGE.hashCode(), clone.hashCode()); - ChangeRequest empty = ChangeRequest.builder().build(); - assertEquals(empty.hashCode(), ChangeRequest.builder().build().hashCode()); - } - - @Test - public void testToAndFromPb() { - assertEquals(CHANGE, ChangeRequest.fromPb(CHANGE.toPb())); - ChangeRequest partial = ChangeRequest.builder().build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().id(ID).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().add(RECORD1).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().delete(RECORD1).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().additions(ADDITIONS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().deletions(DELETIONS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().status(STATUS).build(); - assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - } - - @Test - public void testToBuilder() { - assertEquals(CHANGE, CHANGE.toBuilder().build()); - ChangeRequest partial = ChangeRequest.builder().build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().id(ID).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().add(RECORD1).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().delete(RECORD1).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().additions(ADDITIONS).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().deletions(DELETIONS).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); - assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().status(STATUS).build(); - assertEquals(partial, partial.toBuilder().build()); - } - - @Test - public void testClearAdditions() { - ChangeRequest clone = CHANGE.toBuilder().clearAdditions().build(); - assertTrue(clone.additions().isEmpty()); - assertFalse(clone.deletions().isEmpty()); + private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); + + private Dns dns; + private ChangeRequest changeRequest; + private ChangeRequest changeRequestPartial; + + @Before + public void setUp() throws Exception { + dns = createStrictMock(Dns.class); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + replay(dns); + changeRequest = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( + CHANGE_REQUEST_INFO.toBuilder() + .startTimeMillis(132L) + .id("12") + .status(ChangeRequest.Status.DONE) + .build())); + changeRequestPartial = new ChangeRequest(dns, ZONE_NAME, + new ChangeRequest.BuilderImpl(CHANGE_REQUEST_INFO)); + reset(dns); } - @Test - public void testAddAddition() { - try { - CHANGE.toBuilder().add(null); - fail("Should not be able to add null RecordSet."); - } catch (NullPointerException e) { - // expected - } - ChangeRequest clone = CHANGE.toBuilder().add(RECORD1).build(); - assertEquals(CHANGE.additions().size() + 1, clone.additions().size()); + @After + public void tearDown() throws Exception { + verify(dns); } @Test - public void testAddDeletion() { - try { - CHANGE.toBuilder().delete(null); - fail("Should not be able to delete null RecordSet."); - } catch (NullPointerException e) { - // expected - } - ChangeRequest clone = CHANGE.toBuilder().delete(RECORD1).build(); - assertEquals(CHANGE.deletions().size() + 1, clone.deletions().size()); + public void testConstructor() { + replay(dns); + assertEquals(CHANGE_REQUEST_INFO.toPb(), changeRequestPartial.toPb()); + assertNotNull(changeRequest.dns()); + assertEquals(ZONE_NAME, changeRequest.zoneName()); + assertNotNull(changeRequestPartial.dns()); + assertEquals(ZONE_NAME, changeRequestPartial.zoneName()); } @Test - public void testClearDeletions() { - ChangeRequest clone = CHANGE.toBuilder().clearDeletions().build(); - assertTrue(clone.deletions().isEmpty()); - assertFalse(clone.additions().isEmpty()); + public void testFromPb() { + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + replay(dns); + assertEquals(ChangeRequest.fromPb(dns, ZONE_NAME, changeRequest.toPb()), changeRequest); + assertEquals(ChangeRequest.fromPb(dns, ZONE_NAME, changeRequestPartial.toPb()), + changeRequestPartial); } @Test - public void testRemoveAddition() { - ChangeRequest clone = CHANGE.toBuilder().removeAddition(RECORD1).build(); - assertTrue(clone.additions().contains(RECORD2)); - assertFalse(clone.additions().contains(RECORD1)); - assertTrue(clone.deletions().contains(RECORD3)); - clone = CHANGE.toBuilder().removeAddition(RECORD2).removeAddition(RECORD1).build(); - assertFalse(clone.additions().contains(RECORD2)); - assertFalse(clone.additions().contains(RECORD1)); - assertTrue(clone.additions().isEmpty()); - assertTrue(clone.deletions().contains(RECORD3)); + public void testEqualsAndToBuilder() { + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + replay(dns); + ChangeRequest compare = changeRequest.toBuilder().build(); + assertEquals(changeRequest, compare); + assertEquals(changeRequest.hashCode(), compare.hashCode()); + compare = changeRequestPartial.toBuilder().build(); + assertEquals(changeRequestPartial, compare); + assertEquals(changeRequestPartial.hashCode(), compare.hashCode()); } @Test - public void testRemoveDeletion() { - ChangeRequest clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); - assertTrue(clone.deletions().isEmpty()); + public void testBuilder() { + // one for each build() call because it invokes a constructor + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); + replay(dns); + String id = changeRequest.id() + "aaa"; + assertEquals(id, changeRequest.toBuilder().id(id).build().id()); + ChangeRequest modified = + changeRequest.toBuilder().status(ChangeRequest.Status.PENDING).build(); + assertEquals(ChangeRequest.Status.PENDING, modified.status()); + modified = changeRequest.toBuilder().clearDeletions().build(); + assertTrue(modified.deletions().isEmpty()); + modified = changeRequest.toBuilder().clearAdditions().build(); + assertTrue(modified.additions().isEmpty()); + modified = changeRequest.toBuilder().additions(ImmutableList.of()).build(); + assertTrue(modified.additions().isEmpty()); + modified = changeRequest.toBuilder().deletions(ImmutableList.of()).build(); + assertTrue(modified.deletions().isEmpty()); + RecordSet cname = RecordSet.builder("last", RecordSet.Type.CNAME).build(); + modified = changeRequest.toBuilder().add(cname).build(); + assertTrue(modified.additions().contains(cname)); + modified = changeRequest.toBuilder().delete(cname).build(); + assertTrue(modified.deletions().contains(cname)); + modified = changeRequest.toBuilder().startTimeMillis(0L).build(); + assertEquals(new Long(0), modified.startTimeMillis()); } @Test - public void testDateParsing() { - String startTime = "2016-01-26T18:33:43.512Z"; // obtained from service - com.google.api.services.dns.model.Change change = CHANGE.toPb().setStartTime(startTime); - ChangeRequest converted = ChangeRequest.fromPb(change); - assertNotNull(converted.startTimeMillis()); - assertEquals(change, converted.toPb()); - assertEquals(change.getStartTime(), converted.toPb().getStartTime()); + public void testApplyTo() { + expect(dns.applyChangeRequest(ZONE_NAME, changeRequest)).andReturn(changeRequest); + expect(dns.applyChangeRequest(ZONE_NAME, changeRequest, + Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))) + .andReturn(changeRequest); + replay(dns); + changeRequest.applyTo(); + changeRequest.applyTo(Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index ab2dba0a566c..73548e9cbb91 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -53,10 +53,10 @@ public class DnsImplTest { private static final String PAGE_TOKEN = "some token"; private static final ZoneInfo ZONE_INFO = ZoneInfo.of(ZONE_NAME, DNS_NAME, DESCRIPTION); private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); - private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequest.builder() .add(DNS_RECORD1) .build(); - private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() .add(DNS_RECORD1) .startTimeMillis(123L) .status(ChangeRequest.Status.PENDING) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java index c06cd096bf1e..4e492eff3526 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -63,7 +63,10 @@ public class SerializationTest extends BaseSerializationTest { private static final Zone FULL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(FULL_ZONE_INFO)); private static final Zone PARTIAL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(PARTIAL_ZONE_INFO)); - private static final ChangeRequest CHANGE_REQUEST_PARTIAL = ChangeRequest.builder().build(); + private static final ChangeRequestInfo CHANGE_REQUEST_INFO_PARTIAL = + ChangeRequest.builder().build(); + private static final ChangeRequest CHANGE_REQUEST_PARTIAL = new ChangeRequest(DNS, "name", + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO_PARTIAL)); private static final RecordSet RECORD_SET_PARTIAL = RecordSet.builder("www.www.com", RecordSet.Type.AAAA).build(); private static final RecordSet RECORD_SET_COMPLETE = @@ -71,13 +74,15 @@ public class SerializationTest extends BaseSerializationTest { .ttl(12, TimeUnit.HOURS) .addRecord("record") .build(); - private static final ChangeRequest CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_INFO_COMPLETE = ChangeRequest.builder() .add(RECORD_SET_COMPLETE) .delete(RECORD_SET_PARTIAL) .status(ChangeRequest.Status.PENDING) .id("some id") .startTimeMillis(132L) .build(); + private static final ChangeRequest CHANGE_REQUEST_COMPLETE = new ChangeRequest(DNS, "name", + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO_COMPLETE)); @Override protected Serializable[] serializableObjects() { @@ -91,8 +96,9 @@ protected Serializable[] serializableObjects() { return new Serializable[]{FULL_ZONE_INFO, PARTIAL_ZONE_INFO, ZONE_LIST_OPTION, RECORD_SET_LIST_OPTION, CHANGE_REQUEST_LIST_OPTION, ZONE_OPTION, CHANGE_REQUEST_OPTION, PROJECT_OPTION, PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, OPTIONS, FULL_ZONE, PARTIAL_ZONE, - OPTIONS, CHANGE_REQUEST_PARTIAL, RECORD_SET_PARTIAL, RECORD_SET_COMPLETE, - CHANGE_REQUEST_COMPLETE, options, otherOptions}; + OPTIONS, CHANGE_REQUEST_INFO_PARTIAL, CHANGE_REQUEST_PARTIAL, RECORD_SET_PARTIAL, + RECORD_SET_COMPLETE, CHANGE_REQUEST_INFO_COMPLETE, CHANGE_REQUEST_COMPLETE, options, + otherOptions}; } @Override diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index bd59f8c140e9..3ed395bf6881 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -60,25 +60,29 @@ public class ZoneTest { Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME); private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTIONS = Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME); - private static final ChangeRequest CHANGE_REQUEST = ChangeRequest.builder().id("someid").build(); - private static final ChangeRequest CHANGE_REQUEST_AFTER = CHANGE_REQUEST.toBuilder() - .startTimeMillis(123465L).build(); - private static final ChangeRequest CHANGE_REQUEST_NO_ID = ChangeRequest.builder().build(); + private static final ChangeRequestInfo CHANGE_REQUEST = + ChangeRequest.builder().id("someid").build(); + private static final ChangeRequestInfo CHANGE_REQUEST_NO_ID = + ChangeRequest.builder().build(); private static final DnsException EXCEPTION = createStrictMock(DnsException.class); private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); private Dns dns; private Zone zone; private Zone zoneNoId; + private ChangeRequest changeRequestAfter; @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); expect(dns.options()).andReturn(OPTIONS); expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS); replay(dns); zone = new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)); zoneNoId = new Zone(dns, new ZoneInfo.BuilderImpl(NO_ID_INFO)); + changeRequestAfter = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( + CHANGE_REQUEST.toBuilder().startTimeMillis(123465L).build())); reset(dns); } @@ -208,24 +212,24 @@ public void reloadByNameAndNotFound() { @Test public void applyChangeByNameAndFound() { expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); // again for options expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); replay(dns); ChangeRequest result = zoneNoId.applyChangeRequest(CHANGE_REQUEST); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); result = zone.applyChangeRequest(CHANGE_REQUEST); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); // check options result = zoneNoId.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); result = zone.applyChangeRequest(CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); } @Test @@ -298,24 +302,24 @@ public void applyNullChangeRequest() { @Test public void getChangeAndZoneFoundByName() { expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); // again for options expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(CHANGE_REQUEST_AFTER); + .andReturn(changeRequestAfter); replay(dns); ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); result = zone.getChangeRequest(CHANGE_REQUEST.id()); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); // check options result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); result = zone.getChangeRequest(CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS); - assertEquals(CHANGE_REQUEST_AFTER, result); + assertEquals(changeRequestAfter, result); } @Test diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java index 8f7626a5ae0a..dd8e21043181 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/it/ITDnsTest.java @@ -26,6 +26,7 @@ import com.google.common.collect.ImmutableList; import com.google.gcloud.Page; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsException; import com.google.gcloud.dns.DnsOptions; @@ -76,11 +77,11 @@ public class ITDnsTest { .records(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) .ttl(25, TimeUnit.SECONDS) .build(); - private static final ChangeRequest CHANGE_ADD_ZONE1 = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_ADD_ZONE1 = ChangeRequest.builder() .add(A_RECORD_ZONE1) .add(AAAA_RECORD_ZONE1) .build(); - private static final ChangeRequest CHANGE_DELETE_ZONE1 = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_DELETE_ZONE1 = ChangeRequest.builder() .delete(A_RECORD_ZONE1) .delete(AAAA_RECORD_ZONE1) .build(); @@ -593,7 +594,7 @@ public void testInvalidChangeRequest() { .records(ImmutableList.of("0.255.1.5")) .build(); try { - ChangeRequest validChange = ChangeRequest.builder().add(validA).build(); + ChangeRequestInfo validChange = ChangeRequest.builder().add(validA).build(); zone.applyChangeRequest(validChange); try { zone.applyChangeRequest(validChange); @@ -605,7 +606,7 @@ public void testInvalidChangeRequest() { } // delete with field mismatch RecordSet mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); - ChangeRequest deletion = ChangeRequest.builder().delete(mismatch).build(); + ChangeRequestInfo deletion = ChangeRequest.builder().delete(mismatch).build(); try { zone.applyChangeRequest(deletion); fail("Deleted a record set without a complete match."); @@ -629,7 +630,7 @@ public void testInvalidChangeRequest() { } } deletion = deletion.toBuilder().deletions(deletions).build(); - ChangeRequest addition = ChangeRequest.builder().additions(additions).build(); + ChangeRequestInfo addition = ChangeRequest.builder().additions(additions).build(); try { zone.applyChangeRequest(deletion); fail("Deleted SOA."); @@ -647,7 +648,7 @@ public void testInvalidChangeRequest() { assertEquals(400, ex.code()); } } finally { - ChangeRequest deletion = ChangeRequest.builder().delete(validA).build(); + ChangeRequestInfo deletion = ChangeRequest.builder().delete(validA).build(); ChangeRequest request = zone.applyChangeRequest(deletion); waitForChangeToComplete(zone.name(), request.id()); zone.delete(); From de8bf4bad79ffe422688fd69d12fa388bfb8b44d Mon Sep 17 00:00:00 2001 From: Martin Derka Date: Fri, 25 Mar 2016 09:49:23 -0700 Subject: [PATCH 74/74] Addressed comments. This includes: - Moved Status enum to ChangeRequestInfo. - Switching from ChangeRequest.builer() to ChangeRequestInfo.builder() - Fixing README accordingly - Used times() for mocking instead of repeated expect() - Snippets and documentation work with ChangeRequestInfo. Fixes #788. - Equals uses getClass instead if instanceof. - Removed unnecessary imports. --- README.md | 6 +- gcloud-java-dns/README.md | 26 ++++-- .../com/google/gcloud/dns/ChangeRequest.java | 81 ++++++++--------- .../google/gcloud/dns/ChangeRequestInfo.java | 35 +++++--- .../java/com/google/gcloud/dns/DnsImpl.java | 5 +- .../main/java/com/google/gcloud/dns/Zone.java | 2 +- .../com/google/gcloud/dns/package-info.java | 2 +- .../google/gcloud/dns/ChangeRequestTest.java | 43 ++++----- .../com/google/gcloud/dns/DnsImplTest.java | 32 ++++--- .../google/gcloud/dns/SerializationTest.java | 2 +- .../java/com/google/gcloud/dns/ZoneTest.java | 90 ++++++------------- .../gcloud/examples/dns/DnsExample.java | 11 +-- .../snippets/CreateOrUpdateRecordSets.java | 6 +- .../examples/dns/snippets/DeleteZone.java | 8 +- .../ManipulateZonesAndRecordSets.java | 9 +- 15 files changed, 171 insertions(+), 187 deletions(-) diff --git a/README.md b/README.md index 52229f6d5d34..6061d9dd4c8f 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ Zone zone = dns.create(zoneInfo); The second snippet shows how to create records inside a zone. The complete code can be found on [CreateOrUpdateRecordSets.java](./gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java). ```java -import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; import com.google.gcloud.dns.RecordSet; @@ -269,7 +269,7 @@ RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.T .ttl(24, TimeUnit.HOURS) .addRecord(ip) .build(); -ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); +ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify that the record does not exist yet. // If it does exist, we will overwrite it with our prepared record. @@ -282,7 +282,7 @@ while (recordSetIterator.hasNext()) { } } -ChangeRequest changeRequest = changeBuilder.build(); +ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); ``` diff --git a/gcloud-java-dns/README.md b/gcloud-java-dns/README.md index a2c3238d1f8f..d2e4c85b3b76 100644 --- a/gcloud-java-dns/README.md +++ b/gcloud-java-dns/README.md @@ -159,7 +159,7 @@ our zone that creates a record set of type A and points URL www.someexampledomai IP address 12.13.14.15. Start by adding ```java -import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.RecordSet; import java.util.concurrent.TimeUnit; @@ -176,7 +176,7 @@ RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A .build(); // Make a change -ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build(); +ChangeRequestInfo changeRequest = ChangeRequestInfo.builder().add(toCreate).build(); // Build and apply the change request to our zone changeRequest = zone.applyChangeRequest(changeRequest); @@ -198,7 +198,7 @@ and in the code ```java // Make a change -ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); +ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify the type A record does not exist yet. // If it does exist, we will overwrite it with our prepared record. @@ -211,7 +211,7 @@ while (recordSetIterator.hasNext()) { } // Build and apply the change request to our zone -ChangeRequest changeRequest = changeBuilder.build(); +ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); ``` 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). @@ -220,7 +220,7 @@ When the change request is applied, it is registered with the Cloud DNS service can wait for its completion as follows: ```java -while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { +while (ChangeRequestInfo.Status.PENDING.equals(changeRequest.status())) { try { Thread.sleep(500L); } catch (InterruptedException e) { @@ -262,9 +262,17 @@ while (recordSetIterator.hasNext()) { } ``` -You can also list the history of change requests that were applied to a zone: +You can also list the history of change requests that were applied to a zone. +First add: ```java +import java.util.ChangeRequest; +``` + +and then: + +```java + // List the change requests applied to a particular zone Iterator changeIterator = zone.listChangeRequests().iterateAll(); System.out.println(String.format("The history of changes in %s:", zone.name())); @@ -280,7 +288,7 @@ First, you need to empty the zone by deleting all its records except for the def ```java // Make a change for deleting the record sets -changeBuilder = ChangeRequest.builder(); +changeBuilder = ChangeRequestInfo.builder(); while (recordIterator.hasNext()) { RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted @@ -290,14 +298,14 @@ while (recordIterator.hasNext()) { } // Build and apply the change request to our zone if it contains records to delete -ChangeRequest changeRequest = changeBuilder.build(); +ChangeRequestInfo 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())) { + while (ChangeRequestInfo.Status.PENDING.equals(changeRequest.status())) { System.out.println("Waiting for change to complete. Going to sleep for 500ms..."); try { Thread.sleep(500); diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java index ad1c65f7cb0f..4b6369976ca6 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequest.java @@ -16,6 +16,8 @@ package com.google.gcloud.dns; +import static com.google.common.base.Preconditions.checkNotNull; + import com.google.api.services.dns.model.Change; import com.google.common.base.Function; @@ -25,41 +27,30 @@ import java.util.Objects; /** - * A class representing an atomic update to a collection of {@link RecordSet}s within a {@code - * Zone}. + * An immutable class representing an atomic update to a collection of {@link RecordSet}s within a + * {@code Zone}. * * @see Google Cloud DNS documentation */ public class ChangeRequest extends ChangeRequestInfo { - private static final long serialVersionUID = -9027378042756366333L; + private static final long serialVersionUID = 5335667200595081449L; private final DnsOptions options; - private final String zoneName; + private final String zone; private transient Dns dns; - /** - * This enumerates the possible states of a {@code ChangeRequest}. - * - * @see Google Cloud DNS - * documentation - */ - public enum Status { - PENDING, - DONE - } - /** * A builder for {@code ChangeRequest}s. */ public static class Builder extends ChangeRequestInfo.Builder { private final Dns dns; - private final String zoneName; + private final String zone; private final ChangeRequestInfo.BuilderImpl infoBuilder; private Builder(ChangeRequest cr) { this.dns = cr.dns; - this.zoneName = cr.zoneName; + this.zone = cr.zone; this.infoBuilder = new ChangeRequestInfo.BuilderImpl(cr); } @@ -131,45 +122,36 @@ Builder status(Status status) { @Override public ChangeRequest build() { - return new ChangeRequest(dns, zoneName, infoBuilder); + return new ChangeRequest(dns, zone, infoBuilder); } } - ChangeRequest(Dns dns, String zoneName, ChangeRequest.BuilderImpl infoBuilder) { + ChangeRequest(Dns dns, String zone, ChangeRequest.BuilderImpl infoBuilder) { super(infoBuilder); - this.zoneName = zoneName; - this.dns = dns; + this.zone = checkNotNull(zone); + this.dns = checkNotNull(dns); this.options = dns.options(); } - static Function fromPbFunction(final Dns dns, final String zoneName) { - return new Function() { - @Override - public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { - return ChangeRequest.fromPb(dns, zoneName, pb); - } - }; - } - /** * Returns the name of the {@link Zone} associated with this change request. */ - public String zoneName() { - return this.zoneName; + public String zone() { + return this.zone; } /** - * Returns the {@link Dns} service object associated with this change request. + * Returns the change request's {@code Dns} object used to issue requests. */ public Dns dns() { return dns; } /** - * Applies this change request to a zone that it is associated with. + * Applies this change request to the associated zone. */ public ChangeRequest applyTo(Dns.ChangeRequestOption... options) { - return dns.applyChangeRequest(zoneName, this, options); + return dns.applyChangeRequest(zone, this, options); } @Override @@ -179,24 +161,37 @@ public Builder toBuilder() { @Override public boolean equals(Object obj) { - return obj instanceof ChangeRequest && Objects.equals(toPb(), ((ChangeRequest) obj).toPb()) - && Objects.equals(options, ((ChangeRequest) obj).options) - && Objects.equals(zoneName, ((ChangeRequest) obj).zoneName); + if (obj == null || !obj.getClass().equals(ChangeRequest.class)) { + return false; + } else { + ChangeRequest other = (ChangeRequest) obj; + return Objects.equals(options, other.options) + && Objects.equals(zone, other.zone) + && Objects.equals(toPb(), other.toPb()); + } } @Override public int hashCode() { - return Objects.hash(super.hashCode(), options, zoneName); + return Objects.hash(super.hashCode(), options, zone); } - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); this.dns = options.service(); } - static ChangeRequest fromPb(Dns dns, String zoneName, - com.google.api.services.dns.model.Change pb) { + static ChangeRequest fromPb(Dns dns, String zoneName, Change pb) { ChangeRequestInfo info = ChangeRequestInfo.fromPb(pb); return new ChangeRequest(dns, zoneName, new ChangeRequestInfo.BuilderImpl(info)); } + + static Function fromPbFunction(final Dns dns, final String zoneName) { + return new Function() { + @Override + public ChangeRequest apply(com.google.api.services.dns.model.Change pb) { + return ChangeRequest.fromPb(dns, zoneName, pb); + } + }; + } } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java index 25b915521b13..b63b4f4a0788 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/ChangeRequestInfo.java @@ -52,7 +52,18 @@ public ChangeRequestInfo apply(Change pb) { private final List deletions; private final String id; private final Long startTimeMillis; - private final ChangeRequest.Status status; + private final ChangeRequestInfo.Status status; + + /** + * This enumerates the possible states of a change request. + * + * @see Google Cloud DNS + * documentation + */ + public enum Status { + PENDING, + DONE + } /** * A builder for {@code ChangeRequestInfo}. @@ -110,7 +121,7 @@ public abstract static class Builder { /** * Associates a server-assigned id to this {@code ChangeRequestInfo}. */ - abstract Builder id(String id); + abstract Builder id(String id); /** * Sets the time when this change request was started by a server. @@ -134,7 +145,7 @@ static class BuilderImpl extends Builder { private List deletions; private String id; private Long startTimeMillis; - private ChangeRequest.Status status; + private ChangeRequestInfo.Status status; BuilderImpl() { this.additions = new LinkedList<>(); @@ -215,7 +226,7 @@ Builder startTimeMillis(long startTimeMillis) { } @Override - Builder status(ChangeRequest.Status status) { + Builder status(ChangeRequestInfo.Status status) { this.status = checkNotNull(status); return this; } @@ -274,15 +285,15 @@ public Long startTimeMillis() { } /** - * Returns the status of this {@code ChangeRequest}. + * Returns the status of this {@code ChangeRequest}. If the change request has not been applied + * yet, the status is {@code PENDING}. */ - public ChangeRequest.Status status() { + public ChangeRequestInfo.Status status() { return status; } - com.google.api.services.dns.model.Change toPb() { - com.google.api.services.dns.model.Change pb = - new com.google.api.services.dns.model.Change(); + Change toPb() { + Change pb = new Change(); // set id if (id() != null) { pb.setId(id()); @@ -302,7 +313,7 @@ com.google.api.services.dns.model.Change toPb() { return pb; } - static ChangeRequestInfo fromPb(com.google.api.services.dns.model.Change pb) { + static ChangeRequestInfo fromPb(Change pb) { Builder builder = builder(); if (pb.getId() != null) { builder.id(pb.getId()); @@ -325,8 +336,8 @@ static ChangeRequestInfo fromPb(com.google.api.services.dns.model.Change pb) { @Override public boolean equals(Object other) { - return (other instanceof ChangeRequestInfo) - && toPb().equals(((ChangeRequestInfo) other).toPb()); + return other != null && other.getClass().equals(ChangeRequestInfo.class) + && other instanceof ChangeRequestInfo && toPb().equals(((ChangeRequestInfo) other).toPb()); } @Override diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java index 4e2bd1b207d5..51ab0bd92720 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/DnsImpl.java @@ -19,7 +19,6 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.gcloud.RetryHelper.RetryHelperException; import static com.google.gcloud.RetryHelper.runWithRetries; -import static com.google.gcloud.dns.ChangeRequest.fromPb; import com.google.api.services.dns.model.Change; import com.google.api.services.dns.model.ManagedZone; @@ -170,7 +169,7 @@ public DnsRpc.ListResult call() { Iterable changes = result.results() == null ? ImmutableList.of() : Iterables.transform(result.results(), - ChangeRequest.fromPbFunction(serviceOptions.service(), zoneName)); + ChangeRequest.fromPbFunction(serviceOptions.service(), zoneName)); return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, changes); } catch (RetryHelperException e) { @@ -285,7 +284,7 @@ public com.google.api.services.dns.model.Change call() { return dnsRpc.applyChangeRequest(zoneName, changeRequest.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER); - return answer == null ? null : fromPb(this, zoneName, answer); // should never be null + return answer == null ? null : ChangeRequest.fromPb(this, zoneName, answer); // not null } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java index 88b9e7273e9c..9930bfdbad67 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/Zone.java @@ -146,7 +146,7 @@ public Page listRecordSets(Dns.RecordSetListOption... options) { } /** - * Submits {@link ChangeRequest} to the service for it to applied to this zone. The method + * Submits {@link ChangeRequestInfo} to the service for it to applied to this zone. The method * searches for zone by name. * * @param options optional restriction on what fields of {@link ChangeRequest} should be returned diff --git a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java index 69bee930df62..36f41852400c 100644 --- a/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java +++ b/gcloud-java-dns/src/main/java/com/google/gcloud/dns/package-info.java @@ -46,7 +46,7 @@ * .ttl(24, TimeUnit.HOURS) * .addRecord(ip) * .build(); - * ChangeRequest changeRequest = ChangeRequest.builder().add(toCreate).build(); + * ChangeRequestInfo changeRequest = ChangeRequestInfo.builder().add(toCreate).build(); * zone.applyChangeRequest(changeRequest); * } * diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java index 8d6cc799cad8..bfd1d0f512f4 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ChangeRequestTest.java @@ -23,6 +23,7 @@ import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; @@ -47,8 +48,7 @@ public class ChangeRequestTest { @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(2); replay(dns); changeRequest = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( CHANGE_REQUEST_INFO.toBuilder() @@ -68,28 +68,28 @@ public void tearDown() throws Exception { @Test public void testConstructor() { + expect(dns.options()).andReturn(OPTIONS); replay(dns); - assertEquals(CHANGE_REQUEST_INFO.toPb(), changeRequestPartial.toPb()); + assertEquals(new ChangeRequest(dns, ZONE_NAME, + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO)), changeRequestPartial); assertNotNull(changeRequest.dns()); - assertEquals(ZONE_NAME, changeRequest.zoneName()); - assertNotNull(changeRequestPartial.dns()); - assertEquals(ZONE_NAME, changeRequestPartial.zoneName()); + assertEquals(ZONE_NAME, changeRequest.zone()); + assertSame(dns, changeRequestPartial.dns()); + assertEquals(ZONE_NAME, changeRequestPartial.zone()); } @Test public void testFromPb() { - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(2); replay(dns); - assertEquals(ChangeRequest.fromPb(dns, ZONE_NAME, changeRequest.toPb()), changeRequest); - assertEquals(ChangeRequest.fromPb(dns, ZONE_NAME, changeRequestPartial.toPb()), - changeRequestPartial); + assertEquals(changeRequest, ChangeRequest.fromPb(dns, ZONE_NAME, changeRequest.toPb())); + assertEquals(changeRequestPartial, + ChangeRequest.fromPb(dns, ZONE_NAME, changeRequestPartial.toPb())); } @Test public void testEqualsAndToBuilder() { - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(2); replay(dns); ChangeRequest compare = changeRequest.toBuilder().build(); assertEquals(changeRequest, compare); @@ -102,15 +102,7 @@ public void testEqualsAndToBuilder() { @Test public void testBuilder() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(9); replay(dns); String id = changeRequest.id() + "aaa"; assertEquals(id, changeRequest.toBuilder().id(id).build().id()); @@ -131,7 +123,7 @@ public void testBuilder() { modified = changeRequest.toBuilder().delete(cname).build(); assertTrue(modified.deletions().contains(cname)); modified = changeRequest.toBuilder().startTimeMillis(0L).build(); - assertEquals(new Long(0), modified.startTimeMillis()); + assertEquals(Long.valueOf(0), modified.startTimeMillis()); } @Test @@ -141,7 +133,8 @@ public void testApplyTo() { Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))) .andReturn(changeRequest); replay(dns); - changeRequest.applyTo(); - changeRequest.applyTo(Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME)); + assertSame(changeRequest, changeRequest.applyTo()); + assertSame(changeRequest, + changeRequest.applyTo(Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))); } } diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java index 73548e9cbb91..94ed4a3da3f7 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/DnsImplTest.java @@ -53,10 +53,10 @@ public class DnsImplTest { private static final String PAGE_TOKEN = "some token"; private static final ZoneInfo ZONE_INFO = ZoneInfo.of(ZONE_NAME, DNS_NAME, DESCRIPTION); private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); - private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequestInfo.builder() .add(DNS_RECORD1) .build(); - private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequestInfo.builder() .add(DNS_RECORD1) .startTimeMillis(123L) .status(ChangeRequest.Status.PENDING) @@ -221,7 +221,8 @@ public void testGetChangeRequest() { dns = options.service(); // creates DnsImpl ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_COMPLETE.id()); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); } @Test @@ -235,7 +236,8 @@ public void testGetChangeRequestWithOptions() { ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_COMPLETE.id(), CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); } @@ -248,7 +250,8 @@ public void testApplyChangeRequest() { dns = options.service(); // creates DnsImpl ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_PARTIAL); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); } @Test @@ -262,7 +265,8 @@ public void testApplyChangeRequestWithOptions() { ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); - assertEquals(CHANGE_REQUEST_COMPLETE, changeRequest); + assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); } @@ -275,8 +279,12 @@ public void testListChangeRequests() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_INFO.name()); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_COMPLETE)); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_PARTIAL)); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); } @@ -288,8 +296,12 @@ public void testListChangeRequestsWithOptions() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_NAME, CHANGE_LIST_OPTIONS); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_COMPLETE)); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains(CHANGE_REQUEST_PARTIAL)); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); + assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].rpcOption()); assertEquals(MAX_SIZE, size); diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java index 4e492eff3526..ad25b31068dd 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/SerializationTest.java @@ -74,7 +74,7 @@ public class SerializationTest extends BaseSerializationTest { .ttl(12, TimeUnit.HOURS) .addRecord("record") .build(); - private static final ChangeRequestInfo CHANGE_REQUEST_INFO_COMPLETE = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_INFO_COMPLETE = ChangeRequestInfo.builder() .add(RECORD_SET_COMPLETE) .delete(RECORD_SET_PARTIAL) .status(ChangeRequest.Status.PENDING) diff --git a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java index 3ed395bf6881..ba4493abfca8 100644 --- a/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java +++ b/gcloud-java-dns/src/test/java/com/google/gcloud/dns/ZoneTest.java @@ -61,9 +61,9 @@ public class ZoneTest { private static final Dns.ChangeRequestListOption CHANGE_REQUEST_LIST_OPTIONS = Dns.ChangeRequestListOption.fields(Dns.ChangeRequestField.START_TIME); private static final ChangeRequestInfo CHANGE_REQUEST = - ChangeRequest.builder().id("someid").build(); + ChangeRequestInfo.builder().id("someid").build(); private static final ChangeRequestInfo CHANGE_REQUEST_NO_ID = - ChangeRequest.builder().build(); + ChangeRequestInfo.builder().build(); private static final DnsException EXCEPTION = createStrictMock(DnsException.class); private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); @@ -75,9 +75,7 @@ public class ZoneTest { @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(3); replay(dns); zone = new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)); zoneNoId = new Zone(dns, new ZoneInfo.BuilderImpl(NO_ID_INFO)); @@ -101,8 +99,7 @@ public void testConstructor() { @Test public void deleteByNameAndFound() { - expect(dns.delete(ZONE_NAME)).andReturn(true); - expect(dns.delete(ZONE_NAME)).andReturn(true); + expect(dns.delete(ZONE_NAME)).andReturn(true).times(2); replay(dns); boolean result = zone.delete(); assertTrue(result); @@ -112,8 +109,7 @@ public void deleteByNameAndFound() { @Test public void deleteByNameAndNotFound() { - expect(dns.delete(ZONE_NAME)).andReturn(false); - expect(dns.delete(ZONE_NAME)).andReturn(false); + expect(dns.delete(ZONE_NAME)).andReturn(false).times(2); replay(dns); boolean result = zoneNoId.delete(); assertFalse(result); @@ -126,11 +122,9 @@ public void listDnsRecordsByNameAndFound() { @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listRecordSets(ZONE_NAME)).andReturn(pageMock); - expect(dns.listRecordSets(ZONE_NAME)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME)).andReturn(pageMock).times(2); // again for options - expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); - expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andReturn(pageMock).times(2); replay(dns); Page result = zone.listRecordSets(); assertSame(pageMock, result); @@ -143,11 +137,9 @@ public void listDnsRecordsByNameAndFound() { @Test public void listDnsRecordsByNameAndNotFound() { - expect(dns.listRecordSets(ZONE_NAME)).andThrow(EXCEPTION); - expect(dns.listRecordSets(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME)).andThrow(EXCEPTION).times(2); // again for options - expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); - expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listRecordSets(ZONE_NAME, DNS_RECORD_OPTIONS)).andThrow(EXCEPTION).times(2); replay(dns); try { zoneNoId.listRecordSets(); @@ -177,8 +169,7 @@ public void listDnsRecordsByNameAndNotFound() { @Test public void reloadByNameAndFound() { - expect(dns.getZone(ZONE_NAME)).andReturn(zone); - expect(dns.getZone(ZONE_NAME)).andReturn(zone); + expect(dns.getZone(ZONE_NAME)).andReturn(zone).times(2); // again for options expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zoneNoId); expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone); @@ -195,11 +186,9 @@ public void reloadByNameAndFound() { @Test public void reloadByNameAndNotFound() { - expect(dns.getZone(ZONE_NAME)).andReturn(null); - expect(dns.getZone(ZONE_NAME)).andReturn(null); + expect(dns.getZone(ZONE_NAME)).andReturn(null).times(2); // again for options - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); - expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null); + expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(null).times(2); replay(dns); Zone result = zoneNoId.reload(); assertNull(result); @@ -235,13 +224,10 @@ public void applyChangeByNameAndFound() { @Test public void applyChangeByNameAndNotFound() { // ID is not set - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION); - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION); + expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST)).andThrow(EXCEPTION).times(2); // again for options expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); - expect(dns.applyChangeRequest(ZONE_NAME, CHANGE_REQUEST, CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); + .andThrow(EXCEPTION).times(2); replay(dns); try { zoneNoId.applyChangeRequest(CHANGE_REQUEST); @@ -302,14 +288,10 @@ public void applyNullChangeRequest() { @Test public void getChangeAndZoneFoundByName() { expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(changeRequestAfter); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())) - .andReturn(changeRequestAfter); + .andReturn(changeRequestAfter).times(2); // again for options expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(changeRequestAfter); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(changeRequestAfter); + .andReturn(changeRequestAfter).times(2); replay(dns); ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); assertEquals(changeRequestAfter, result); @@ -324,13 +306,10 @@ public void getChangeAndZoneFoundByName() { @Test public void getChangeAndZoneNotFoundByName() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andThrow(EXCEPTION).times(2); // again for options expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andThrow(EXCEPTION); + .andThrow(EXCEPTION).times(2); replay(dns); try { zoneNoId.getChangeRequest(CHANGE_REQUEST.id()); @@ -361,13 +340,10 @@ public void getChangeAndZoneNotFoundByName() { @Test public void getChangedWhichDoesNotExistZoneFound() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id())).andReturn(null).times(2); // again for options expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.id(), CHANGE_REQUEST_FIELD_OPTIONS)) - .andReturn(null); + .andReturn(null).times(2); replay(dns); assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.id())); assertNull(zone.getChangeRequest(CHANGE_REQUEST.id())); @@ -438,13 +414,10 @@ public void listChangeRequestsAndZoneFound() { @SuppressWarnings("unchecked") Page pageMock = createStrictMock(Page.class); replay(pageMock); - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); - expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock); + expect(dns.listChangeRequests(ZONE_NAME)).andReturn(pageMock).times(2); // again for options expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) - .andReturn(pageMock); - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)) - .andReturn(pageMock); + .andReturn(pageMock).times(2); replay(dns); Page result = zoneNoId.listChangeRequests(); assertSame(pageMock, result); @@ -457,11 +430,10 @@ public void listChangeRequestsAndZoneFound() { @Test public void listChangeRequestsAndZoneNotFound() { - expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION); - expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION); + expect(dns.listChangeRequests(ZONE_NAME)).andThrow(EXCEPTION).times(2); // again for options - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION); - expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION); + expect(dns.listChangeRequests(ZONE_NAME, CHANGE_REQUEST_LIST_OPTIONS)).andThrow(EXCEPTION) + .times(2); replay(dns); try { zoneNoId.listChangeRequests(); @@ -498,8 +470,7 @@ public void testFromPb() { @Test public void testEqualsAndToBuilder() { - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(2); replay(dns); assertEquals(zone, zone.toBuilder().build()); assertEquals(zone.hashCode(), zone.toBuilder().build().hashCode()); @@ -508,14 +479,7 @@ public void testEqualsAndToBuilder() { @Test public void testBuilder() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); - expect(dns.options()).andReturn(OPTIONS); + expect(dns.options()).andReturn(OPTIONS).times(8); replay(dns); assertNotEquals(zone, zone.toBuilder() .id((new BigInteger(zone.id())).add(BigInteger.ONE).toString()) 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 40ce61b07281..a9e5c5d25377 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 @@ -19,6 +19,7 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; import com.google.gcloud.dns.ProjectInfo; @@ -207,7 +208,7 @@ public void run(Dns dns, String... args) { .records(ImmutableList.of(ip)) .ttl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequest changeRequest = ChangeRequest.builder() + ChangeRequestInfo changeRequest = ChangeRequest.builder() .delete(recordSet) .build(); changeRequest = dns.applyChangeRequest(zoneName, changeRequest); @@ -254,7 +255,7 @@ public void run(Dns dns, String... args) { .records(ImmutableList.of(ip)) .ttl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequest changeRequest = ChangeRequest.builder().add(recordSet).build(); + ChangeRequestInfo changeRequest = ChangeRequest.builder().add(recordSet).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()); @@ -444,9 +445,9 @@ private static void printZone(Zone zone) { 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; + private static ChangeRequestInfo waitForChangeToFinish(Dns dns, String zoneName, + ChangeRequestInfo request) { + ChangeRequestInfo current = request; while (current.status().equals(ChangeRequest.Status.PENDING)) { System.out.print("."); try { diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java index 74647daf666e..e3ddbb10fc0f 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/CreateOrUpdateRecordSets.java @@ -22,7 +22,7 @@ package com.google.gcloud.examples.dns.snippets; -import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; import com.google.gcloud.dns.RecordSet; @@ -55,7 +55,7 @@ public static void main(String... args) { .build(); // Make a change - ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.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. @@ -68,7 +68,7 @@ public static void main(String... args) { } // Build and apply the change request to our zone - ChangeRequest changeRequest = changeBuilder.build(); + ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); } } 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 index 27377345b62f..63f26eeebb2a 100644 --- 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 @@ -22,7 +22,7 @@ package com.google.gcloud.examples.dns.snippets; -import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; import com.google.gcloud.dns.RecordSet; @@ -47,7 +47,7 @@ public static void main(String... args) { Iterator recordIterator = dns.listRecordSets(zoneName).iterateAll(); // Make a change for deleting the records - ChangeRequest.Builder changeBuilder = ChangeRequest.builder(); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder(); while (recordIterator.hasNext()) { RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted @@ -57,14 +57,14 @@ public static void main(String... args) { } // Build and apply the change request to our zone if it contains records to delete - ChangeRequest changeRequest = changeBuilder.build(); + ChangeRequestInfo 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())) { + while (ChangeRequestInfo.Status.PENDING.equals(changeRequest.status())) { System.out.println("Waiting for change to complete. Going to sleep for 500ms..."); try { Thread.sleep(500); diff --git a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java index 6d9d09d704a6..9c9a9e77289c 100644 --- a/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java +++ b/gcloud-java-examples/src/main/java/com/google/gcloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java @@ -23,6 +23,7 @@ package com.google.gcloud.examples.dns.snippets; import com.google.gcloud.dns.ChangeRequest; +import com.google.gcloud.dns.ChangeRequestInfo; import com.google.gcloud.dns.Dns; import com.google.gcloud.dns.DnsOptions; import com.google.gcloud.dns.RecordSet; @@ -66,7 +67,7 @@ public static void main(String... args) { .build(); // Make a change - ChangeRequest.Builder changeBuilder = ChangeRequest.builder().add(toCreate); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); // Verify the type A record does not exist yet. // If it does exist, we will overwrite it with our prepared record. @@ -79,10 +80,10 @@ public static void main(String... args) { } // Build and apply the change request to our zone - ChangeRequest changeRequest = changeBuilder.build(); + ChangeRequestInfo changeRequest = changeBuilder.build(); zone.applyChangeRequest(changeRequest); - while (ChangeRequest.Status.PENDING.equals(changeRequest.status())) { + while (ChangeRequestInfo.Status.PENDING.equals(changeRequest.status())) { try { Thread.sleep(500L); } catch (InterruptedException e) { @@ -115,7 +116,7 @@ public static void main(String... args) { } // Make a change for deleting the record sets - changeBuilder = ChangeRequest.builder(); + changeBuilder = ChangeRequestInfo.builder(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); // SOA and NS records cannot be deleted